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 <cstdlib>
25 #include <cstring>
26 #include <ctime>
27 #include <iostream>
28 #include <sstream>
29 #include <string>
30 #include <sys/types.h>
31 #include <inttypes.h>
32 #include <pthread.h>
33 #include <poll.h>
34 
35 #include <android/hardware/ICamera.h>
36 #include <android/hardware/ICameraClient.h>
37 
38 #include <aidl/AidlCameraService.h>
39 #include <android-base/macros.h>
40 #include <android-base/parseint.h>
41 #include <android_companion_virtualdevice_flags.h>
42 #include <android/companion/virtualnative/IVirtualDeviceManagerNative.h>
43 #include <binder/ActivityManager.h>
44 #include <binder/AppOpsManager.h>
45 #include <binder/IPCThreadState.h>
46 #include <binder/MemoryBase.h>
47 #include <binder/MemoryHeapBase.h>
48 #include <binder/PermissionController.h>
49 #include <binder/IResultReceiver.h>
50 #include <binderthreadstate/CallerUtils.h>
51 #include <com_android_internal_camera_flags.h>
52 #include <cutils/atomic.h>
53 #include <cutils/properties.h>
54 #include <cutils/misc.h>
55 #include <gui/Surface.h>
56 #include <hardware/hardware.h>
57 #include "hidl/HidlCameraService.h"
58 #include <hidl/HidlTransportSupport.h>
59 #include <hwbinder/IPCThreadState.h>
60 #include <memunreachable/memunreachable.h>
61 #include <media/AudioSystem.h>
62 #include <media/IMediaHTTPService.h>
63 #include <media/mediaplayer.h>
64 #include <mediautils/BatteryNotifier.h>
65 #include <processinfo/ProcessInfoService.h>
66 #include <utils/Errors.h>
67 #include <utils/Log.h>
68 #include <utils/String16.h>
69 #include <utils/SystemClock.h>
70 #include <utils/Trace.h>
71 #include <utils/CallStack.h>
72 #include <private/android_filesystem_config.h>
73 #include <system/camera_vendor_tags.h>
74 #include <system/camera_metadata.h>
75 #include <binder/IServiceManager.h>
76 #include <binder/IActivityManager.h>
77 #include <camera/CameraUtils.h>
78 #include <camera/StringUtils.h>
79 
80 #include <system/camera.h>
81 
82 #include "CameraService.h"
83 #include "api1/Camera2Client.h"
84 #include "api2/CameraDeviceClient.h"
85 #include "utils/CameraServiceProxyWrapper.h"
86 #include "utils/CameraTraces.h"
87 #include "utils/SessionConfigurationUtils.h"
88 #include "utils/TagMonitor.h"
89 #include "utils/Utils.h"
90 
91 namespace {
92     const char* kPermissionServiceName = "permission";
93     const char* kActivityServiceName = "activity";
94     const char* kSensorPrivacyServiceName = "sensor_privacy";
95     const char* kAppopsServiceName = "appops";
96     const char* kProcessInfoServiceName = "processinfo";
97     const char* kVirtualDeviceBackCameraId = "0";
98     const char* kVirtualDeviceFrontCameraId = "1";
99 
getDeviceId(const android::CameraMetadata & cameraInfo)100     int32_t getDeviceId(const android::CameraMetadata& cameraInfo) {
101         if (!cameraInfo.exists(ANDROID_INFO_DEVICE_ID)) {
102             return android::kDefaultDeviceId;
103         }
104 
105         const auto &deviceIdEntry = cameraInfo.find(ANDROID_INFO_DEVICE_ID);
106         return deviceIdEntry.data.i32[0];
107     }
108 } // namespace anonymous
109 
110 namespace android {
111 
112 using namespace camera3;
113 using namespace camera3::SessionConfigurationUtils;
114 
115 using binder::Status;
116 using companion::virtualnative::IVirtualDeviceManagerNative;
117 using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService;
118 using frameworks::cameraservice::service::implementation::AidlCameraService;
119 using hardware::ICamera;
120 using hardware::ICameraClient;
121 using hardware::ICameraServiceListener;
122 using hardware::camera2::ICameraInjectionCallback;
123 using hardware::camera2::ICameraInjectionSession;
124 using hardware::camera2::utils::CameraIdAndSessionConfiguration;
125 using hardware::camera2::utils::ConcurrentCameraIdCombination;
126 
127 namespace flags = com::android::internal::camera::flags;
128 namespace vd_flags = android::companion::virtualdevice::flags;
129 
130 // ----------------------------------------------------------------------------
131 // Logging support -- this is for debugging only
132 // Use "adb shell dumpsys media.camera -v 1" to change it.
133 volatile int32_t gLogLevel = 0;
134 
135 #define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
136 #define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
137 
setLogLevel(int level)138 static void setLogLevel(int level) {
139     android_atomic_write(level, &gLogLevel);
140 }
141 
format_as(CameraService::StatusInternal s)142 int32_t format_as(CameraService::StatusInternal s) {
143   return fmt::underlying(s);
144 }
145 
146 // ----------------------------------------------------------------------------
147 
148 // Permission strings (references to AttributionAndPermissionUtils for brevity)
149 static const std::string &sDumpPermission =
150         AttributionAndPermissionUtils::sDumpPermission;
151 static const std::string &sManageCameraPermission =
152         AttributionAndPermissionUtils::sManageCameraPermission;
153 static const std::string &sCameraSendSystemEventsPermission =
154         AttributionAndPermissionUtils::sCameraSendSystemEventsPermission;
155 static const std::string &sCameraInjectExternalCameraPermission =
156         AttributionAndPermissionUtils::sCameraInjectExternalCameraPermission;
157 
158 // Constant integer for FGS Logging, used to denote the API type for logger
159 static const int LOG_FGS_CAMERA_API = 1;
160 const char *sFileName = "lastOpenSessionDumpFile";
161 static constexpr int32_t kSystemNativeClientScore = resource_policy::PERCEPTIBLE_APP_ADJ;
162 static constexpr int32_t kSystemNativeClientState =
163         ActivityManager::PROCESS_STATE_PERSISTENT_UI;
164 static const std::string kServiceName("cameraserver");
165 
166 const std::string CameraService::kOfflineDevice("offline-");
167 const std::string CameraService::kWatchAllClientsFlag("all");
168 
169 constexpr int32_t kInvalidDeviceId = -1;
170 
171 // Set to keep track of logged service error events.
172 static std::set<std::string> sServiceErrorEventSet;
173 
CameraService(std::shared_ptr<CameraServiceProxyWrapper> cameraServiceProxyWrapper,std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils)174 CameraService::CameraService(
175         std::shared_ptr<CameraServiceProxyWrapper> cameraServiceProxyWrapper,
176         std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils) :
177         AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils == nullptr ?
178                 std::make_shared<AttributionAndPermissionUtils>()\
179                 : attributionAndPermissionUtils),
180         mCameraServiceProxyWrapper(cameraServiceProxyWrapper == nullptr ?
181                 std::make_shared<CameraServiceProxyWrapper>() : cameraServiceProxyWrapper),
182         mEventLog(DEFAULT_EVENT_LOG_LENGTH),
183         mNumberOfCameras(0),
184         mNumberOfCamerasWithoutSystemCamera(0),
185         mSoundRef(0), mInitialized(false),
186         mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
187     ALOGI("CameraService started (pid=%d)", getpid());
188     mAttributionAndPermissionUtils->setCameraService(this);
189     mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
190     mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
191     if (mMemFd == -1) {
192         ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
193     }
194 }
195 
196 // Enable processes with isolated AID to request the binder
instantiate()197 void CameraService::instantiate() {
198     CameraService::publish(true);
199 }
200 
onServiceRegistration(const String16 & name,const sp<IBinder> &)201 void CameraService::onServiceRegistration(const String16& name, const sp<IBinder>&) {
202     if (name != toString16(kAppopsServiceName)) {
203         return;
204     }
205 
206     ALOGV("appops service registered. setting camera audio restriction");
207     mAppOps.setCameraAudioRestriction(mAudioRestriction);
208 }
209 
onFirstRef()210 void CameraService::onFirstRef()
211 {
212     ALOGI("CameraService process starting");
213 
214     BnCameraService::onFirstRef();
215 
216     // Update battery life tracking if service is restarting
217     BatteryNotifier& notifier(BatteryNotifier::getInstance());
218     notifier.noteResetCamera();
219     notifier.noteResetFlashlight();
220 
221     status_t res = INVALID_OPERATION;
222 
223     res = enumerateProviders();
224     if (res == OK) {
225         mInitialized = true;
226     }
227 
228     mUidPolicy = new UidPolicy(this);
229     mUidPolicy->registerSelf();
230     mSensorPrivacyPolicy = new SensorPrivacyPolicy(this, mAttributionAndPermissionUtils);
231     mSensorPrivacyPolicy->registerSelf();
232     mInjectionStatusListener = new InjectionStatusListener(this);
233 
234     // appops function setCamerAudioRestriction uses getService which
235     // is blocking till the appops service is ready. To enable early
236     // boot availability for cameraservice, use checkService which is
237     // non blocking and register for notifications
238     sp<IServiceManager> sm = defaultServiceManager();
239     sp<IBinder> binder = sm->checkService(toString16(kAppopsServiceName));
240     if (!binder) {
241         sm->registerForNotifications(toString16(kAppopsServiceName), this);
242     } else {
243         mAppOps.setCameraAudioRestriction(mAudioRestriction);
244     }
245 
246     sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
247     if (hcs->registerAsService() != android::OK) {
248         // Deprecated, so it will fail to register on newer devices
249         ALOGW("%s: Did not register default android.frameworks.cameraservice.service@2.2",
250               __FUNCTION__);
251     }
252 
253     if (!AidlCameraService::registerService(this)) {
254         ALOGE("%s: Failed to register default AIDL VNDK CameraService", __FUNCTION__);
255     }
256 
257     // This needs to be last call in this function, so that it's as close to
258     // ServiceManager::addService() as possible.
259     mCameraServiceProxyWrapper->pingCameraServiceProxy();
260     ALOGI("CameraService pinged cameraservice proxy");
261 }
262 
enumerateProviders()263 status_t CameraService::enumerateProviders() {
264     status_t res;
265 
266     std::vector<std::string> deviceIds;
267     std::unordered_map<std::string, std::set<std::string>> unavailPhysicalIds;
268     {
269         Mutex::Autolock l(mServiceLock);
270 
271         if (nullptr == mCameraProviderManager.get()) {
272             mCameraProviderManager = new CameraProviderManager();
273             res = mCameraProviderManager->initialize(this);
274             if (res != OK) {
275                 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
276                         __FUNCTION__, strerror(-res), res);
277                 logServiceError("Unable to initialize camera provider manager",
278                         ERROR_DISCONNECTED);
279                 return res;
280             }
281         }
282 
283         // Setup vendor tags before we call get_camera_info the first time
284         // because HAL might need to setup static vendor keys in get_camera_info
285         // TODO: maybe put this into CameraProviderManager::initialize()?
286         mCameraProviderManager->setUpVendorTags();
287 
288         if (nullptr == mFlashlight.get()) {
289             mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
290         }
291 
292         res = mFlashlight->findFlashUnits();
293         if (res != OK) {
294             ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
295         }
296 
297         deviceIds = mCameraProviderManager->getCameraDeviceIds(&unavailPhysicalIds);
298     }
299 
300     for (auto& cameraId : deviceIds) {
301         if (getCameraState(cameraId) == nullptr) {
302             onDeviceStatusChanged(cameraId, CameraDeviceStatus::PRESENT);
303         }
304         if (unavailPhysicalIds.count(cameraId) > 0) {
305             for (const auto& physicalId : unavailPhysicalIds[cameraId]) {
306                 onDeviceStatusChanged(cameraId, physicalId, CameraDeviceStatus::NOT_PRESENT);
307             }
308         }
309     }
310 
311     // Derive primary rear/front cameras, and filter their charactierstics.
312     // This needs to be done after all cameras are enumerated and camera ids are sorted.
313     if (SessionConfigurationUtils::IS_PERF_CLASS) {
314         // Assume internal cameras are advertised from the same
315         // provider. If multiple providers are registered at different time,
316         // and each provider contains multiple internal color cameras, the current
317         // logic may filter the characteristics of more than one front/rear color
318         // cameras.
319         Mutex::Autolock l(mServiceLock);
320         filterSPerfClassCharacteristicsLocked();
321     }
322 
323     return OK;
324 }
325 
broadcastTorchModeStatus(const std::string & cameraId,TorchModeStatus status,SystemCameraKind systemCameraKind)326 void CameraService::broadcastTorchModeStatus(const std::string& cameraId, TorchModeStatus status,
327         SystemCameraKind systemCameraKind) {
328     // Get the device id and app-visible camera id for the given HAL-visible camera id.
329     auto [deviceId, mappedCameraId] =
330             mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
331 
332     Mutex::Autolock lock(mStatusListenerLock);
333     for (auto& i : mListenerList) {
334         if (shouldSkipStatusUpdates(systemCameraKind, i->isVendorListener(), i->getListenerPid(),
335                 i->getListenerUid())) {
336             ALOGV("%s: Skipping torch callback for system-only camera device %s",
337                     __FUNCTION__, cameraId.c_str());
338             continue;
339         }
340 
341         auto ret = i->getListener()->onTorchStatusChanged(mapToInterface(status),
342                 mappedCameraId, deviceId);
343         i->handleBinderStatus(ret, "%s: Failed to trigger onTorchStatusChanged for %d:%d: %d",
344                 __FUNCTION__, i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
345     }
346 }
347 
~CameraService()348 CameraService::~CameraService() {
349     VendorTagDescriptor::clearGlobalVendorTagDescriptor();
350     mUidPolicy->unregisterSelf();
351     mSensorPrivacyPolicy->unregisterSelf();
352     mInjectionStatusListener->removeListener();
353 }
354 
onNewProviderRegistered()355 void CameraService::onNewProviderRegistered() {
356     enumerateProviders();
357 }
358 
filterAPI1SystemCameraLocked(const std::vector<std::string> & normalDeviceIds)359 void CameraService::filterAPI1SystemCameraLocked(
360         const std::vector<std::string> &normalDeviceIds) {
361     mNormalDeviceIdsWithoutSystemCamera.clear();
362     for (auto &cameraId : normalDeviceIds) {
363         if (vd_flags::camera_device_awareness()) {
364             CameraMetadata cameraInfo;
365             status_t res = mCameraProviderManager->getCameraCharacteristics(
366                     cameraId, false, &cameraInfo,
367                     hardware::ICameraService::ROTATION_OVERRIDE_NONE);
368             int32_t deviceId = kDefaultDeviceId;
369             if (res != OK) {
370                 ALOGW("%s: Not able to get camera characteristics for camera id %s",
371                       __FUNCTION__, cameraId.c_str());
372             } else {
373                 deviceId = getDeviceId(cameraInfo);
374             }
375             // Cameras associated with non-default device id's (i.e., virtual cameras) can never be
376             // system cameras, so skip for non-default device id's.
377             if (deviceId != kDefaultDeviceId) {
378                 continue;
379             }
380         }
381 
382         SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
383         if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
384             ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
385             continue;
386         }
387         if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
388             // All system camera ids will necessarily come after public camera
389             // device ids as per the HAL interface contract.
390             break;
391         }
392         mNormalDeviceIdsWithoutSystemCamera.push_back(cameraId);
393     }
394     ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
395               mNormalDeviceIdsWithoutSystemCamera.size());
396 }
397 
getSystemCameraKind(const std::string & cameraId,SystemCameraKind * kind) const398 status_t CameraService::getSystemCameraKind(const std::string& cameraId,
399         SystemCameraKind *kind) const {
400     auto state = getCameraState(cameraId);
401     if (state != nullptr) {
402         *kind = state->getSystemCameraKind();
403         return OK;
404     }
405     // Hidden physical camera ids won't have CameraState
406     return mCameraProviderManager->getSystemCameraKind(cameraId, kind);
407 }
408 
updateCameraNumAndIds()409 void CameraService::updateCameraNumAndIds() {
410     Mutex::Autolock l(mServiceLock);
411     std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
412     // Excludes hidden secure cameras
413     mNumberOfCameras =
414             systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
415     mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
416     mNormalDeviceIds =
417             mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
418     filterAPI1SystemCameraLocked(mNormalDeviceIds);
419 }
420 
filterSPerfClassCharacteristicsLocked()421 void CameraService::filterSPerfClassCharacteristicsLocked() {
422     // To claim to be S Performance primary cameras, the cameras must be
423     // backward compatible. So performance class primary camera Ids must be API1
424     // compatible.
425     bool firstRearCameraSeen = false, firstFrontCameraSeen = false;
426     for (const auto& cameraId : mNormalDeviceIdsWithoutSystemCamera) {
427         int facing = -1;
428         int orientation = 0;
429         int portraitRotation;
430         getDeviceVersion(cameraId,
431                 /*rotationOverride*/hardware::ICameraService::ROTATION_OVERRIDE_NONE,
432                 /*out*/&portraitRotation, /*out*/&facing, /*out*/&orientation);
433         if (facing == -1) {
434             ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
435             return;
436         }
437 
438         if ((facing == hardware::CAMERA_FACING_BACK && !firstRearCameraSeen) ||
439                 (facing == hardware::CAMERA_FACING_FRONT && !firstFrontCameraSeen)) {
440             status_t res = mCameraProviderManager->filterSmallJpegSizes(cameraId);
441             if (res == OK) {
442                 mPerfClassPrimaryCameraIds.insert(cameraId);
443             } else {
444                 ALOGE("%s: Failed to filter small JPEG sizes for performance class primary "
445                         "camera %s: %s(%d)", __FUNCTION__, cameraId.c_str(), strerror(-res), res);
446                 break;
447             }
448 
449             if (facing == hardware::CAMERA_FACING_BACK) {
450                 firstRearCameraSeen = true;
451             }
452             if (facing == hardware::CAMERA_FACING_FRONT) {
453                 firstFrontCameraSeen = true;
454             }
455         }
456 
457         if (firstRearCameraSeen && firstFrontCameraSeen) {
458             break;
459         }
460     }
461 }
462 
addStates(const std::string & cameraId)463 void CameraService::addStates(const std::string& cameraId) {
464     CameraResourceCost cost;
465     status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
466     if (res != OK) {
467         ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
468         return;
469     }
470     SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
471     res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
472     if (res != OK) {
473         ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
474         return;
475     }
476     std::vector<std::string> physicalCameraIds;
477     mCameraProviderManager->isLogicalCamera(cameraId, &physicalCameraIds);
478     std::set<std::string> conflicting;
479     for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
480         conflicting.emplace(cost.conflictingDevices[i]);
481     }
482 
483     {
484         Mutex::Autolock lock(mCameraStatesLock);
485         mCameraStates.emplace(cameraId, std::make_shared<CameraState>(cameraId, cost.resourceCost,
486                 conflicting, deviceKind, physicalCameraIds));
487     }
488 
489     if (mFlashlight->hasFlashUnit(cameraId)) {
490         Mutex::Autolock al(mTorchStatusMutex);
491         mTorchStatusMap.add(cameraId, TorchModeStatus::AVAILABLE_OFF);
492 
493         broadcastTorchModeStatus(cameraId, TorchModeStatus::AVAILABLE_OFF, deviceKind);
494     }
495 
496     updateCameraNumAndIds();
497     logDeviceAdded(cameraId, "Device added");
498 }
499 
removeStates(const std::string & cameraId)500 void CameraService::removeStates(const std::string& cameraId) {
501     updateCameraNumAndIds();
502     if (mFlashlight->hasFlashUnit(cameraId)) {
503         Mutex::Autolock al(mTorchStatusMutex);
504         mTorchStatusMap.removeItem(cameraId);
505     }
506 
507     {
508         Mutex::Autolock lock(mCameraStatesLock);
509         mCameraStates.erase(cameraId);
510     }
511 }
512 
onDeviceStatusChanged(const std::string & cameraId,CameraDeviceStatus newHalStatus)513 void CameraService::onDeviceStatusChanged(const std::string& cameraId,
514         CameraDeviceStatus newHalStatus) {
515     ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
516             cameraId.c_str(), newHalStatus);
517 
518     StatusInternal newStatus = mapToInternal(newHalStatus);
519 
520     std::shared_ptr<CameraState> state = getCameraState(cameraId);
521 
522     if (state == nullptr) {
523         if (newStatus == StatusInternal::PRESENT) {
524             ALOGI("%s: Unknown camera ID %s, a new camera is added",
525                     __FUNCTION__, cameraId.c_str());
526 
527             // First add as absent to make sure clients are notified below
528             addStates(cameraId);
529 
530             updateStatus(newStatus, cameraId);
531         } else {
532             ALOGE("%s: Bad camera ID %s", __FUNCTION__, cameraId.c_str());
533         }
534         return;
535     }
536 
537     StatusInternal oldStatus = state->getStatus();
538 
539     if (oldStatus == newStatus) {
540         ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
541         return;
542     }
543 
544     if (newStatus == StatusInternal::NOT_PRESENT) {
545         logDeviceRemoved(cameraId, fmt::format("Device status changed from {} to {}",
546                 oldStatus, newStatus));
547         // Set the device status to NOT_PRESENT, clients will no longer be able to connect
548         // to this device until the status changes
549         updateStatus(StatusInternal::NOT_PRESENT, cameraId);
550         mVirtualDeviceCameraIdMapper.removeCamera(cameraId);
551 
552         sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
553         {
554             // Don't do this in updateStatus to avoid deadlock over mServiceLock
555             Mutex::Autolock lock(mServiceLock);
556 
557             // Remove cached shim parameters
558             state->setShimParams(CameraParameters());
559 
560             // Remove online as well as offline client from the list of active clients,
561             // if they are present
562             clientToDisconnectOnline = removeClientLocked(cameraId);
563             clientToDisconnectOffline = removeClientLocked(kOfflineDevice + cameraId);
564         }
565 
566         disconnectClient(cameraId, clientToDisconnectOnline);
567         disconnectClient(kOfflineDevice + cameraId, clientToDisconnectOffline);
568 
569         removeStates(cameraId);
570     } else {
571         if (oldStatus == StatusInternal::NOT_PRESENT) {
572             logDeviceAdded(cameraId, fmt::format("Device status changed from {} to {}",
573                     oldStatus, newStatus));
574         }
575         updateStatus(newStatus, cameraId);
576     }
577 }
578 
onDeviceStatusChanged(const std::string & id,const std::string & physicalId,CameraDeviceStatus newHalStatus)579 void CameraService::onDeviceStatusChanged(const std::string& id,
580         const std::string& physicalId,
581         CameraDeviceStatus newHalStatus) {
582     ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
583             __FUNCTION__, id.c_str(), physicalId.c_str(), newHalStatus);
584 
585     StatusInternal newStatus = mapToInternal(newHalStatus);
586 
587     std::shared_ptr<CameraState> state = getCameraState(id);
588 
589     if (state == nullptr) {
590         ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
591                 __FUNCTION__, physicalId.c_str(), id.c_str());
592         return;
593     }
594 
595     StatusInternal logicalCameraStatus = state->getStatus();
596     if (logicalCameraStatus != StatusInternal::PRESENT &&
597             logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
598         ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
599                 __FUNCTION__, physicalId.c_str(), newHalStatus, logicalCameraStatus);
600         return;
601     }
602 
603     bool updated = false;
604     if (newStatus == StatusInternal::PRESENT) {
605         updated = state->removeUnavailablePhysicalId(physicalId);
606     } else {
607         updated = state->addUnavailablePhysicalId(physicalId);
608     }
609 
610     if (updated) {
611         std::string idCombo = id + " : " + physicalId;
612         if (newStatus == StatusInternal::PRESENT) {
613             logDeviceAdded(idCombo, fmt::format("Device status changed to {}", newStatus));
614         } else {
615             logDeviceRemoved(idCombo, fmt::format("Device status changed to {}", newStatus));
616         }
617         // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
618         SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
619         if (getSystemCameraKind(id, &deviceKind) != OK) {
620             ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.c_str());
621             return;
622         }
623         Mutex::Autolock lock(mStatusListenerLock);
624         for (auto& listener : mListenerList) {
625             if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
626                     listener->getListenerPid(), listener->getListenerUid())) {
627                 ALOGV("Skipping discovery callback for system-only camera device %s",
628                         id.c_str());
629                 continue;
630             }
631             auto ret = listener->getListener()->onPhysicalCameraStatusChanged(
632                     mapToInterface(newStatus), id, physicalId, kDefaultDeviceId);
633             listener->handleBinderStatus(ret,
634                     "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
635                     __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
636                     ret.exceptionCode());
637         }
638     }
639 }
640 
disconnectClient(const std::string & id,sp<BasicClient> clientToDisconnect)641 void CameraService::disconnectClient(const std::string& id, sp<BasicClient> clientToDisconnect) {
642     if (clientToDisconnect.get() != nullptr) {
643         ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
644                 __FUNCTION__, id.c_str());
645         // Notify the client of disconnection
646         clientToDisconnect->notifyError(
647                 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
648                 CaptureResultExtras{});
649         clientToDisconnect->disconnect();
650     }
651 }
652 
onTorchStatusChanged(const std::string & cameraId,TorchModeStatus newStatus)653 void CameraService::onTorchStatusChanged(const std::string& cameraId,
654         TorchModeStatus newStatus) {
655     SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
656     status_t res = getSystemCameraKind(cameraId, &systemCameraKind);
657     if (res != OK) {
658         ALOGE("%s: Could not get system camera kind for camera id %s", __FUNCTION__,
659                 cameraId.c_str());
660         return;
661     }
662     Mutex::Autolock al(mTorchStatusMutex);
663     onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
664 }
665 
onTorchStatusChanged(const std::string & cameraId,TorchModeStatus newStatus,SystemCameraKind systemCameraKind)666 void CameraService::onTorchStatusChanged(const std::string& cameraId,
667         TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
668     Mutex::Autolock al(mTorchStatusMutex);
669     onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
670 }
671 
broadcastTorchStrengthLevel(const std::string & cameraId,int32_t newStrengthLevel)672 void CameraService::broadcastTorchStrengthLevel(const std::string& cameraId,
673         int32_t newStrengthLevel) {
674     // Get the device id and app-visible camera id for the given HAL-visible camera id.
675     auto [deviceId, mappedCameraId] =
676             mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
677 
678     Mutex::Autolock lock(mStatusListenerLock);
679     for (auto& i : mListenerList) {
680         auto ret = i->getListener()->onTorchStrengthLevelChanged(mappedCameraId,
681                 newStrengthLevel, deviceId);
682         i->handleBinderStatus(ret,
683                 "%s: Failed to trigger onTorchStrengthLevelChanged for %d:%d: %d", __FUNCTION__,
684                 i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
685     }
686 }
687 
onTorchStatusChangedLocked(const std::string & cameraId,TorchModeStatus newStatus,SystemCameraKind systemCameraKind)688 void CameraService::onTorchStatusChangedLocked(const std::string& cameraId,
689         TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
690     ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
691             __FUNCTION__, cameraId.c_str(), newStatus);
692 
693     TorchModeStatus status;
694     status_t res = getTorchStatusLocked(cameraId, &status);
695     if (res) {
696         ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
697                 __FUNCTION__, cameraId.c_str(), strerror(-res), res);
698         return;
699     }
700     if (status == newStatus) {
701         return;
702     }
703 
704     res = setTorchStatusLocked(cameraId, newStatus);
705     if (res) {
706         ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
707                 (uint32_t)newStatus, strerror(-res), res);
708         return;
709     }
710 
711     {
712         // Update battery life logging for flashlight
713         Mutex::Autolock al(mTorchUidMapMutex);
714         auto iter = mTorchUidMap.find(cameraId);
715         if (iter != mTorchUidMap.end()) {
716             int oldUid = iter->second.second;
717             int newUid = iter->second.first;
718             BatteryNotifier& notifier(BatteryNotifier::getInstance());
719             if (oldUid != newUid) {
720                 // If the UID has changed, log the status and update current UID in mTorchUidMap
721                 if (status == TorchModeStatus::AVAILABLE_ON) {
722                     notifier.noteFlashlightOff(toString8(cameraId), oldUid);
723                 }
724                 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
725                     notifier.noteFlashlightOn(toString8(cameraId), newUid);
726                 }
727                 iter->second.second = newUid;
728             } else {
729                 // If the UID has not changed, log the status
730                 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
731                     notifier.noteFlashlightOn(toString8(cameraId), oldUid);
732                 } else {
733                     notifier.noteFlashlightOff(toString8(cameraId), oldUid);
734                 }
735             }
736         }
737     }
738     broadcastTorchModeStatus(cameraId, newStatus, systemCameraKind);
739 }
740 
isAutomotiveExteriorSystemCamera(const std::string & cam_id) const741 bool CameraService::isAutomotiveExteriorSystemCamera(const std::string& cam_id) const {
742     // Returns false if this is not an automotive device type.
743     if (!isAutomotiveDevice())
744         return false;
745 
746     // Returns false if no camera id is provided.
747     if (cam_id.empty())
748         return false;
749 
750     SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
751     if (getSystemCameraKind(cam_id, &systemCameraKind) != OK) {
752         // This isn't a known camera ID, so it's not a system camera.
753         ALOGE("%s: Unknown camera id %s, ", __FUNCTION__, cam_id.c_str());
754         return false;
755     }
756 
757     if (systemCameraKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) {
758         ALOGE("%s: camera id %s is not a system camera", __FUNCTION__, cam_id.c_str());
759         return false;
760     }
761 
762     CameraMetadata cameraInfo;
763     status_t res = mCameraProviderManager->getCameraCharacteristics(
764             cam_id, false, &cameraInfo, hardware::ICameraService::ROTATION_OVERRIDE_NONE);
765     if (res != OK){
766         ALOGE("%s: Not able to get camera characteristics for camera id %s",__FUNCTION__,
767                 cam_id.c_str());
768         return false;
769     }
770 
771     camera_metadata_entry auto_location  = cameraInfo.find(ANDROID_AUTOMOTIVE_LOCATION);
772     if (auto_location.count != 1)
773         return false;
774 
775     uint8_t location = auto_location.data.u8[0];
776     if ((location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_FRONT) &&
777             (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_REAR) &&
778             (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_LEFT) &&
779             (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_RIGHT)) {
780         return false;
781     }
782 
783     return true;
784 }
785 
getNumberOfCameras(int32_t type,int32_t deviceId,int32_t devicePolicy,int32_t * numCameras)786 Status CameraService::getNumberOfCameras(int32_t type, int32_t deviceId, int32_t devicePolicy,
787         int32_t* numCameras) {
788     ATRACE_CALL();
789     if (vd_flags::camera_device_awareness() && (deviceId != kDefaultDeviceId)
790             && (devicePolicy != IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
791         *numCameras = mVirtualDeviceCameraIdMapper.getNumberOfCameras(deviceId);
792         return Status::ok();
793     }
794 
795     Mutex::Autolock l(mServiceLock);
796     bool hasSystemCameraPermissions =
797             hasPermissionsForSystemCamera(std::string(), getCallingPid(),
798                     getCallingUid());
799     switch (type) {
800         case CAMERA_TYPE_BACKWARD_COMPATIBLE:
801             if (hasSystemCameraPermissions) {
802                 *numCameras = static_cast<int>(mNormalDeviceIds.size());
803             } else {
804                 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
805             }
806             break;
807         case CAMERA_TYPE_ALL:
808             if (hasSystemCameraPermissions) {
809                 *numCameras = mNumberOfCameras;
810             } else {
811                 *numCameras = mNumberOfCamerasWithoutSystemCamera;
812             }
813             break;
814         default:
815             ALOGW("%s: Unknown camera type %d",
816                     __FUNCTION__, type);
817             return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
818                     "Unknown camera type %d", type);
819     }
820     return Status::ok();
821 }
822 
createDefaultRequest(const std::string & unresolvedCameraId,int templateId,int32_t deviceId,int32_t devicePolicy,hardware::camera2::impl::CameraMetadataNative * request)823 Status CameraService::createDefaultRequest(const std::string& unresolvedCameraId, int templateId,
824         int32_t deviceId, int32_t devicePolicy,
825         /* out */
826         hardware::camera2::impl::CameraMetadataNative* request) {
827     ATRACE_CALL();
828 
829     if (!flags::feature_combination_query()) {
830         return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION,
831                 "Camera subsystem doesn't support this method!");
832     }
833     if (!mInitialized) {
834         ALOGE("%s: Camera subsystem is not available", __FUNCTION__);
835         logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
836         return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
837     }
838 
839     std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
840             devicePolicy);
841     if (!cameraIdOptional.has_value()) {
842         std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
843                 unresolvedCameraId.c_str(), deviceId);
844         ALOGE("%s: %s", __FUNCTION__, msg.c_str());
845         return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
846     }
847     std::string cameraId = cameraIdOptional.value();
848 
849     binder::Status res;
850     if (request == nullptr) {
851         res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
852                 "Camera %s: Error creating default request", cameraId.c_str());
853         return res;
854     }
855     camera_request_template_t tempId = camera_request_template_t::CAMERA_TEMPLATE_COUNT;
856     res = SessionConfigurationUtils::mapRequestTemplateFromClient(
857             cameraId, templateId, &tempId);
858     if (!res.isOk()) {
859         ALOGE("%s: Camera %s: failed to map request Template %d",
860                 __FUNCTION__, cameraId.c_str(), templateId);
861         return res;
862     }
863 
864     if (shouldRejectSystemCameraConnection(cameraId)) {
865         return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to create default"
866                 "request for system only device %s: ", cameraId.c_str());
867     }
868 
869     CameraMetadata metadata;
870     status_t err = mCameraProviderManager->createDefaultRequest(cameraId, tempId, &metadata);
871     if (err == OK) {
872         request->swap(metadata);
873     } else if (err == BAD_VALUE) {
874         res = STATUS_ERROR_FMT(CameraService::ERROR_ILLEGAL_ARGUMENT,
875                 "Camera %s: Template ID %d is invalid or not supported: %s (%d)",
876                 cameraId.c_str(), templateId, strerror(-err), err);
877     } else {
878         res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
879                 "Camera %s: Error creating default request for template %d: %s (%d)",
880                 cameraId.c_str(), templateId, strerror(-err), err);
881     }
882     return res;
883 }
884 
isSessionConfigurationWithParametersSupported(const std::string & unresolvedCameraId,int targetSdkVersion,const SessionConfiguration & sessionConfiguration,int32_t deviceId,int32_t devicePolicy,bool * supported)885 Status CameraService::isSessionConfigurationWithParametersSupported(
886         const std::string& unresolvedCameraId, int targetSdkVersion,
887         const SessionConfiguration& sessionConfiguration,
888         int32_t deviceId, int32_t devicePolicy,
889         /*out*/ bool* supported) {
890     ATRACE_CALL();
891 
892     if (!flags::feature_combination_query()) {
893         return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION,
894                 "Camera subsystem doesn't support this method!");
895     }
896     if (!mInitialized) {
897         ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
898         logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
899         return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
900     }
901 
902     std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
903             devicePolicy);
904     if (!cameraIdOptional.has_value()) {
905         std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
906                 unresolvedCameraId.c_str(), deviceId);
907         ALOGE("%s: %s", __FUNCTION__, msg.c_str());
908         return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
909     }
910     std::string cameraId = cameraIdOptional.value();
911 
912     if (supported == nullptr) {
913         std::string msg = fmt::sprintf("Camera %s: Invalid 'support' input!",
914                 unresolvedCameraId.c_str());
915         ALOGE("%s: %s", __FUNCTION__, msg.c_str());
916         return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
917     }
918 
919     if (shouldRejectSystemCameraConnection(cameraId)) {
920         return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query "
921                 "session configuration with parameters support for system only device %s: ",
922                 cameraId.c_str());
923     }
924 
925     bool overrideForPerfClass = flags::calculate_perf_override_during_session_support() &&
926                                 SessionConfigurationUtils::targetPerfClassPrimaryCamera(
927                                         mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
928 
929     auto ret = isSessionConfigurationWithParametersSupportedUnsafe(cameraId,
930             sessionConfiguration, overrideForPerfClass, supported);
931     if (flags::analytics_24q3()) {
932         mCameraServiceProxyWrapper->logFeatureCombinationQuery(cameraId,
933                 getCallingUid(), sessionConfiguration, ret);
934     }
935     return ret;
936 }
937 
isSessionConfigurationWithParametersSupportedUnsafe(const std::string & cameraId,const SessionConfiguration & sessionConfiguration,bool overrideForPerfClass,bool * supported)938 Status CameraService::isSessionConfigurationWithParametersSupportedUnsafe(
939         const std::string& cameraId, const SessionConfiguration& sessionConfiguration,
940         bool overrideForPerfClass, /*out*/ bool* supported) {
941     *supported = false;
942     status_t ret = mCameraProviderManager->isSessionConfigurationSupported(
943             cameraId, sessionConfiguration, overrideForPerfClass,
944             /*checkSessionParams=*/true, supported);
945     binder::Status res;
946     switch (ret) {
947         case OK:
948             // Expected. Do Nothing.
949             return Status::ok();
950         case INVALID_OPERATION: {
951                 std::string msg = fmt::sprintf(
952                         "Camera %s: Session configuration with parameters supported query not "
953                         "supported!",
954                         cameraId.c_str());
955                 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
956                 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
957                 *supported = false;
958                 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
959             }
960             break;
961         case NAME_NOT_FOUND: {
962                 std::string msg = fmt::sprintf("Camera %s: Unknown camera ID.", cameraId.c_str());
963                 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
964                 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
965                 *supported = false;
966                 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
967             }
968             break;
969         default: {
970                 std::string msg = fmt::sprintf(
971                         "Unable to retrieve session configuration support for camera "
972                         "device %s: Error: %s (%d)",
973                         cameraId.c_str(), strerror(-ret), ret);
974                 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
975                 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
976                 *supported = false;
977                 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
978             }
979             break;
980     }
981 }
982 
getSessionCharacteristics(const std::string & unresolvedCameraId,int targetSdkVersion,int rotationOverride,const SessionConfiguration & sessionConfiguration,int32_t deviceId,int32_t devicePolicy,CameraMetadata * outMetadata)983 Status CameraService::getSessionCharacteristics(const std::string& unresolvedCameraId,
984         int targetSdkVersion, int rotationOverride,
985         const SessionConfiguration& sessionConfiguration, int32_t deviceId, int32_t devicePolicy,
986         /*out*/ CameraMetadata* outMetadata) {
987     ATRACE_CALL();
988 
989     if (outMetadata == nullptr) {
990         std::string msg =
991                 fmt::sprintf("Camera %s: Invalid 'outMetadata' input!", unresolvedCameraId.c_str());
992         ALOGE("%s: %s", __FUNCTION__, msg.c_str());
993         return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
994     }
995 
996     if (!mInitialized) {
997         ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
998         logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
999         return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
1000     }
1001 
1002     std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
1003                                                                   devicePolicy);
1004     if (!cameraIdOptional.has_value()) {
1005         std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1006                                        unresolvedCameraId.c_str(), deviceId);
1007         ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1008         return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1009     }
1010     std::string cameraId = cameraIdOptional.value();
1011 
1012     if (shouldRejectSystemCameraConnection(cameraId)) {
1013         return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1014                                 "Unable to retrieve camera"
1015                                 "characteristics for system only device %s: ",
1016                                 cameraId.c_str());
1017     }
1018 
1019     bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
1020             mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
1021     if (flags::check_session_support_before_session_char()) {
1022         bool sessionConfigSupported;
1023         Status res = isSessionConfigurationWithParametersSupportedUnsafe(
1024                 cameraId, sessionConfiguration, overrideForPerfClass, &sessionConfigSupported);
1025         if (!res.isOk()) {
1026             // isSessionConfigurationWithParametersSupportedUnsafe should log what went wrong and
1027             // report the correct Status to send to the client. Simply forward the error to
1028             // the client.
1029             outMetadata->clear();
1030             return res;
1031         }
1032         if (!sessionConfigSupported) {
1033             std::string msg = fmt::sprintf(
1034                     "Session configuration not supported for camera device %s.", cameraId.c_str());
1035             outMetadata->clear();
1036             return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1037         }
1038     }
1039 
1040     status_t ret = mCameraProviderManager->getSessionCharacteristics(
1041             cameraId, sessionConfiguration, overrideForPerfClass, rotationOverride, outMetadata);
1042 
1043     switch (ret) {
1044         case OK:
1045             // Expected, no handling needed.
1046             break;
1047         case INVALID_OPERATION: {
1048                 std::string msg = fmt::sprintf(
1049                         "Camera %s: Session characteristics query not supported!",
1050                         cameraId.c_str());
1051                 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
1052                 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
1053                 outMetadata->clear();
1054                 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
1055             }
1056             break;
1057         case NAME_NOT_FOUND: {
1058                 std::string msg = fmt::sprintf(
1059                         "Camera %s: Unknown camera ID.",
1060                         cameraId.c_str());
1061                 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
1062                 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
1063                 outMetadata->clear();
1064                 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1065             }
1066             break;
1067         default: {
1068                 std::string msg = fmt::sprintf(
1069                         "Unable to retrieve session characteristics for camera device %s: "
1070                         "Error: %s (%d)",
1071                         cameraId.c_str(), strerror(-ret), ret);
1072                 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1073                 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
1074                 outMetadata->clear();
1075                 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
1076             }
1077     }
1078 
1079     Status res = filterSensitiveMetadataIfNeeded(cameraId, outMetadata);
1080     if (flags::analytics_24q3()) {
1081         mCameraServiceProxyWrapper->logSessionCharacteristicsQuery(cameraId,
1082                 getCallingUid(), sessionConfiguration, res);
1083     }
1084     return res;
1085 }
1086 
filterSensitiveMetadataIfNeeded(const std::string & cameraId,CameraMetadata * metadata)1087 Status CameraService::filterSensitiveMetadataIfNeeded(
1088         const std::string& cameraId, CameraMetadata* metadata) {
1089     int callingPid = getCallingPid();
1090     int callingUid = getCallingUid();
1091 
1092     if (callingPid == getpid()) {
1093         // Caller is cameraserver; no need to remove keys
1094         return Status::ok();
1095     }
1096 
1097     SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1098     if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1099         ALOGE("%s: Couldn't get camera kind for camera id %s", __FUNCTION__, cameraId.c_str());
1100         metadata->clear();
1101         return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1102                                 "Unable to retrieve camera kind for device %s", cameraId.c_str());
1103     }
1104     if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
1105         // Attempting to query system only camera without system camera permission would have
1106         // failed the shouldRejectSystemCameraConnection in the caller. So if we get here
1107         // for a system only camera, then the caller has the required permission.
1108         // No need to remove keys
1109         return Status::ok();
1110     }
1111 
1112     std::vector<int32_t> tagsRemoved;
1113     // Get the device id that owns this camera.
1114     auto [cameraOwnerDeviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(
1115             cameraId);
1116     bool hasCameraPermission = hasPermissionsForCamera(cameraId, callingPid, callingUid,
1117             cameraOwnerDeviceId);
1118     if (hasCameraPermission) {
1119         // Caller has camera permission; no need to remove keys
1120         return Status::ok();
1121     }
1122 
1123     status_t ret = metadata->removePermissionEntries(
1124             mCameraProviderManager->getProviderTagIdLocked(cameraId), &tagsRemoved);
1125     if (ret != OK) {
1126         metadata->clear();
1127         return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1128                                 "Failed to remove camera characteristics needing camera permission "
1129                                 "for device %s:%s (%d)",
1130                                 cameraId.c_str(), strerror(-ret), ret);
1131     }
1132 
1133     if (!tagsRemoved.empty()) {
1134         ret = metadata->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
1135                                   tagsRemoved.data(), tagsRemoved.size());
1136         if (ret != OK) {
1137             metadata->clear();
1138             return STATUS_ERROR_FMT(
1139                     ERROR_INVALID_OPERATION,
1140                     "Failed to insert camera keys needing permission for device %s: %s (%d)",
1141                     cameraId.c_str(), strerror(-ret), ret);
1142         }
1143     }
1144     return Status::ok();
1145 }
1146 
injectSessionParams(const std::string & cameraId,const CameraMetadata & sessionParams)1147 Status CameraService::injectSessionParams(
1148         const std::string& cameraId,
1149         const CameraMetadata& sessionParams) {
1150     if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
1151         const int pid = getCallingPid();
1152         const int uid = getCallingUid();
1153         ALOGE("%s: Permission Denial: can't inject session params pid=%d, uid=%d",
1154                 __FUNCTION__, pid, uid);
1155         return STATUS_ERROR(ERROR_PERMISSION_DENIED,
1156                 "Permission Denial: no permission to inject session params");
1157     }
1158 
1159     // Do not allow session params injection for a virtual camera.
1160     auto [deviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
1161     if (deviceId != kDefaultDeviceId) {
1162         return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1163                 "Cannot inject session params for a virtual camera");
1164     }
1165 
1166     std::unique_ptr<AutoConditionLock> serviceLockWrapper =
1167             AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1168 
1169     auto clientDescriptor = mActiveClientManager.get(cameraId);
1170     if (clientDescriptor == nullptr) {
1171         ALOGI("%s: No active client for camera id %s", __FUNCTION__, cameraId.c_str());
1172         return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1173                 "No active client for camera id %s", cameraId.c_str());
1174     }
1175 
1176     sp<BasicClient> clientSp = clientDescriptor->getValue();
1177     status_t res = clientSp->injectSessionParams(sessionParams);
1178 
1179     if (res != OK) {
1180         return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1181                 "Error injecting session params into camera \"%s\": %s (%d)",
1182                 cameraId.c_str(), strerror(-res), res);
1183     }
1184     return Status::ok();
1185 }
1186 
resolveCameraId(const std::string & inputCameraId,int32_t deviceId,int32_t devicePolicy)1187 std::optional<std::string> CameraService::resolveCameraId(
1188         const std::string& inputCameraId,
1189         int32_t deviceId,
1190         int32_t devicePolicy) {
1191     if ((deviceId == kDefaultDeviceId)
1192             || (devicePolicy == IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
1193         auto [storedDeviceId, _] =
1194                 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(inputCameraId);
1195         if (storedDeviceId != kDefaultDeviceId) {
1196             // Trying to access a virtual camera from default-policy device context, we should fail.
1197             std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1198                     inputCameraId.c_str(), deviceId);
1199             ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1200             return std::nullopt;
1201         }
1202         return inputCameraId;
1203     }
1204 
1205     return mVirtualDeviceCameraIdMapper.getActualCameraId(deviceId, inputCameraId);
1206 }
1207 
getCameraInfo(int cameraId,int rotationOverride,int32_t deviceId,int32_t devicePolicy,CameraInfo * cameraInfo)1208 Status CameraService::getCameraInfo(int cameraId,  int rotationOverride, int32_t deviceId,
1209         int32_t devicePolicy, CameraInfo* cameraInfo) {
1210     ATRACE_CALL();
1211     Mutex::Autolock l(mServiceLock);
1212     std::string cameraIdStr = cameraIdIntToStrLocked(cameraId, deviceId, devicePolicy);
1213     if (cameraIdStr.empty()) {
1214         std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
1215                 cameraId, deviceId);
1216         ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1217         return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1218     }
1219 
1220     if (shouldRejectSystemCameraConnection(cameraIdStr)) {
1221         return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
1222                 "characteristics for system only device %s: ", cameraIdStr.c_str());
1223     }
1224 
1225     if (!mInitialized) {
1226         logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
1227         return STATUS_ERROR(ERROR_DISCONNECTED,
1228                 "Camera subsystem is not available");
1229     }
1230     bool hasSystemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraId),
1231             getCallingPid(), getCallingUid());
1232     int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
1233     if (hasSystemCameraPermissions) {
1234         cameraIdBound = mNumberOfCameras;
1235     }
1236     if (cameraId < 0 || cameraId >= cameraIdBound) {
1237         return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1238                 "CameraId is not valid");
1239     }
1240 
1241     Status ret = Status::ok();
1242     int portraitRotation;
1243     status_t err = mCameraProviderManager->getCameraInfo(
1244             cameraIdStr, rotationOverride, &portraitRotation, cameraInfo);
1245     if (err != OK) {
1246         ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1247                 "Error retrieving camera info from device %d: %s (%d)", cameraId,
1248                 strerror(-err), err);
1249         logServiceError(std::string("Error retrieving camera info from device ")
1250                 + std::to_string(cameraId), ERROR_INVALID_OPERATION);
1251     }
1252 
1253     return ret;
1254 }
1255 
cameraIdIntToStrLocked(int cameraIdInt,int32_t deviceId,int32_t devicePolicy)1256 std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt,
1257         int32_t deviceId, int32_t devicePolicy) {
1258     if (vd_flags::camera_device_awareness() && (deviceId != kDefaultDeviceId)
1259             && (devicePolicy != IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
1260         std::optional<std::string> cameraIdOptional =
1261                 mVirtualDeviceCameraIdMapper.getActualCameraId(cameraIdInt, deviceId);
1262         return cameraIdOptional.has_value() ? cameraIdOptional.value() : std::string{};
1263     }
1264 
1265     const std::vector<std::string> *cameraIds = &mNormalDeviceIdsWithoutSystemCamera;
1266     auto callingPid = getCallingPid();
1267     auto callingUid = getCallingUid();
1268     bool systemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraIdInt),
1269             callingPid, callingUid, /* checkCameraPermissions= */ false);
1270     if (systemCameraPermissions || getpid() == callingPid) {
1271         cameraIds = &mNormalDeviceIds;
1272     }
1273     if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(cameraIds->size())) {
1274         ALOGE("%s: input id %d invalid: valid range (0, %zu)",
1275                 __FUNCTION__, cameraIdInt, cameraIds->size());
1276         return std::string{};
1277     }
1278 
1279     return (*cameraIds)[cameraIdInt];
1280 }
1281 
cameraIdIntToStr(int cameraIdInt,int32_t deviceId,int32_t devicePolicy)1282 std::string CameraService::cameraIdIntToStr(int cameraIdInt, int32_t deviceId,
1283         int32_t devicePolicy) {
1284     Mutex::Autolock lock(mServiceLock);
1285     return cameraIdIntToStrLocked(cameraIdInt, deviceId, devicePolicy);
1286 }
1287 
getCameraCharacteristics(const std::string & unresolvedCameraId,int targetSdkVersion,int rotationOverride,int32_t deviceId,int32_t devicePolicy,CameraMetadata * cameraInfo)1288 Status CameraService::getCameraCharacteristics(const std::string& unresolvedCameraId,
1289         int targetSdkVersion, int rotationOverride, int32_t deviceId, int32_t devicePolicy,
1290         CameraMetadata* cameraInfo) {
1291     ATRACE_CALL();
1292 
1293     if (!cameraInfo) {
1294         ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
1295         return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
1296     }
1297 
1298     if (!mInitialized) {
1299         ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1300         logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
1301         return STATUS_ERROR(ERROR_DISCONNECTED,
1302                 "Camera subsystem is not available");;
1303     }
1304 
1305     std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
1306             devicePolicy);
1307     if (!cameraIdOptional.has_value()) {
1308         std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1309                 unresolvedCameraId.c_str(), deviceId);
1310         ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1311         return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1312     }
1313     std::string cameraId = cameraIdOptional.value();
1314 
1315     if (shouldRejectSystemCameraConnection(cameraId)) {
1316         return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
1317                 "characteristics for system only device %s: ", cameraId.c_str());
1318     }
1319 
1320     bool overrideForPerfClass =
1321             SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
1322                     cameraId, targetSdkVersion);
1323     status_t res = mCameraProviderManager->getCameraCharacteristics(
1324             cameraId, overrideForPerfClass, cameraInfo, rotationOverride);
1325     if (res != OK) {
1326         if (res == NAME_NOT_FOUND) {
1327             return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
1328                     "characteristics for unknown device %s: %s (%d)", cameraId.c_str(),
1329                     strerror(-res), res);
1330         } else {
1331             logServiceError(fmt::sprintf("Unable to retrieve camera characteristics for device %s.",
1332                     cameraId.c_str()), ERROR_INVALID_OPERATION);
1333             return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
1334                     "characteristics for device %s: %s (%d)", cameraId.c_str(),
1335                     strerror(-res), res);
1336         }
1337     }
1338 
1339     return filterSensitiveMetadataIfNeeded(cameraId, cameraInfo);
1340 }
1341 
getTorchStrengthLevel(const std::string & unresolvedCameraId,int32_t deviceId,int32_t devicePolicy,int32_t * torchStrength)1342 Status CameraService::getTorchStrengthLevel(const std::string& unresolvedCameraId, int32_t deviceId,
1343         int32_t devicePolicy, int32_t* torchStrength) {
1344     ATRACE_CALL();
1345     Mutex::Autolock l(mServiceLock);
1346 
1347     std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
1348             devicePolicy);
1349     if (!cameraIdOptional.has_value()) {
1350         std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1351                 unresolvedCameraId.c_str(), deviceId);
1352         ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1353         return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1354     }
1355     std::string cameraId = cameraIdOptional.value();
1356 
1357     if (!mInitialized) {
1358         ALOGE("%s: Camera HAL couldn't be initialized.", __FUNCTION__);
1359         return STATUS_ERROR(ERROR_DISCONNECTED, "Camera HAL couldn't be initialized.");
1360     }
1361 
1362     if (torchStrength == NULL) {
1363         ALOGE("%s: strength level must not be null.", __FUNCTION__);
1364         return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Strength level should not be null.");
1365     }
1366 
1367     status_t res = mCameraProviderManager->getTorchStrengthLevel(cameraId, torchStrength);
1368     if (res != OK) {
1369         return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve torch "
1370             "strength level for device %s: %s (%d)", cameraId.c_str(),
1371             strerror(-res), res);
1372     }
1373     ALOGI("%s: Torch strength level is: %d", __FUNCTION__, *torchStrength);
1374     return Status::ok();
1375 }
1376 
getFormattedCurrentTime()1377 std::string CameraService::getFormattedCurrentTime() {
1378     time_t now = time(nullptr);
1379     char formattedTime[64];
1380     strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
1381     return std::string(formattedTime);
1382 }
1383 
getCameraVendorTagDescriptor(hardware::camera2::params::VendorTagDescriptor * desc)1384 Status CameraService::getCameraVendorTagDescriptor(
1385         /*out*/
1386         hardware::camera2::params::VendorTagDescriptor* desc) {
1387     ATRACE_CALL();
1388     if (!mInitialized) {
1389         ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1390         return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
1391     }
1392     sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
1393     if (globalDescriptor != nullptr) {
1394         *desc = *(globalDescriptor.get());
1395     }
1396     return Status::ok();
1397 }
1398 
getCameraVendorTagCache(hardware::camera2::params::VendorTagDescriptorCache * cache)1399 Status CameraService::getCameraVendorTagCache(
1400         /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
1401     ATRACE_CALL();
1402     if (!mInitialized) {
1403         ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1404         return STATUS_ERROR(ERROR_DISCONNECTED,
1405                 "Camera subsystem not available");
1406     }
1407     sp<VendorTagDescriptorCache> globalCache =
1408             VendorTagDescriptorCache::getGlobalVendorTagCache();
1409     if (globalCache != nullptr) {
1410         *cache = *(globalCache.get());
1411     }
1412     return Status::ok();
1413 }
1414 
clearCachedVariables()1415 void CameraService::clearCachedVariables() {
1416     BasicClient::BasicClient::sCameraService = nullptr;
1417 }
1418 
getDeviceVersion(const std::string & cameraId,int rotationOverride,int * portraitRotation,int * facing,int * orientation)1419 std::pair<int, IPCTransport> CameraService::getDeviceVersion(const std::string& cameraId,
1420         int rotationOverride, int* portraitRotation, int* facing,
1421         int* orientation) {
1422     ATRACE_CALL();
1423 
1424     int deviceVersion = 0;
1425 
1426     status_t res;
1427     hardware::hidl_version maxVersion{0,0};
1428     IPCTransport transport = IPCTransport::INVALID;
1429     res = mCameraProviderManager->getHighestSupportedVersion(cameraId, &maxVersion, &transport);
1430     if (res != OK || transport == IPCTransport::INVALID) {
1431         ALOGE("%s: Unable to get highest supported version for camera id %s", __FUNCTION__,
1432                 cameraId.c_str());
1433         return std::make_pair(-1, IPCTransport::INVALID) ;
1434     }
1435     deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
1436 
1437     hardware::CameraInfo info;
1438     if (facing) {
1439         res = mCameraProviderManager->getCameraInfo(cameraId, rotationOverride,
1440                 portraitRotation, &info);
1441         if (res != OK) {
1442             return std::make_pair(-1, IPCTransport::INVALID);
1443         }
1444         *facing = info.facing;
1445         if (orientation) {
1446             *orientation = info.orientation;
1447         }
1448     }
1449 
1450     return std::make_pair(deviceVersion, transport);
1451 }
1452 
filterGetInfoErrorCode(status_t err)1453 Status CameraService::filterGetInfoErrorCode(status_t err) {
1454     switch(err) {
1455         case NO_ERROR:
1456             return Status::ok();
1457         case BAD_VALUE:
1458             return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1459                     "CameraId is not valid for HAL module");
1460         case NO_INIT:
1461             return STATUS_ERROR(ERROR_DISCONNECTED,
1462                     "Camera device not available");
1463         default:
1464             return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1465                     "Camera HAL encountered error %d: %s",
1466                     err, strerror(-err));
1467     }
1468 }
1469 
makeClient(const sp<CameraService> & cameraService,const sp<IInterface> & cameraCb,const std::string & packageName,bool systemNativeClient,const std::optional<std::string> & featureId,const std::string & cameraId,int api1CameraId,int facing,int sensorOrientation,int clientPid,uid_t clientUid,int servicePid,std::pair<int,IPCTransport> deviceVersionAndTransport,apiLevel effectiveApiLevel,bool overrideForPerfClass,int rotationOverride,bool forceSlowJpegMode,const std::string & originalCameraId,sp<BasicClient> * client)1470 Status CameraService::makeClient(const sp<CameraService>& cameraService,
1471         const sp<IInterface>& cameraCb, const std::string& packageName, bool systemNativeClient,
1472         const std::optional<std::string>& featureId,  const std::string& cameraId,
1473         int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
1474         int servicePid, std::pair<int, IPCTransport> deviceVersionAndTransport,
1475         apiLevel effectiveApiLevel, bool overrideForPerfClass, int rotationOverride,
1476         bool forceSlowJpegMode, const std::string& originalCameraId,
1477         /*out*/sp<BasicClient>* client) {
1478     // For HIDL devices
1479     if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
1480         // Create CameraClient based on device version reported by the HAL.
1481         int deviceVersion = deviceVersionAndTransport.first;
1482         switch(deviceVersion) {
1483             case CAMERA_DEVICE_API_VERSION_1_0:
1484                 ALOGE("Camera using old HAL version: %d", deviceVersion);
1485                 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
1486                         "Camera device \"%s\" HAL version %d no longer supported",
1487                         cameraId.c_str(), deviceVersion);
1488                 break;
1489             case CAMERA_DEVICE_API_VERSION_3_0:
1490             case CAMERA_DEVICE_API_VERSION_3_1:
1491             case CAMERA_DEVICE_API_VERSION_3_2:
1492             case CAMERA_DEVICE_API_VERSION_3_3:
1493             case CAMERA_DEVICE_API_VERSION_3_4:
1494             case CAMERA_DEVICE_API_VERSION_3_5:
1495             case CAMERA_DEVICE_API_VERSION_3_6:
1496             case CAMERA_DEVICE_API_VERSION_3_7:
1497                 break;
1498             default:
1499                 // Should not be reachable
1500                 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
1501                 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1502                         "Camera device \"%s\" has unknown HAL version %d",
1503                         cameraId.c_str(), deviceVersion);
1504         }
1505     }
1506     if (effectiveApiLevel == API_1) { // Camera1 API route
1507         sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
1508         *client = new Camera2Client(cameraService, tmp, cameraService->mCameraServiceProxyWrapper,
1509                 cameraService->mAttributionAndPermissionUtils, packageName, featureId, cameraId,
1510                 api1CameraId, facing, sensorOrientation,
1511                 clientPid, clientUid, servicePid, overrideForPerfClass, rotationOverride,
1512                 forceSlowJpegMode);
1513         ALOGI("%s: Camera1 API (legacy), rotationOverride %d, forceSlowJpegMode %d",
1514                 __FUNCTION__, rotationOverride, forceSlowJpegMode);
1515     } else { // Camera2 API route
1516         sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
1517                 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
1518         *client = new CameraDeviceClient(cameraService, tmp,
1519                 cameraService->mCameraServiceProxyWrapper,
1520                 cameraService->mAttributionAndPermissionUtils, packageName, systemNativeClient,
1521                 featureId, cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid,
1522                 overrideForPerfClass, rotationOverride, originalCameraId);
1523         ALOGI("%s: Camera2 API, rotationOverride %d", __FUNCTION__, rotationOverride);
1524     }
1525     return Status::ok();
1526 }
1527 
toString(std::set<userid_t> intSet)1528 std::string CameraService::toString(std::set<userid_t> intSet) {
1529     std::ostringstream s;
1530     bool first = true;
1531     for (userid_t i : intSet) {
1532         if (first) {
1533             s << std::to_string(i);
1534             first = false;
1535         } else {
1536             s << ", " << std::to_string(i);
1537         }
1538     }
1539     return std::move(s.str());
1540 }
1541 
mapToInterface(TorchModeStatus status)1542 int32_t CameraService::mapToInterface(TorchModeStatus status) {
1543     int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1544     switch (status) {
1545         case TorchModeStatus::NOT_AVAILABLE:
1546             serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1547             break;
1548         case TorchModeStatus::AVAILABLE_OFF:
1549             serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
1550             break;
1551         case TorchModeStatus::AVAILABLE_ON:
1552             serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
1553             break;
1554         default:
1555             ALOGW("Unknown new flash status: %d", status);
1556     }
1557     return serviceStatus;
1558 }
1559 
mapToInternal(CameraDeviceStatus status)1560 CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
1561     StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
1562     switch (status) {
1563         case CameraDeviceStatus::NOT_PRESENT:
1564             serviceStatus = StatusInternal::NOT_PRESENT;
1565             break;
1566         case CameraDeviceStatus::PRESENT:
1567             serviceStatus = StatusInternal::PRESENT;
1568             break;
1569         case CameraDeviceStatus::ENUMERATING:
1570             serviceStatus = StatusInternal::ENUMERATING;
1571             break;
1572         default:
1573             ALOGW("Unknown new HAL device status: %d", status);
1574     }
1575     return serviceStatus;
1576 }
1577 
mapToInterface(StatusInternal status)1578 int32_t CameraService::mapToInterface(StatusInternal status) {
1579     int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1580     switch (status) {
1581         case StatusInternal::NOT_PRESENT:
1582             serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1583             break;
1584         case StatusInternal::PRESENT:
1585             serviceStatus = ICameraServiceListener::STATUS_PRESENT;
1586             break;
1587         case StatusInternal::ENUMERATING:
1588             serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
1589             break;
1590         case StatusInternal::NOT_AVAILABLE:
1591             serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
1592             break;
1593         case StatusInternal::UNKNOWN:
1594             serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
1595             break;
1596         default:
1597             ALOGW("Unknown new internal device status: %d", status);
1598     }
1599     return serviceStatus;
1600 }
1601 
initializeShimMetadata(int cameraId)1602 Status CameraService::initializeShimMetadata(int cameraId) {
1603     int uid = getCallingUid();
1604 
1605     std::string cameraIdStr = std::to_string(cameraId);
1606     Status ret = Status::ok();
1607     sp<Client> tmp = nullptr;
1608     if (!(ret = connectHelper<ICameraClient,Client>(
1609             sp<ICameraClient>{nullptr}, cameraIdStr, cameraId,
1610             kServiceName, /*systemNativeClient*/ false, {}, uid, USE_CALLING_PID,
1611             API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0,
1612             /*targetSdkVersion*/ __ANDROID_API_FUTURE__,
1613             /*rotationOverride*/hardware::ICameraService::ROTATION_OVERRIDE_OVERRIDE_TO_PORTRAIT,
1614             /*forceSlowJpegMode*/false, cameraIdStr, /*out*/ tmp)
1615             ).isOk()) {
1616         ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().c_str());
1617     }
1618     return ret;
1619 }
1620 
getLegacyParametersLazy(int cameraId,CameraParameters * parameters)1621 Status CameraService::getLegacyParametersLazy(int cameraId,
1622         /*out*/
1623         CameraParameters* parameters) {
1624 
1625     ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1626 
1627     Status ret = Status::ok();
1628 
1629     if (parameters == NULL) {
1630         ALOGE("%s: parameters must not be null", __FUNCTION__);
1631         return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
1632     }
1633 
1634     std::string cameraIdStr = std::to_string(cameraId);
1635 
1636     // Check if we already have parameters
1637     {
1638         // Scope for service lock
1639         Mutex::Autolock lock(mServiceLock);
1640         auto cameraState = getCameraState(cameraIdStr);
1641         if (cameraState == nullptr) {
1642             ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
1643             return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1644                     "Invalid camera ID: %s", cameraIdStr.c_str());
1645         }
1646         CameraParameters p = cameraState->getShimParams();
1647         if (!p.isEmpty()) {
1648             *parameters = p;
1649             return ret;
1650         }
1651     }
1652 
1653     int64_t token = clearCallingIdentity();
1654     ret = initializeShimMetadata(cameraId);
1655     restoreCallingIdentity(token);
1656     if (!ret.isOk()) {
1657         // Error already logged by callee
1658         return ret;
1659     }
1660 
1661     // Check for parameters again
1662     {
1663         // Scope for service lock
1664         Mutex::Autolock lock(mServiceLock);
1665         auto cameraState = getCameraState(cameraIdStr);
1666         if (cameraState == nullptr) {
1667             ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
1668             return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1669                     "Invalid camera ID: %s", cameraIdStr.c_str());
1670         }
1671         CameraParameters p = cameraState->getShimParams();
1672         if (!p.isEmpty()) {
1673             *parameters = p;
1674             return ret;
1675         }
1676     }
1677 
1678     ALOGE("%s: Parameters were not initialized, or were empty.  Device may not be present.",
1679             __FUNCTION__);
1680     return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
1681 }
1682 
validateConnectLocked(const std::string & cameraId,const std::string & clientName8,int & clientUid,int & clientPid,int & originalClientPid) const1683 Status CameraService::validateConnectLocked(const std::string& cameraId,
1684         const std::string& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
1685         /*out*/int& originalClientPid) const {
1686 
1687 #ifdef __BRILLO__
1688     UNUSED(clientName8);
1689     UNUSED(clientUid);
1690     UNUSED(clientPid);
1691     UNUSED(originalClientPid);
1692 #else
1693     Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1694             originalClientPid);
1695     if (!allowed.isOk()) {
1696         return allowed;
1697     }
1698 #endif  // __BRILLO__
1699 
1700     int callingPid = getCallingPid();
1701 
1702     if (!mInitialized) {
1703         ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1704                 callingPid);
1705         return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1706                 "No camera HAL module available to open camera device \"%s\"", cameraId.c_str());
1707     }
1708 
1709     if (getCameraState(cameraId) == nullptr) {
1710         ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1711                 cameraId.c_str());
1712         return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1713                 "No camera device with ID \"%s\" available", cameraId.c_str());
1714     }
1715 
1716     status_t err = checkIfDeviceIsUsable(cameraId);
1717     if (err != NO_ERROR) {
1718         switch(err) {
1719             case -ENODEV:
1720             case -EBUSY:
1721                 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1722                         "No camera device with ID \"%s\" currently available", cameraId.c_str());
1723             default:
1724                 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1725                         "Unknown error connecting to ID \"%s\"", cameraId.c_str());
1726         }
1727     }
1728     return Status::ok();
1729 }
1730 
validateClientPermissionsLocked(const std::string & cameraId,const std::string & clientName,int & clientUid,int & clientPid,int & originalClientPid) const1731 Status CameraService::validateClientPermissionsLocked(const std::string& cameraId,
1732         const std::string& clientName, int& clientUid, int& clientPid,
1733         /*out*/int& originalClientPid) const {
1734     int callingPid = getCallingPid();
1735     int callingUid = getCallingUid();
1736 
1737     // Check if we can trust clientUid
1738     if (clientUid == USE_CALLING_UID) {
1739         clientUid = callingUid;
1740     } else if (!isTrustedCallingUid(callingUid)) {
1741         ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1742                 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
1743         return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1744                 "Untrusted caller (calling PID %d, UID %d) trying to "
1745                 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1746                 callingPid, callingUid, cameraId.c_str(),
1747                 clientName.c_str(), clientPid, clientUid);
1748     }
1749 
1750     // Check if we can trust clientPid
1751     if (clientPid == USE_CALLING_PID) {
1752         clientPid = callingPid;
1753     } else if (!isTrustedCallingUid(callingUid)) {
1754         ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1755                 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
1756         return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1757                 "Untrusted caller (calling PID %d, UID %d) trying to "
1758                 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1759                 callingPid, callingUid, cameraId.c_str(),
1760                 clientName.c_str(), clientPid, clientUid);
1761     }
1762 
1763     if (shouldRejectSystemCameraConnection(cameraId)) {
1764         ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1765                 cameraId.c_str());
1766         return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
1767                                 "available", cameraId.c_str());
1768     }
1769     SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1770     if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1771         ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
1772         return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
1773                 "found while trying to query device kind", cameraId.c_str());
1774     }
1775 
1776     // Get the device id that owns this camera.
1777     auto [deviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
1778 
1779     // If it's not calling from cameraserver, check the permission if the
1780     // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1781     // android.permission.SYSTEM_CAMERA for system only camera devices).
1782     bool checkPermissionForCamera =
1783             hasPermissionsForCamera(cameraId, clientPid, clientUid, clientName, deviceId);
1784     if (callingPid != getpid() &&
1785                 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) && !checkPermissionForCamera) {
1786         ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
1787         return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1788                 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
1789                 clientName.c_str(), clientPid, clientUid, cameraId.c_str());
1790     }
1791 
1792     // Make sure the UID is in an active state to use the camera
1793     if (!mUidPolicy->isUidActive(callingUid, clientName)) {
1794         int32_t procState = mUidPolicy->getProcState(callingUid);
1795         ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1796             clientPid, clientUid);
1797         return STATUS_ERROR_FMT(ERROR_DISABLED,
1798                 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1799                 "calling UID %d proc state %" PRId32 ")",
1800                 clientName.c_str(), clientPid, clientUid, cameraId.c_str(),
1801                 callingUid, procState);
1802     }
1803 
1804     // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
1805     // such as rear view and surround view cannot be disabled and are exempt from sensor privacy
1806     // policy. In all other cases,if sensor privacy is enabled then prevent access to the camera.
1807     if ((!isAutomotivePrivilegedClient(callingUid) ||
1808             !isAutomotiveExteriorSystemCamera(cameraId)) &&
1809             mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1810         ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1811         return STATUS_ERROR_FMT(ERROR_DISABLED,
1812                 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
1813                 "is enabled", clientName.c_str(), clientPid, clientUid, cameraId.c_str());
1814     }
1815 
1816     // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1817     // connected to camera service directly.
1818     originalClientPid = clientPid;
1819     clientPid = callingPid;
1820 
1821     userid_t clientUserId = multiuser_get_user_id(clientUid);
1822 
1823     // For non-system clients : Only allow clients who are being used by the current foreground
1824     // device user, unless calling from our own process.
1825     if (!callerHasSystemUid() && callingPid != getpid() &&
1826             (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
1827         ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1828                 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
1829                 toString(mAllowedUsers).c_str());
1830         return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1831                 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
1832                 clientUserId, cameraId.c_str());
1833     }
1834 
1835     if (flags::camera_hsum_permission()) {
1836         // If the System User tries to access the camera when the device is running in
1837         // headless system user mode, ensure that client has the required permission
1838         // CAMERA_HEADLESS_SYSTEM_USER.
1839         if (isHeadlessSystemUserMode()
1840                 && (clientUserId == USER_SYSTEM)
1841                 && !hasPermissionsForCameraHeadlessSystemUser(cameraId, callingPid, callingUid)) {
1842             ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
1843             return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1844                     "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" as Headless System \
1845                     User without camera headless system user permission",
1846                     clientName.c_str(), clientPid, clientUid, cameraId.c_str());
1847         }
1848     }
1849 
1850     return Status::ok();
1851 }
1852 
checkIfDeviceIsUsable(const std::string & cameraId) const1853 status_t CameraService::checkIfDeviceIsUsable(const std::string& cameraId) const {
1854     auto cameraState = getCameraState(cameraId);
1855     int callingPid = getCallingPid();
1856     if (cameraState == nullptr) {
1857         ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1858                 cameraId.c_str());
1859         return -ENODEV;
1860     }
1861 
1862     StatusInternal currentStatus = cameraState->getStatus();
1863     if (currentStatus == StatusInternal::NOT_PRESENT) {
1864         ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
1865                 callingPid, cameraId.c_str());
1866         return -ENODEV;
1867     } else if (currentStatus == StatusInternal::ENUMERATING) {
1868         ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
1869                 callingPid, cameraId.c_str());
1870         return -EBUSY;
1871     }
1872 
1873     return NO_ERROR;
1874 }
1875 
finishConnectLocked(const sp<BasicClient> & client,const CameraService::DescriptorPtr & desc,int oomScoreOffset,bool systemNativeClient)1876 void CameraService::finishConnectLocked(const sp<BasicClient>& client,
1877         const CameraService::DescriptorPtr& desc, int oomScoreOffset, bool systemNativeClient) {
1878 
1879     // Make a descriptor for the incoming client
1880     auto clientDescriptor =
1881             CameraService::CameraClientManager::makeClientDescriptor(client, desc,
1882                     oomScoreOffset, systemNativeClient);
1883     auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1884 
1885     logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
1886             client->getPackageName());
1887 
1888     if (evicted.size() > 0) {
1889         // This should never happen - clients should already have been removed in disconnect
1890         for (auto& i : evicted) {
1891             ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
1892                     __FUNCTION__, i->getKey().c_str());
1893         }
1894 
1895         LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1896                 __FUNCTION__);
1897     }
1898 
1899     // And register a death notification for the client callback. Do
1900     // this last to avoid Binder policy where a nested Binder
1901     // transaction might be pre-empted to service the client death
1902     // notification if the client process dies before linkToDeath is
1903     // invoked.
1904     sp<IBinder> remoteCallback = client->getRemote();
1905     if (remoteCallback != nullptr) {
1906         remoteCallback->linkToDeath(this);
1907     }
1908 }
1909 
handleEvictionsLocked(const std::string & cameraId,int clientPid,apiLevel effectiveApiLevel,const sp<IBinder> & remoteCallback,const std::string & packageName,int oomScoreOffset,bool systemNativeClient,sp<BasicClient> * client,std::shared_ptr<resource_policy::ClientDescriptor<std::string,sp<BasicClient>>> * partial)1910 status_t CameraService::handleEvictionsLocked(const std::string& cameraId, int clientPid,
1911         apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback,
1912         const std::string& packageName, int oomScoreOffset, bool systemNativeClient,
1913         /*out*/
1914         sp<BasicClient>* client,
1915         std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>* partial) {
1916     ATRACE_CALL();
1917     status_t ret = NO_ERROR;
1918     std::vector<DescriptorPtr> evictedClients;
1919     DescriptorPtr clientDescriptor;
1920     {
1921         if (effectiveApiLevel == API_1) {
1922             // If we are using API1, any existing client for this camera ID with the same remote
1923             // should be returned rather than evicted to allow MediaRecorder to work properly.
1924 
1925             auto current = mActiveClientManager.get(cameraId);
1926             if (current != nullptr) {
1927                 auto clientSp = current->getValue();
1928                 if (clientSp.get() != nullptr) { // should never be needed
1929                     if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
1930                         ALOGW("CameraService connect called with a different"
1931                                 " API level, evicting prior client...");
1932                     } else if (clientSp->getRemote() == remoteCallback) {
1933                         ALOGI("CameraService::connect X (PID %d) (second call from same"
1934                                 " app binder, returning the same client)", clientPid);
1935                         *client = clientSp;
1936                         return NO_ERROR;
1937                     }
1938                 }
1939             }
1940         }
1941 
1942         // Get state for the given cameraId
1943         auto state = getCameraState(cameraId);
1944         if (state == nullptr) {
1945             ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1946                 clientPid, cameraId.c_str());
1947             // Should never get here because validateConnectLocked should have errored out
1948             return BAD_VALUE;
1949         }
1950 
1951         sp<IServiceManager> sm = defaultServiceManager();
1952         sp<IBinder> binder = sm->checkService(String16(kProcessInfoServiceName));
1953         if (!binder && isAutomotivePrivilegedClient(getCallingUid())) {
1954             // If processinfo service is not available and the client is automotive privileged
1955             // client used for safety critical uses cases such as rear-view and surround-view which
1956             // needs to be available before android boot completes, then use the hardcoded values
1957             // for the process state and priority score. As this scenario is before android system
1958             // services are up and client is native client, hence using NATIVE_ADJ as the priority
1959             // score and state as PROCESS_STATE_BOUND_TOP as such automotive apps need to be
1960             // visible on the top.
1961             clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1962                     sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1963                     state->getConflicting(), resource_policy::NATIVE_ADJ, clientPid,
1964                     ActivityManager::PROCESS_STATE_BOUND_TOP, oomScoreOffset, systemNativeClient);
1965         } else {
1966             // Get current active client PIDs
1967             std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1968             ownerPids.push_back(clientPid);
1969 
1970             std::vector<int> priorityScores(ownerPids.size());
1971             std::vector<int> states(ownerPids.size());
1972 
1973             // Get priority scores of all active PIDs
1974             status_t err = ProcessInfoService::getProcessStatesScoresFromPids(ownerPids.size(),
1975                     &ownerPids[0], /*out*/&states[0], /*out*/&priorityScores[0]);
1976             if (err != OK) {
1977                 ALOGE("%s: Priority score query failed: %d", __FUNCTION__, err);
1978                 return err;
1979             }
1980 
1981             // Update all active clients' priorities
1982             std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
1983             for (size_t i = 0; i < ownerPids.size() - 1; i++) {
1984                 pidToPriorityMap.emplace(ownerPids[i],
1985                         resource_policy::ClientPriority(priorityScores[i], states[i],
1986                         /* isVendorClient won't get copied over*/ false,
1987                         /* oomScoreOffset won't get copied over*/ 0));
1988             }
1989             mActiveClientManager.updatePriorities(pidToPriorityMap);
1990 
1991             int32_t actualScore = priorityScores[priorityScores.size() - 1];
1992             int32_t actualState = states[states.size() - 1];
1993 
1994             // Make descriptor for incoming client. We store the oomScoreOffset
1995             // since we might need it later on new handleEvictionsLocked and
1996             // ProcessInfoService would not take that into account.
1997             clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1998                     sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1999                     state->getConflicting(), actualScore, clientPid, actualState,
2000                     oomScoreOffset, systemNativeClient);
2001         }
2002 
2003         resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
2004 
2005         // Find clients that would be evicted
2006         auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
2007 
2008         // If the incoming client was 'evicted,' higher priority clients have the camera in the
2009         // background, so we cannot do evictions
2010         if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
2011             ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
2012                     " priority).", clientPid);
2013 
2014             sp<BasicClient> clientSp = clientDescriptor->getValue();
2015             std::string curTime = getFormattedCurrentTime();
2016             auto incompatibleClients =
2017                     mActiveClientManager.getIncompatibleClients(clientDescriptor);
2018 
2019             std::string msg = fmt::sprintf("%s : DENIED connect device %s client for package %s "
2020                     "(PID %d, score %d state %d) due to eviction policy", curTime.c_str(),
2021                     cameraId.c_str(), packageName.c_str(), clientPid,
2022                     clientPriority.getScore(), clientPriority.getState());
2023 
2024             for (auto& i : incompatibleClients) {
2025                 msg += fmt::sprintf("\n   - Blocked by existing device %s client for package %s"
2026                         "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
2027                         i->getKey().c_str(),
2028                         i->getValue()->getPackageName().c_str(),
2029                         i->getOwnerId(), i->getPriority().getScore(),
2030                         i->getPriority().getState());
2031                 ALOGE("   Conflicts with: Device %s, client package %s (PID %"
2032                         PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().c_str(),
2033                         i->getValue()->getPackageName().c_str(), i->getOwnerId(),
2034                         i->getPriority().getScore(), i->getPriority().getState());
2035             }
2036 
2037             // Log the client's attempt
2038             Mutex::Autolock l(mLogLock);
2039             mEventLog.add(msg);
2040 
2041             auto current = mActiveClientManager.get(cameraId);
2042             if (current != nullptr) {
2043                 return -EBUSY; // CAMERA_IN_USE
2044             } else {
2045                 return -EUSERS; // MAX_CAMERAS_IN_USE
2046             }
2047         }
2048 
2049         for (auto& i : evicted) {
2050             sp<BasicClient> clientSp = i->getValue();
2051             if (clientSp.get() == nullptr) {
2052                 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
2053 
2054                 // TODO: Remove this
2055                 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
2056                         __FUNCTION__);
2057                 mActiveClientManager.remove(i);
2058                 continue;
2059             }
2060 
2061             ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
2062                     i->getKey().c_str());
2063             evictedClients.push_back(i);
2064 
2065             // Log the clients evicted
2066             logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID"
2067                     " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
2068                     " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
2069                     i->getKey().c_str(), clientSp->getPackageName().c_str(),
2070                     i->getOwnerId(), i->getPriority().getScore(),
2071                     i->getPriority().getState(), cameraId.c_str(),
2072                     packageName.c_str(), clientPid, clientPriority.getScore(),
2073                     clientPriority.getState()));
2074 
2075             // Notify the client of disconnection
2076             clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
2077                     CaptureResultExtras());
2078         }
2079     }
2080 
2081     // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2082     // other clients from connecting in mServiceLockWrapper if held
2083     mServiceLock.unlock();
2084 
2085     // Clear caller identity temporarily so client disconnect PID checks work correctly
2086     int64_t token = clearCallingIdentity();
2087 
2088     // Destroy evicted clients
2089     for (auto& i : evictedClients) {
2090         // Disconnect is blocking, and should only have returned when HAL has cleaned up
2091         i->getValue()->disconnect(); // Clients will remove themselves from the active client list
2092     }
2093 
2094     restoreCallingIdentity(token);
2095 
2096     for (const auto& i : evictedClients) {
2097         ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
2098                 __FUNCTION__, i->getKey().c_str(), i->getOwnerId());
2099         ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
2100         if (ret == TIMED_OUT) {
2101             ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
2102                     "current clients:\n%s", __FUNCTION__, i->getKey().c_str(),
2103                     mActiveClientManager.toString().c_str());
2104             return -EBUSY;
2105         }
2106         if (ret != NO_ERROR) {
2107             ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
2108                     "current clients:\n%s", __FUNCTION__, i->getKey().c_str(), strerror(-ret),
2109                     ret, mActiveClientManager.toString().c_str());
2110             return ret;
2111         }
2112     }
2113 
2114     evictedClients.clear();
2115 
2116     // Once clients have been disconnected, relock
2117     mServiceLock.lock();
2118 
2119     // Check again if the device was unplugged or something while we weren't holding mServiceLock
2120     if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
2121         return ret;
2122     }
2123 
2124     *partial = clientDescriptor;
2125     return NO_ERROR;
2126 }
2127 
connect(const sp<ICameraClient> & cameraClient,int api1CameraId,const std::string & clientPackageName,int clientUid,int clientPid,int targetSdkVersion,int rotationOverride,bool forceSlowJpegMode,int32_t deviceId,int32_t devicePolicy,sp<ICamera> * device)2128 Status CameraService::connect(
2129         const sp<ICameraClient>& cameraClient,
2130         int api1CameraId,
2131         const std::string& clientPackageName,
2132         int clientUid,
2133         int clientPid,
2134         int targetSdkVersion,
2135         int rotationOverride,
2136         bool forceSlowJpegMode,
2137         int32_t deviceId,
2138         int32_t devicePolicy,
2139         /*out*/
2140         sp<ICamera>* device) {
2141     ATRACE_CALL();
2142     Status ret = Status::ok();
2143 
2144     std::string cameraIdStr = cameraIdIntToStr(api1CameraId, deviceId, devicePolicy);
2145     if (cameraIdStr.empty()) {
2146         std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
2147                 api1CameraId, deviceId);
2148         ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2149         return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2150     }
2151 
2152     sp<Client> client = nullptr;
2153     ret = connectHelper<ICameraClient,Client>(cameraClient, cameraIdStr, api1CameraId,
2154             clientPackageName, /*systemNativeClient*/ false, {}, clientUid, clientPid, API_1,
2155             /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion,
2156             rotationOverride, forceSlowJpegMode, cameraIdStr, /*out*/client);
2157 
2158     if (!ret.isOk()) {
2159         logRejected(cameraIdStr, getCallingPid(), clientPackageName, toStdString(ret.toString8()));
2160         return ret;
2161     }
2162 
2163     *device = client;
2164 
2165     const sp<IServiceManager> sm(defaultServiceManager());
2166     const auto& mActivityManager = getActivityManager();
2167     if (mActivityManager) {
2168         mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
2169             getCallingUid(),
2170             getCallingPid());
2171     }
2172 
2173     return ret;
2174 }
2175 
shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,bool isVendorListener,int clientPid,int clientUid)2176 bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
2177         bool isVendorListener, int clientPid, int clientUid) {
2178     // If the client is not a vendor client, don't add listener if
2179     //   a) the camera is a publicly hidden secure camera OR
2180     //   b) the camera is a system only camera and the client doesn't
2181     //      have android.permission.SYSTEM_CAMERA permissions.
2182     if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
2183             (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
2184             !hasPermissionsForSystemCamera(std::string(), clientPid, clientUid)))) {
2185         return true;
2186     }
2187     return false;
2188 }
2189 
shouldRejectSystemCameraConnection(const std::string & cameraId) const2190 bool CameraService::shouldRejectSystemCameraConnection(const std::string& cameraId) const {
2191     // Rules for rejection:
2192     // 1) If cameraserver tries to access this camera device, accept the
2193     //    connection.
2194     // 2) The camera device is a publicly hidden secure camera device AND some
2195     //    non system component is trying to access it.
2196     // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
2197     //    and the serving thread is a non hwbinder thread, the client must have
2198     //    android.permission.SYSTEM_CAMERA permissions to connect.
2199 
2200     int cPid = getCallingPid();
2201     int cUid = getCallingUid();
2202     bool systemClient = callerHasSystemUid();
2203     SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
2204     if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
2205         // This isn't a known camera ID, so it's not a system camera
2206         ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
2207         return false;
2208     }
2209 
2210     // (1) Cameraserver trying to connect, accept.
2211     if (isCallerCameraServerNotDelegating()) {
2212         return false;
2213     }
2214     // (2)
2215     if (!systemClient && systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
2216         ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
2217         return true;
2218     }
2219     // (3) Here we only check for permissions if it is a system only camera device. This is since
2220     //     getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
2221     //     characteristics) even if clients don't have android.permission.CAMERA. We do not want the
2222     //     same behavior for system camera devices.
2223     if (!systemClient && systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
2224             !hasPermissionsForSystemCamera(cameraId, cPid, cUid)) {
2225         ALOGW("Rejecting access to system only camera %s, inadequete permissions",
2226                 cameraId.c_str());
2227         return true;
2228     }
2229 
2230     return false;
2231 }
2232 
connectDevice(const sp<hardware::camera2::ICameraDeviceCallbacks> & cameraCb,const std::string & unresolvedCameraId,const std::string & clientPackageName,const std::optional<std::string> & clientFeatureId,int clientUid,int oomScoreOffset,int targetSdkVersion,int rotationOverride,int32_t deviceId,int32_t devicePolicy,sp<hardware::camera2::ICameraDeviceUser> * device)2233 Status CameraService::connectDevice(
2234         const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
2235         const std::string& unresolvedCameraId,
2236         const std::string& clientPackageName,
2237         const std::optional<std::string>& clientFeatureId,
2238         int clientUid, int oomScoreOffset, int targetSdkVersion,
2239         int rotationOverride, int32_t deviceId, int32_t devicePolicy,
2240         /*out*/
2241         sp<hardware::camera2::ICameraDeviceUser>* device) {
2242     ATRACE_CALL();
2243     RunThreadWithRealtimePriority priorityBump;
2244     Status ret = Status::ok();
2245     sp<CameraDeviceClient> client = nullptr;
2246     std::string clientPackageNameAdj = clientPackageName;
2247     int callingPid = getCallingPid();
2248     int callingUid = getCallingUid();
2249     bool systemNativeClient = false;
2250     if (callerHasSystemUid() && (clientPackageNameAdj.size() == 0)) {
2251         std::string systemClient = fmt::sprintf("client.pid<%d>", callingPid);
2252         clientPackageNameAdj = systemClient;
2253         systemNativeClient = true;
2254     }
2255 
2256     std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
2257             devicePolicy);
2258     if (!cameraIdOptional.has_value()) {
2259         std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
2260                 unresolvedCameraId.c_str(), deviceId);
2261         ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2262         return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2263     }
2264     std::string cameraId = cameraIdOptional.value();
2265 
2266     if (oomScoreOffset < 0) {
2267         std::string msg =
2268                 fmt::sprintf("Cannot increase the priority of a client %s pid %d for "
2269                         "camera id %s", clientPackageNameAdj.c_str(), callingPid,
2270                         cameraId.c_str());
2271         ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2272         return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2273     }
2274 
2275     userid_t clientUserId = multiuser_get_user_id(clientUid);
2276     if (clientUid == USE_CALLING_UID) {
2277         clientUserId = multiuser_get_user_id(callingUid);
2278     }
2279 
2280     // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
2281     // such as rear view and surround view cannot be disabled.
2282     if ((!isAutomotivePrivilegedClient(callingUid) || !isAutomotiveExteriorSystemCamera(cameraId))
2283             && mCameraServiceProxyWrapper->isCameraDisabled(clientUserId)) {
2284         std::string msg = "Camera disabled by device policy";
2285         ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2286         return STATUS_ERROR(ERROR_DISABLED, msg.c_str());
2287     }
2288 
2289     // enforce system camera permissions
2290     if (oomScoreOffset > 0
2291             && !hasPermissionsForSystemCamera(cameraId, callingPid,
2292                     callingUid)
2293             && !isTrustedCallingUid(callingUid)) {
2294         std::string msg = fmt::sprintf("Cannot change the priority of a client %s pid %d for "
2295                         "camera id %s without SYSTEM_CAMERA permissions",
2296                         clientPackageNameAdj.c_str(), callingPid, cameraId.c_str());
2297         ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2298         return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.c_str());
2299     }
2300 
2301     ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb,
2302             cameraId, /*api1CameraId*/-1, clientPackageNameAdj, systemNativeClient, clientFeatureId,
2303             clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, oomScoreOffset,
2304             targetSdkVersion, rotationOverride, /*forceSlowJpegMode*/false, unresolvedCameraId,
2305             /*out*/client);
2306 
2307     if (!ret.isOk()) {
2308         logRejected(cameraId, callingPid, clientPackageNameAdj, toStdString(ret.toString8()));
2309         return ret;
2310     }
2311 
2312     *device = client;
2313     Mutex::Autolock lock(mServiceLock);
2314 
2315     // Clear the previous cached logs and reposition the
2316     // file offset to beginning of the file to log new data.
2317     // If either truncate or lseek fails, close the previous file and create a new one.
2318     if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
2319         ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
2320         // Close the previous memfd.
2321         close(mMemFd);
2322         // If failure to wipe the data, then create a new file and
2323         // assign the new value to mMemFd.
2324         mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
2325         if (mMemFd == -1) {
2326             ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
2327         }
2328     }
2329     const sp<IServiceManager> sm(defaultServiceManager());
2330     const auto& mActivityManager = getActivityManager();
2331     if (mActivityManager) {
2332         mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
2333             callingUid,
2334             callingPid);
2335     }
2336     return ret;
2337 }
2338 
isCameraPrivacyEnabled(const String16 & packageName,const std::string & cam_id,int callingPid,int callingUid)2339 bool CameraService::isCameraPrivacyEnabled(const String16& packageName, const std::string& cam_id,
2340         int callingPid, int callingUid) {
2341     if (!isAutomotiveDevice()) {
2342         return mSensorPrivacyPolicy->isCameraPrivacyEnabled();
2343     }
2344 
2345     // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for
2346     // safety-critical use cases cannot be disabled and are exempt from camera privacy policy.
2347     if ((isAutomotivePrivilegedClient(callingUid) && isAutomotiveExteriorSystemCamera(cam_id))) {
2348         ALOGI("Camera privacy cannot be enabled for automotive privileged client %d "
2349                 "using camera %s", callingUid, cam_id.c_str());
2350         return false;
2351     }
2352 
2353     if (mSensorPrivacyPolicy->isCameraPrivacyEnabled(packageName)) {
2354         return true;
2355     } else if (mSensorPrivacyPolicy->getCameraPrivacyState() == SensorPrivacyManager::DISABLED) {
2356         return false;
2357     } else if (mSensorPrivacyPolicy->getCameraPrivacyState()
2358             == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
2359         if (hasPermissionsForCameraPrivacyAllowlist(callingPid, callingUid)) {
2360             return false;
2361         } else {
2362             return true;
2363         }
2364     }
2365     return false;
2366 }
2367 
getPackageNameFromUid(int clientUid)2368 std::string CameraService::getPackageNameFromUid(int clientUid) {
2369     std::string packageName("");
2370 
2371     sp<IPermissionController> permCtrl;
2372     if (flags::cache_permission_services()) {
2373         permCtrl = getPermissionController();
2374     } else {
2375         sp<IServiceManager> sm = defaultServiceManager();
2376 #pragma clang diagnostic push
2377 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
2378         // Using deprecated function to preserve functionality until the
2379         // cache_permission_services flag is removed.
2380         sp<IBinder> binder = sm->getService(toString16(kPermissionServiceName));
2381 #pragma clang diagnostic pop
2382         if (binder == 0) {
2383             ALOGE("Cannot get permission service");
2384             permCtrl = nullptr;
2385         } else {
2386             permCtrl = interface_cast<IPermissionController>(binder);
2387         }
2388     }
2389 
2390     if (permCtrl == nullptr) {
2391         // Return empty package name and the further interaction
2392         // with camera will likely fail
2393         return packageName;
2394     }
2395 
2396     Vector<String16> packages;
2397 
2398     permCtrl->getPackagesForUid(clientUid, packages);
2399 
2400     if (packages.isEmpty()) {
2401         ALOGE("No packages for calling UID %d", clientUid);
2402         // Return empty package name and the further interaction
2403         // with camera will likely fail
2404         return packageName;
2405     }
2406 
2407     // Arbitrarily pick the first name in the list
2408     packageName = toStdString(packages[0]);
2409 
2410     return packageName;
2411 }
2412 
2413 template<class CALLBACK, class CLIENT>
connectHelper(const sp<CALLBACK> & cameraCb,const std::string & cameraId,int api1CameraId,const std::string & clientPackageNameMaybe,bool systemNativeClient,const std::optional<std::string> & clientFeatureId,int clientUid,int clientPid,apiLevel effectiveApiLevel,bool shimUpdateOnly,int oomScoreOffset,int targetSdkVersion,int rotationOverride,bool forceSlowJpegMode,const std::string & originalCameraId,sp<CLIENT> & device)2414 Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const std::string& cameraId,
2415         int api1CameraId, const std::string& clientPackageNameMaybe, bool systemNativeClient,
2416         const std::optional<std::string>& clientFeatureId, int clientUid, int clientPid,
2417         apiLevel effectiveApiLevel, bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
2418         int rotationOverride, bool forceSlowJpegMode,
2419         const std::string& originalCameraId, /*out*/sp<CLIENT>& device) {
2420     binder::Status ret = binder::Status::ok();
2421 
2422     bool isNonSystemNdk = false;
2423     std::string clientPackageName;
2424     int packageUid = (clientUid == USE_CALLING_UID) ?
2425             getCallingUid() : clientUid;
2426     if (clientPackageNameMaybe.size() <= 0) {
2427         // NDK calls don't come with package names, but we need one for various cases.
2428         // Generally, there's a 1:1 mapping between UID and package name, but shared UIDs
2429         // do exist. For all authentication cases, all packages under the same UID get the
2430         // same permissions, so picking any associated package name is sufficient. For some
2431         // other cases, this may give inaccurate names for clients in logs.
2432         isNonSystemNdk = true;
2433         clientPackageName = getPackageNameFromUid(packageUid);
2434     } else {
2435         clientPackageName = clientPackageNameMaybe;
2436     }
2437 
2438     int originalClientPid = 0;
2439 
2440     int packagePid = (clientPid == USE_CALLING_PID) ?
2441         getCallingPid() : clientPid;
2442     ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
2443             "Camera API version %d", packagePid, clientPackageName.c_str(), cameraId.c_str(),
2444             static_cast<int>(effectiveApiLevel));
2445 
2446     nsecs_t openTimeNs = systemTime();
2447 
2448     sp<CLIENT> client = nullptr;
2449     int facing = -1;
2450     int orientation = 0;
2451 
2452     {
2453         // Acquire mServiceLock and prevent other clients from connecting
2454         std::unique_ptr<AutoConditionLock> lock =
2455                 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2456 
2457         if (lock == nullptr) {
2458             ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
2459                     , clientPid);
2460             return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2461                     "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
2462                     cameraId.c_str(), clientPackageName.c_str(), clientPid);
2463         }
2464 
2465         // Enforce client permissions and do basic validity checks
2466         if (!(ret = validateConnectLocked(cameraId, clientPackageName,
2467                 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
2468             return ret;
2469         }
2470 
2471         // Check the shim parameters after acquiring lock, if they have already been updated and
2472         // we were doing a shim update, return immediately
2473         if (shimUpdateOnly) {
2474             auto cameraState = getCameraState(cameraId);
2475             if (cameraState != nullptr) {
2476                 if (!cameraState->getShimParams().isEmpty()) return ret;
2477             }
2478         }
2479 
2480         status_t err;
2481 
2482         sp<BasicClient> clientTmp = nullptr;
2483         std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>> partial;
2484         if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
2485                 IInterface::asBinder(cameraCb), clientPackageName, oomScoreOffset,
2486                 systemNativeClient, /*out*/&clientTmp, /*out*/&partial)) != NO_ERROR) {
2487             switch (err) {
2488                 case -ENODEV:
2489                     return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2490                             "No camera device with ID \"%s\" currently available",
2491                             cameraId.c_str());
2492                 case -EBUSY:
2493                     return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2494                             "Higher-priority client using camera, ID \"%s\" currently unavailable",
2495                             cameraId.c_str());
2496                 case -EUSERS:
2497                     return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2498                             "Too many cameras already open, cannot open camera \"%s\"",
2499                             cameraId.c_str());
2500                 default:
2501                     return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2502                             "Unexpected error %s (%d) opening camera \"%s\"",
2503                             strerror(-err), err, cameraId.c_str());
2504             }
2505         }
2506 
2507         if (clientTmp.get() != nullptr) {
2508             // Handle special case for API1 MediaRecorder where the existing client is returned
2509             device = static_cast<CLIENT*>(clientTmp.get());
2510             return ret;
2511         }
2512 
2513         // give flashlight a chance to close devices if necessary.
2514         mFlashlight->prepareDeviceOpen(cameraId);
2515 
2516         int portraitRotation;
2517         auto deviceVersionAndTransport =
2518                 getDeviceVersion(cameraId, rotationOverride, /*out*/&portraitRotation,
2519                         /*out*/&facing, /*out*/&orientation);
2520         if (facing == -1) {
2521             ALOGE("%s: Unable to get camera device \"%s\"  facing", __FUNCTION__, cameraId.c_str());
2522             return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2523                     "Unable to get camera device \"%s\" facing", cameraId.c_str());
2524         }
2525 
2526         sp<BasicClient> tmp = nullptr;
2527         bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
2528                 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
2529 
2530         if(!(ret = makeClient(this, cameraCb, clientPackageName, systemNativeClient,
2531                 clientFeatureId, cameraId, api1CameraId, facing,
2532                 orientation, clientPid, clientUid, getpid(),
2533                 deviceVersionAndTransport, effectiveApiLevel, overrideForPerfClass,
2534                 rotationOverride, forceSlowJpegMode, originalCameraId,
2535                 /*out*/&tmp)).isOk()) {
2536             return ret;
2537         }
2538         client = static_cast<CLIENT*>(tmp.get());
2539 
2540         LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
2541                 __FUNCTION__);
2542 
2543         std::string monitorTags = isClientWatched(client.get()) ? mMonitorTags : std::string();
2544         err = client->initialize(mCameraProviderManager, monitorTags);
2545         if (err != OK) {
2546             ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
2547             // Errors could be from the HAL module open call or from AppOpsManager
2548             mServiceLock.unlock();
2549             client->disconnect();
2550             mServiceLock.lock();
2551             switch(err) {
2552                 case BAD_VALUE:
2553                     return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2554                             "Illegal argument to HAL module for camera \"%s\"", cameraId.c_str());
2555                 case -EBUSY:
2556                     return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2557                             "Camera \"%s\" is already open", cameraId.c_str());
2558                 case -EUSERS:
2559                     return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2560                             "Too many cameras already open, cannot open camera \"%s\"",
2561                             cameraId.c_str());
2562                 case PERMISSION_DENIED:
2563                     return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2564                             "No permission to open camera \"%s\"", cameraId.c_str());
2565                 case -EACCES:
2566                     return STATUS_ERROR_FMT(ERROR_DISABLED,
2567                             "Camera \"%s\" disabled by policy", cameraId.c_str());
2568                 case -ENODEV:
2569                 default:
2570                     return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2571                             "Failed to initialize camera \"%s\": %s (%d)", cameraId.c_str(),
2572                             strerror(-err), err);
2573             }
2574         }
2575 
2576         // Update shim paremeters for legacy clients
2577         if (effectiveApiLevel == API_1) {
2578             // Assume we have always received a Client subclass for API1
2579             sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
2580             String8 rawParams = shimClient->getParameters();
2581             CameraParameters params(rawParams);
2582 
2583             auto cameraState = getCameraState(cameraId);
2584             if (cameraState != nullptr) {
2585                 cameraState->setShimParams(params);
2586             } else {
2587                 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
2588                         __FUNCTION__, cameraId.c_str());
2589             }
2590         }
2591 
2592         // Enable/disable camera service watchdog
2593         client->setCameraServiceWatchdog(mCameraServiceWatchdogEnabled);
2594 
2595         CameraMetadata chars;
2596         bool rotateAndCropSupported = true;
2597         err = mCameraProviderManager->getCameraCharacteristics(cameraId, overrideForPerfClass,
2598                 &chars, rotationOverride);
2599         if (err == OK) {
2600             auto availableRotateCropEntry = chars.find(
2601                     ANDROID_SCALER_AVAILABLE_ROTATE_AND_CROP_MODES);
2602             if (availableRotateCropEntry.count <= 1) {
2603                 rotateAndCropSupported = false;
2604             }
2605         } else {
2606             ALOGE("%s: Unable to query static metadata for camera %s: %s (%d)", __FUNCTION__,
2607                     cameraId.c_str(), strerror(-err), err);
2608         }
2609 
2610         if (rotateAndCropSupported) {
2611             // Set rotate-and-crop override behavior
2612             if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2613                 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
2614             } else if (rotationOverride != hardware::ICameraService::ROTATION_OVERRIDE_NONE &&
2615                     portraitRotation != 0) {
2616                 uint8_t rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_AUTO;
2617                 switch (portraitRotation) {
2618                     case 90:
2619                         rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_90;
2620                         break;
2621                     case 180:
2622                         rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_180;
2623                         break;
2624                     case 270:
2625                         rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_270;
2626                         break;
2627                     default:
2628                         ALOGE("Unexpected portrait rotation: %d", portraitRotation);
2629                         break;
2630                 }
2631                 // Here we're communicating to the client the chosen rotate
2632                 // and crop mode to send to the HAL
2633                 client->setRotateAndCropOverride(rotateAndCropMode);
2634             } else {
2635                 client->setRotateAndCropOverride(
2636                     mCameraServiceProxyWrapper->getRotateAndCropOverride(
2637                         clientPackageName, facing, multiuser_get_user_id(clientUid)));
2638             }
2639         }
2640 
2641         bool autoframingSupported = true;
2642         auto availableAutoframingEntry = chars.find(ANDROID_CONTROL_AUTOFRAMING_AVAILABLE);
2643         if ((availableAutoframingEntry.count == 1) && (availableAutoframingEntry.data.u8[0] ==
2644                     ANDROID_CONTROL_AUTOFRAMING_AVAILABLE_FALSE)) {
2645             autoframingSupported = false;
2646         }
2647 
2648         if (autoframingSupported) {
2649             // Set autoframing override behaviour
2650             if (mOverrideAutoframingMode != ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2651                 client->setAutoframingOverride(mOverrideAutoframingMode);
2652             } else {
2653                 client->setAutoframingOverride(
2654                     mCameraServiceProxyWrapper->getAutoframingOverride(
2655                         clientPackageName));
2656             }
2657         }
2658 
2659         bool isCameraPrivacyEnabled;
2660         if (flags::camera_privacy_allowlist()) {
2661             // Set camera muting behavior.
2662             isCameraPrivacyEnabled = this->isCameraPrivacyEnabled(
2663                     toString16(client->getPackageName()), cameraId, packagePid, packageUid);
2664         } else {
2665             isCameraPrivacyEnabled =
2666                     mSensorPrivacyPolicy->isCameraPrivacyEnabled();
2667         }
2668 
2669         if (client->supportsCameraMute()) {
2670             client->setCameraMute(
2671                     mOverrideCameraMuteMode || isCameraPrivacyEnabled);
2672         } else if (isCameraPrivacyEnabled) {
2673             // no camera mute supported, but privacy is on! => disconnect
2674             ALOGI("Camera mute not supported for package: %s, camera id: %s",
2675                     client->getPackageName().c_str(), cameraId.c_str());
2676             // Do not hold mServiceLock while disconnecting clients, but
2677             // retain the condition blocking other clients from connecting
2678             // in mServiceLockWrapper if held.
2679             mServiceLock.unlock();
2680             // Clear caller identity temporarily so client disconnect PID
2681             // checks work correctly
2682             int64_t token = clearCallingIdentity();
2683             // Note AppOp to trigger the "Unblock" dialog
2684             client->noteAppOp();
2685             client->disconnect();
2686             restoreCallingIdentity(token);
2687             // Reacquire mServiceLock
2688             mServiceLock.lock();
2689 
2690             return STATUS_ERROR_FMT(ERROR_DISABLED,
2691                     "Camera \"%s\" disabled due to camera mute", cameraId.c_str());
2692         }
2693 
2694         if (shimUpdateOnly) {
2695             // If only updating legacy shim parameters, immediately disconnect client
2696             mServiceLock.unlock();
2697             client->disconnect();
2698             mServiceLock.lock();
2699         } else {
2700             // Otherwise, add client to active clients list
2701             finishConnectLocked(client, partial, oomScoreOffset, systemNativeClient);
2702         }
2703 
2704         client->setImageDumpMask(mImageDumpMask);
2705         client->setStreamUseCaseOverrides(mStreamUseCaseOverrides);
2706         client->setZoomOverride(mZoomOverrideValue);
2707     } // lock is destroyed, allow further connect calls
2708 
2709     // Important: release the mutex here so the client can call back into the service from its
2710     // destructor (can be at the end of the call)
2711     device = client;
2712 
2713     int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
2714     mCameraServiceProxyWrapper->logOpen(cameraId, facing, clientPackageName,
2715             effectiveApiLevel, isNonSystemNdk, openLatencyMs);
2716 
2717     {
2718         Mutex::Autolock lock(mInjectionParametersLock);
2719         if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
2720             mInjectionInitPending = false;
2721             status_t res = NO_ERROR;
2722             auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2723             if (clientDescriptor != nullptr) {
2724                 sp<BasicClient> clientSp = clientDescriptor->getValue();
2725                 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2726                 if(res != OK) {
2727                     return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2728                             "No camera device with ID \"%s\" currently available",
2729                             mInjectionExternalCamId.c_str());
2730                 }
2731                 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
2732                 if (res != OK) {
2733                     mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2734                 }
2735             } else {
2736                 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
2737                         __FUNCTION__, mInjectionInternalCamId.c_str());
2738                 res = NO_INIT;
2739                 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2740             }
2741         }
2742     }
2743 
2744     return ret;
2745 }
2746 
addOfflineClient(const std::string & cameraId,sp<BasicClient> offlineClient)2747 status_t CameraService::addOfflineClient(const std::string &cameraId,
2748         sp<BasicClient> offlineClient) {
2749     if (offlineClient.get() == nullptr) {
2750         return BAD_VALUE;
2751     }
2752 
2753     {
2754         // Acquire mServiceLock and prevent other clients from connecting
2755         std::unique_ptr<AutoConditionLock> lock =
2756                 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2757 
2758         if (lock == nullptr) {
2759             ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
2760                     , __FUNCTION__, offlineClient->getClientPid());
2761             return TIMED_OUT;
2762         }
2763 
2764         auto onlineClientDesc = mActiveClientManager.get(cameraId);
2765         if (onlineClientDesc.get() == nullptr) {
2766             ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
2767                     cameraId.c_str());
2768             return BAD_VALUE;
2769         }
2770 
2771         // Offline clients do not evict or conflict with other online devices. Resource sharing
2772         // conflicts are handled by the camera provider which will either succeed or fail before
2773         // reaching this method.
2774         const auto& onlinePriority = onlineClientDesc->getPriority();
2775         auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
2776                 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
2777                 /*conflictingKeys*/ std::set<std::string>(), onlinePriority.getScore(),
2778                 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
2779                 // native clients don't have offline processing support.
2780                 /*ommScoreOffset*/ 0, /*systemNativeClient*/false);
2781         if (offlineClientDesc == nullptr) {
2782             ALOGE("%s: Offline client descriptor was NULL", __FUNCTION__);
2783             return BAD_VALUE;
2784         }
2785 
2786         // Allow only one offline device per camera
2787         auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
2788         if (!incompatibleClients.empty()) {
2789             ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
2790             return BAD_VALUE;
2791         }
2792 
2793         std::string monitorTags = isClientWatched(offlineClient.get())
2794                 ? mMonitorTags : std::string();
2795         auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
2796         if (err != OK) {
2797             ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
2798             return err;
2799         }
2800 
2801         auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
2802         if (evicted.size() > 0) {
2803             for (auto& i : evicted) {
2804                 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
2805                         __FUNCTION__, i->getKey().c_str());
2806             }
2807 
2808             LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
2809                     "properly", __FUNCTION__);
2810 
2811             return BAD_VALUE;
2812         }
2813 
2814         logConnectedOffline(offlineClientDesc->getKey(),
2815                 static_cast<int>(offlineClientDesc->getOwnerId()),
2816                 offlineClient->getPackageName());
2817 
2818         sp<IBinder> remoteCallback = offlineClient->getRemote();
2819         if (remoteCallback != nullptr) {
2820             remoteCallback->linkToDeath(this);
2821         }
2822     } // lock is destroyed, allow further connect calls
2823 
2824     return OK;
2825 }
2826 
turnOnTorchWithStrengthLevel(const std::string & unresolvedCameraId,int32_t torchStrength,const sp<IBinder> & clientBinder,int32_t deviceId,int32_t devicePolicy)2827 Status CameraService::turnOnTorchWithStrengthLevel(const std::string& unresolvedCameraId,
2828         int32_t torchStrength, const sp<IBinder>& clientBinder, int32_t deviceId,
2829         int32_t devicePolicy) {
2830     Mutex::Autolock lock(mServiceLock);
2831 
2832     ATRACE_CALL();
2833     if (clientBinder == nullptr) {
2834         ALOGE("%s: torch client binder is NULL", __FUNCTION__);
2835         return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2836                 "Torch client binder in null.");
2837     }
2838 
2839     int uid = getCallingUid();
2840     std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
2841             devicePolicy);
2842     if (!cameraIdOptional.has_value()) {
2843         std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
2844                 unresolvedCameraId.c_str(), deviceId);
2845         ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2846         return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2847     }
2848     std::string cameraId = cameraIdOptional.value();
2849 
2850     if (shouldRejectSystemCameraConnection(cameraId)) {
2851         return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to change the strength level"
2852                 "for system only device %s: ", cameraId.c_str());
2853     }
2854 
2855     // verify id is valid
2856     auto state = getCameraState(cameraId);
2857     if (state == nullptr) {
2858         ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
2859         return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2860             "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
2861     }
2862 
2863     StatusInternal cameraStatus = state->getStatus();
2864     if (cameraStatus != StatusInternal::NOT_AVAILABLE &&
2865             cameraStatus != StatusInternal::PRESENT) {
2866         ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
2867             (int)cameraStatus);
2868         return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2869                 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
2870     }
2871 
2872     {
2873         Mutex::Autolock al(mTorchStatusMutex);
2874         TorchModeStatus status;
2875         status_t err = getTorchStatusLocked(cameraId, &status);
2876         if (err != OK) {
2877             if (err == NAME_NOT_FOUND) {
2878              return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2879                     "Camera \"%s\" does not have a flash unit", cameraId.c_str());
2880             }
2881             ALOGE("%s: getting current torch status failed for camera %s",
2882                     __FUNCTION__, cameraId.c_str());
2883             return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2884                     "Error changing torch strength level for camera \"%s\": %s (%d)",
2885                     cameraId.c_str(), strerror(-err), err);
2886         }
2887 
2888         if (status == TorchModeStatus::NOT_AVAILABLE) {
2889             if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
2890                 ALOGE("%s: torch mode of camera %s is not available because "
2891                         "camera is in use.", __FUNCTION__, cameraId.c_str());
2892                 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2893                         "Torch for camera \"%s\" is not available due to an existing camera user",
2894                         cameraId.c_str());
2895             } else {
2896                 ALOGE("%s: torch mode of camera %s is not available due to "
2897                        "insufficient resources", __FUNCTION__, cameraId.c_str());
2898                 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2899                         "Torch for camera \"%s\" is not available due to insufficient resources",
2900                         cameraId.c_str());
2901             }
2902         }
2903     }
2904 
2905     {
2906         Mutex::Autolock al(mTorchUidMapMutex);
2907         updateTorchUidMapLocked(cameraId, uid);
2908     }
2909     // Check if the current torch strength level is same as the new one.
2910     bool shouldSkipTorchStrengthUpdates = mCameraProviderManager->shouldSkipTorchStrengthUpdate(
2911             cameraId, torchStrength);
2912 
2913     status_t err = mFlashlight->turnOnTorchWithStrengthLevel(cameraId, torchStrength);
2914 
2915     if (err != OK) {
2916         int32_t errorCode;
2917         std::string msg;
2918         switch (err) {
2919             case -ENOSYS:
2920                 msg = fmt::sprintf("Camera \"%s\" has no flashlight.",
2921                     cameraId.c_str());
2922                 errorCode = ERROR_ILLEGAL_ARGUMENT;
2923                 break;
2924             case -EBUSY:
2925                 msg = fmt::sprintf("Camera \"%s\" is in use",
2926                     cameraId.c_str());
2927                 errorCode = ERROR_CAMERA_IN_USE;
2928                 break;
2929             case -EINVAL:
2930                 msg = fmt::sprintf("Torch strength level %d is not within the "
2931                         "valid range.", torchStrength);
2932                 errorCode = ERROR_ILLEGAL_ARGUMENT;
2933                 break;
2934             default:
2935                 msg = "Changing torch strength level failed.";
2936                 errorCode = ERROR_INVALID_OPERATION;
2937         }
2938         ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2939         return STATUS_ERROR(errorCode, msg.c_str());
2940     }
2941 
2942     {
2943         // update the link to client's death
2944         // Store the last client that turns on each camera's torch mode.
2945         Mutex::Autolock al(mTorchClientMapMutex);
2946         ssize_t index = mTorchClientMap.indexOfKey(cameraId);
2947         if (index == NAME_NOT_FOUND) {
2948             mTorchClientMap.add(cameraId, clientBinder);
2949         } else {
2950             mTorchClientMap.valueAt(index)->unlinkToDeath(this);
2951             mTorchClientMap.replaceValueAt(index, clientBinder);
2952         }
2953         clientBinder->linkToDeath(this);
2954     }
2955 
2956     int clientPid = getCallingPid();
2957     ALOGI("%s: Torch strength for camera id %s changed to %d for client PID %d",
2958             __FUNCTION__, cameraId.c_str(), torchStrength, clientPid);
2959     if (!shouldSkipTorchStrengthUpdates) {
2960         broadcastTorchStrengthLevel(cameraId, torchStrength);
2961     }
2962     return Status::ok();
2963 }
2964 
setTorchMode(const std::string & unresolvedCameraId,bool enabled,const sp<IBinder> & clientBinder,int32_t deviceId,int32_t devicePolicy)2965 Status CameraService::setTorchMode(const std::string& unresolvedCameraId, bool enabled,
2966         const sp<IBinder>& clientBinder, int32_t deviceId, int32_t devicePolicy) {
2967     Mutex::Autolock lock(mServiceLock);
2968 
2969     ATRACE_CALL();
2970     if (enabled && clientBinder == nullptr) {
2971         ALOGE("%s: torch client binder is NULL", __FUNCTION__);
2972         return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2973                 "Torch client Binder is null");
2974     }
2975 
2976     int uid = getCallingUid();
2977     std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
2978             devicePolicy);
2979     if (!cameraIdOptional.has_value()) {
2980         std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
2981                 unresolvedCameraId.c_str(), deviceId);
2982         ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2983         return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2984     }
2985     std::string cameraId = cameraIdOptional.value();
2986 
2987     if (shouldRejectSystemCameraConnection(cameraId)) {
2988         return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
2989                 " for system only device %s: ", cameraId.c_str());
2990     }
2991     // verify id is valid.
2992     auto state = getCameraState(cameraId);
2993     if (state == nullptr) {
2994         ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
2995         return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2996                 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
2997     }
2998 
2999     StatusInternal cameraStatus = state->getStatus();
3000     if (cameraStatus != StatusInternal::PRESENT &&
3001             cameraStatus != StatusInternal::NOT_AVAILABLE) {
3002         ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
3003                 (int)cameraStatus);
3004         return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
3005                 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
3006     }
3007 
3008     {
3009         Mutex::Autolock al(mTorchStatusMutex);
3010         TorchModeStatus status;
3011         status_t err = getTorchStatusLocked(cameraId, &status);
3012         if (err != OK) {
3013             if (err == NAME_NOT_FOUND) {
3014                 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
3015                         "Camera \"%s\" does not have a flash unit", cameraId.c_str());
3016             }
3017             ALOGE("%s: getting current torch status failed for camera %s",
3018                     __FUNCTION__, cameraId.c_str());
3019             return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
3020                     "Error updating torch status for camera \"%s\": %s (%d)", cameraId.c_str(),
3021                     strerror(-err), err);
3022         }
3023 
3024         if (status == TorchModeStatus::NOT_AVAILABLE) {
3025             if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
3026                 ALOGE("%s: torch mode of camera %s is not available because "
3027                         "camera is in use", __FUNCTION__, cameraId.c_str());
3028                 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
3029                         "Torch for camera \"%s\" is not available due to an existing camera user",
3030                         cameraId.c_str());
3031             } else {
3032                 ALOGE("%s: torch mode of camera %s is not available due to "
3033                         "insufficient resources", __FUNCTION__, cameraId.c_str());
3034                 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
3035                         "Torch for camera \"%s\" is not available due to insufficient resources",
3036                         cameraId.c_str());
3037             }
3038         }
3039     }
3040 
3041     {
3042         // Update UID map - this is used in the torch status changed callbacks, so must be done
3043         // before setTorchMode
3044         Mutex::Autolock al(mTorchUidMapMutex);
3045         updateTorchUidMapLocked(cameraId, uid);
3046     }
3047 
3048     status_t err = mFlashlight->setTorchMode(cameraId, enabled);
3049 
3050     if (err != OK) {
3051         int32_t errorCode;
3052         std::string msg;
3053         switch (err) {
3054             case -ENOSYS:
3055                 msg = fmt::sprintf("Camera \"%s\" has no flashlight",
3056                     cameraId.c_str());
3057                 errorCode = ERROR_ILLEGAL_ARGUMENT;
3058                 break;
3059             case -EBUSY:
3060                 msg = fmt::sprintf("Camera \"%s\" is in use",
3061                     cameraId.c_str());
3062                 errorCode = ERROR_CAMERA_IN_USE;
3063                 break;
3064             default:
3065                 msg = fmt::sprintf(
3066                     "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
3067                     cameraId.c_str(), enabled, strerror(-err), err);
3068                 errorCode = ERROR_INVALID_OPERATION;
3069         }
3070         ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3071         logServiceError(msg, errorCode);
3072         return STATUS_ERROR(errorCode, msg.c_str());
3073     }
3074 
3075     {
3076         // update the link to client's death
3077         Mutex::Autolock al(mTorchClientMapMutex);
3078         ssize_t index = mTorchClientMap.indexOfKey(cameraId);
3079         if (enabled) {
3080             if (index == NAME_NOT_FOUND) {
3081                 mTorchClientMap.add(cameraId, clientBinder);
3082             } else {
3083                 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
3084                 mTorchClientMap.replaceValueAt(index, clientBinder);
3085             }
3086             clientBinder->linkToDeath(this);
3087         } else if (index != NAME_NOT_FOUND) {
3088             mTorchClientMap.valueAt(index)->unlinkToDeath(this);
3089         }
3090     }
3091 
3092     int clientPid = getCallingPid();
3093     std::string torchState = enabled ? "on" : "off";
3094     ALOGI("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3095             torchState.c_str(), clientPid);
3096     logTorchEvent(cameraId, torchState, clientPid);
3097     return Status::ok();
3098 }
3099 
updateTorchUidMapLocked(const std::string & cameraId,int uid)3100 void CameraService::updateTorchUidMapLocked(const std::string& cameraId, int uid) {
3101     if (mTorchUidMap.find(cameraId) == mTorchUidMap.end()) {
3102         mTorchUidMap[cameraId].first = uid;
3103         mTorchUidMap[cameraId].second = uid;
3104     } else {
3105         // Set the pending UID
3106         mTorchUidMap[cameraId].first = uid;
3107     }
3108 }
3109 
notifySystemEvent(int32_t eventId,const std::vector<int32_t> & args)3110 Status CameraService::notifySystemEvent(int32_t eventId,
3111         const std::vector<int32_t>& args) {
3112     const int pid = getCallingPid();
3113     const int selfPid = getpid();
3114 
3115     // Permission checks
3116     if (pid != selfPid) {
3117         // Ensure we're being called by system_server, or similar process with
3118         // permissions to notify the camera service about system events
3119         if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
3120             const int uid = getCallingUid();
3121             ALOGE("Permission Denial: cannot send updates to camera service about system"
3122                     " events from pid=%d, uid=%d", pid, uid);
3123             return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3124                     "No permission to send updates to camera service about system events"
3125                     " from pid=%d, uid=%d", pid, uid);
3126         }
3127     }
3128 
3129     ATRACE_CALL();
3130 
3131     switch(eventId) {
3132         case ICameraService::EVENT_USER_SWITCHED: {
3133             // Try to register for UID and sensor privacy policy updates, in case we're recovering
3134             // from a system server crash
3135             mUidPolicy->registerSelf();
3136             mSensorPrivacyPolicy->registerSelf();
3137             doUserSwitch(/*newUserIds*/ args);
3138             break;
3139         }
3140         case ICameraService::EVENT_USB_DEVICE_ATTACHED:
3141         case ICameraService::EVENT_USB_DEVICE_DETACHED: {
3142             if (args.size() != 1) {
3143                 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT,
3144                     "USB Device Event requires 1 argument");
3145             }
3146 
3147             // Notify CameraProviderManager for lazy HALs
3148             mCameraProviderManager->notifyUsbDeviceEvent(eventId,
3149                                                         std::to_string(args[0]));
3150             break;
3151         }
3152         case ICameraService::EVENT_NONE:
3153         default: {
3154             ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
3155                     eventId);
3156             break;
3157         }
3158     }
3159     return Status::ok();
3160 }
3161 
notifyMonitoredUids()3162 void CameraService::notifyMonitoredUids() {
3163     Mutex::Autolock lock(mStatusListenerLock);
3164 
3165     for (const auto& it : mListenerList) {
3166         auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
3167         it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3168                 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
3169     }
3170 }
3171 
notifyMonitoredUids(const std::unordered_set<uid_t> & notifyUidSet)3172 void CameraService::notifyMonitoredUids(const std::unordered_set<uid_t> &notifyUidSet) {
3173     Mutex::Autolock lock(mStatusListenerLock);
3174 
3175     for (const auto& it : mListenerList) {
3176         if (notifyUidSet.find(it->getListenerUid()) != notifyUidSet.end()) {
3177             ALOGV("%s: notifying uid %d", __FUNCTION__, it->getListenerUid());
3178             auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
3179             it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3180                     __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
3181         }
3182     }
3183 }
3184 
notifyDeviceStateChange(int64_t newState)3185 Status CameraService::notifyDeviceStateChange(int64_t newState) {
3186     const int pid = getCallingPid();
3187     const int selfPid = getpid();
3188 
3189     // Permission checks
3190     if (pid != selfPid) {
3191         // Ensure we're being called by system_server, or similar process with
3192         // permissions to notify the camera service about system events
3193         if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
3194             const int uid = getCallingUid();
3195             ALOGE("Permission Denial: cannot send updates to camera service about device"
3196                     " state changes from pid=%d, uid=%d", pid, uid);
3197             return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3198                     "No permission to send updates to camera service about device state"
3199                     " changes from pid=%d, uid=%d", pid, uid);
3200         }
3201     }
3202 
3203     ATRACE_CALL();
3204 
3205     {
3206         Mutex::Autolock lock(mServiceLock);
3207         mDeviceState = newState;
3208     }
3209 
3210     mCameraProviderManager->notifyDeviceStateChange(newState);
3211 
3212     return Status::ok();
3213 }
3214 
notifyDisplayConfigurationChange()3215 Status CameraService::notifyDisplayConfigurationChange() {
3216     ATRACE_CALL();
3217     const int callingPid = getCallingPid();
3218     const int selfPid = getpid();
3219 
3220     // Permission checks
3221     if (callingPid != selfPid) {
3222         // Ensure we're being called by system_server, or similar process with
3223         // permissions to notify the camera service about system events
3224         if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
3225             const int uid = getCallingUid();
3226             ALOGE("Permission Denial: cannot send updates to camera service about orientation"
3227                     " changes from pid=%d, uid=%d", callingPid, uid);
3228             return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3229                     "No permission to send updates to camera service about orientation"
3230                     " changes from pid=%d, uid=%d", callingPid, uid);
3231         }
3232     }
3233 
3234     Mutex::Autolock lock(mServiceLock);
3235 
3236     // Don't do anything if rotate-and-crop override via cmd is active
3237     if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
3238 
3239     const auto clients = mActiveClientManager.getAll();
3240     for (auto& current : clients) {
3241         if (current != nullptr) {
3242             const auto basicClient = current->getValue();
3243             if (basicClient.get() != nullptr && !basicClient->getOverrideToPortrait()) {
3244                 basicClient->setRotateAndCropOverride(
3245                         mCameraServiceProxyWrapper->getRotateAndCropOverride(
3246                                 basicClient->getPackageName(),
3247                                 basicClient->getCameraFacing(),
3248                                 multiuser_get_user_id(basicClient->getClientUid())));
3249             }
3250         }
3251     }
3252 
3253     return Status::ok();
3254 }
3255 
getConcurrentCameraIds(std::vector<ConcurrentCameraIdCombination> * concurrentCameraIds)3256 Status CameraService::getConcurrentCameraIds(
3257         std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
3258     ATRACE_CALL();
3259     if (!concurrentCameraIds) {
3260         ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
3261         return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
3262     }
3263 
3264     if (!mInitialized) {
3265         ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
3266         logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
3267         return STATUS_ERROR(ERROR_DISCONNECTED,
3268                 "Camera subsystem is not available");
3269     }
3270     // First call into the provider and get the set of concurrent camera
3271     // combinations
3272     std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
3273             mCameraProviderManager->getConcurrentCameraIds();
3274     for (auto &combination : concurrentCameraCombinations) {
3275         std::vector<std::pair<std::string, int32_t>> validCombination;
3276         int32_t firstDeviceId = kInvalidDeviceId;
3277         for (auto &cameraId : combination) {
3278             // if the camera state is not present, skip
3279             auto state = getCameraState(cameraId);
3280             if (state == nullptr) {
3281                 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
3282                 continue;
3283             }
3284             StatusInternal status = state->getStatus();
3285             if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
3286                 continue;
3287             }
3288             if (shouldRejectSystemCameraConnection(cameraId)) {
3289                 continue;
3290             }
3291             auto [cameraOwnerDeviceId, mappedCameraId] =
3292                     mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
3293             if (firstDeviceId == kInvalidDeviceId) {
3294                 firstDeviceId = cameraOwnerDeviceId;
3295             } else if (firstDeviceId != cameraOwnerDeviceId) {
3296                 // Found an invalid combination which contains cameras with different device id's,
3297                 // hence discard it.
3298                 validCombination.clear();
3299                 break;
3300             }
3301             validCombination.push_back({mappedCameraId, cameraOwnerDeviceId});
3302         }
3303         if (validCombination.size() != 0) {
3304             concurrentCameraIds->push_back(std::move(validCombination));
3305         }
3306     }
3307     return Status::ok();
3308 }
3309 
isConcurrentSessionConfigurationSupported(const std::vector<CameraIdAndSessionConfiguration> & cameraIdsAndSessionConfigurations,int targetSdkVersion,int32_t deviceId,int32_t devicePolicy,bool * isSupported)3310 Status CameraService::isConcurrentSessionConfigurationSupported(
3311         const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
3312         int targetSdkVersion, int32_t deviceId, int32_t devicePolicy,
3313         /*out*/bool* isSupported) {
3314     if (!isSupported) {
3315         ALOGE("%s: isSupported is NULL", __FUNCTION__);
3316         return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
3317     }
3318 
3319     if (!mInitialized) {
3320         ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
3321         return STATUS_ERROR(ERROR_DISCONNECTED,
3322                 "Camera subsystem is not available");
3323     }
3324 
3325     for (auto cameraIdAndSessionConfiguration : cameraIdsAndSessionConfigurations) {
3326         std::optional<std::string> cameraIdOptional =
3327                 resolveCameraId(cameraIdAndSessionConfiguration.mCameraId, deviceId, devicePolicy);
3328         if (!cameraIdOptional.has_value()) {
3329             std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
3330                     cameraIdAndSessionConfiguration.mCameraId.c_str(), deviceId);
3331             ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3332             return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
3333         }
3334         cameraIdAndSessionConfiguration.mCameraId = cameraIdOptional.value();
3335     }
3336 
3337     // Check for camera permissions
3338     int callingPid = getCallingPid();
3339     int callingUid = getCallingUid();
3340     bool hasCameraPermission = ((callingPid == getpid()) ||
3341             hasPermissionsForCamera(callingPid, callingUid,
3342                     devicePolicy == IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT
3343                         ? kDefaultDeviceId : deviceId));
3344     if (!hasCameraPermission) {
3345         return STATUS_ERROR(ERROR_PERMISSION_DENIED,
3346                 "android.permission.CAMERA needed to call"
3347                 "isConcurrentSessionConfigurationSupported");
3348     }
3349 
3350     status_t res =
3351             mCameraProviderManager->isConcurrentSessionConfigurationSupported(
3352                     cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
3353                     targetSdkVersion, isSupported);
3354     if (res != OK) {
3355         logServiceError("Unable to query session configuration support",
3356             ERROR_INVALID_OPERATION);
3357         return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
3358                 "support %s (%d)", strerror(-res), res);
3359     }
3360     return Status::ok();
3361 }
3362 
addListener(const sp<ICameraServiceListener> & listener,std::vector<hardware::CameraStatus> * cameraStatuses)3363 Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
3364         /*out*/
3365         std::vector<hardware::CameraStatus> *cameraStatuses) {
3366     return addListenerHelper(listener, cameraStatuses);
3367 }
3368 
addListenerTest(const sp<hardware::ICameraServiceListener> & listener,std::vector<hardware::CameraStatus> * cameraStatuses)3369 binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
3370             std::vector<hardware::CameraStatus>* cameraStatuses) {
3371     return addListenerHelper(listener, cameraStatuses, false, true);
3372 }
3373 
addListenerHelper(const sp<ICameraServiceListener> & listener,std::vector<hardware::CameraStatus> * cameraStatuses,bool isVendorListener,bool isProcessLocalTest)3374 Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
3375         /*out*/
3376         std::vector<hardware::CameraStatus> *cameraStatuses,
3377         bool isVendorListener, bool isProcessLocalTest) {
3378     ATRACE_CALL();
3379 
3380     ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
3381 
3382     if (listener == nullptr) {
3383         ALOGE("%s: Listener must not be null", __FUNCTION__);
3384         return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
3385     }
3386 
3387     auto clientPid = getCallingPid();
3388     auto clientUid = getCallingUid();
3389     bool openCloseCallbackAllowed = hasPermissionsForOpenCloseListener(clientPid, clientUid);
3390 
3391     Mutex::Autolock lock(mServiceLock);
3392 
3393     {
3394         Mutex::Autolock lock(mStatusListenerLock);
3395         for (const auto &it : mListenerList) {
3396             if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
3397                 ALOGW("%s: Tried to add listener %p which was already subscribed",
3398                       __FUNCTION__, listener.get());
3399                 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
3400             }
3401         }
3402 
3403         sp<ServiceListener> serviceListener =
3404                 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
3405                         openCloseCallbackAllowed);
3406         auto ret = serviceListener->initialize(isProcessLocalTest);
3407         if (ret != NO_ERROR) {
3408             std::string msg = fmt::sprintf("Failed to initialize service listener: %s (%d)",
3409                     strerror(-ret), ret);
3410             logServiceError(msg, ERROR_ILLEGAL_ARGUMENT);
3411             ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3412             return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
3413         }
3414         // The listener still needs to be added to the list of listeners, regardless of what
3415         // permissions the listener process has / whether it is a vendor listener. Since it might be
3416         // eligible to listen to other camera ids.
3417         mListenerList.emplace_back(serviceListener);
3418         mUidPolicy->registerMonitorUid(clientUid, /*openCamera*/false);
3419     }
3420 
3421     /* Collect current devices and status */
3422     {
3423         Mutex::Autolock lock(mCameraStatesLock);
3424         for (auto& i : mCameraStates) {
3425             // Get the device id and app-visible camera id for the given HAL-visible camera id.
3426             auto [deviceId, mappedCameraId] =
3427                     mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(i.first);
3428 
3429             cameraStatuses->emplace_back(mappedCameraId,
3430                     mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
3431                     openCloseCallbackAllowed ? i.second->getClientPackage() : std::string(),
3432                     deviceId);
3433         }
3434     }
3435     // Remove the camera statuses that should be hidden from the client, we do
3436     // this after collecting the states in order to avoid holding
3437     // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
3438     // the same time.
3439     cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
3440                 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
3441                         std::string cameraId = s.cameraId;
3442                         std::optional<std::string> cameraIdOptional = resolveCameraId(s.cameraId,
3443                                 s.deviceId, IVirtualDeviceManagerNative::DEVICE_POLICY_CUSTOM);
3444                         if (!cameraIdOptional.has_value()) {
3445                             std::string msg =
3446                                     fmt::sprintf(
3447                                             "Camera %s: Invalid camera id for device id %d",
3448                                             s.cameraId.c_str(), s.deviceId);
3449                             ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3450                             return true;
3451                         }
3452                         cameraId = cameraIdOptional.value();
3453                         SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3454                         if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3455                             ALOGE("%s: Invalid camera id %s, skipping status update",
3456                                     __FUNCTION__, s.cameraId.c_str());
3457                             return true;
3458                         }
3459                         return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
3460                                 clientUid);
3461                      }), cameraStatuses->end());
3462 
3463     // cameraStatuses will have non-eligible camera ids removed.
3464     std::set<std::string> idsChosenForCallback;
3465     for (const auto &s : *cameraStatuses) {
3466         // Add only default device cameras here, as virtual cameras currently don't support torch
3467         // anyway. Note that this is a simplification of the implementation here, and we should
3468         // change this when virtual cameras support torch.
3469         if (s.deviceId == kDefaultDeviceId) {
3470             idsChosenForCallback.insert(s.cameraId);
3471         }
3472     }
3473 
3474     /*
3475      * Immediately signal current torch status to this listener only
3476      * This may be a subset of all the devices, so don't include it in the response directly
3477      */
3478     {
3479         Mutex::Autolock al(mTorchStatusMutex);
3480         for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
3481             const std::string &id = mTorchStatusMap.keyAt(i);
3482             // The camera id is visible to the client. Fine to send torch
3483             // callback.
3484             if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
3485                 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id,
3486                         kDefaultDeviceId);
3487             }
3488         }
3489     }
3490 
3491     return Status::ok();
3492 }
3493 
removeListener(const sp<ICameraServiceListener> & listener)3494 Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
3495     ATRACE_CALL();
3496 
3497     ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
3498 
3499     if (listener == 0) {
3500         ALOGE("%s: Listener must not be null", __FUNCTION__);
3501         return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
3502     }
3503 
3504     Mutex::Autolock lock(mServiceLock);
3505 
3506     {
3507         Mutex::Autolock lock(mStatusListenerLock);
3508         for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
3509             if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
3510                 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid(), /*closeCamera*/false);
3511                 IInterface::asBinder(listener)->unlinkToDeath(*it);
3512                 mListenerList.erase(it);
3513                 return Status::ok();
3514             }
3515         }
3516     }
3517 
3518     ALOGW("%s: Tried to remove a listener %p which was not subscribed",
3519           __FUNCTION__, listener.get());
3520 
3521     return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
3522 }
3523 
getLegacyParameters(int cameraId,std::string * parameters)3524 Status CameraService::getLegacyParameters(int cameraId, /*out*/std::string* parameters) {
3525 
3526     ATRACE_CALL();
3527     ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
3528 
3529     if (parameters == NULL) {
3530         ALOGE("%s: parameters must not be null", __FUNCTION__);
3531         return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
3532     }
3533 
3534     Status ret = Status::ok();
3535 
3536     CameraParameters shimParams;
3537     if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
3538         // Error logged by caller
3539         return ret;
3540     }
3541 
3542     String8 shimParamsString8 = shimParams.flatten();
3543 
3544     *parameters = toStdString(shimParamsString8);
3545 
3546     return ret;
3547 }
3548 
supportsCameraApi(const std::string & cameraId,int apiVersion,bool * isSupported)3549 Status CameraService::supportsCameraApi(const std::string& cameraId, int apiVersion,
3550         /*out*/ bool *isSupported) {
3551     ATRACE_CALL();
3552 
3553     ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
3554 
3555     switch (apiVersion) {
3556         case API_VERSION_1:
3557         case API_VERSION_2:
3558             break;
3559         default:
3560             std::string msg = fmt::sprintf("Unknown API version %d", apiVersion);
3561             ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3562             return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
3563     }
3564 
3565     int portraitRotation;
3566     auto deviceVersionAndTransport =
3567             getDeviceVersion(cameraId,
3568                     /*rotationOverride*/hardware::ICameraService::ROTATION_OVERRIDE_NONE,
3569                     &portraitRotation);
3570     if (deviceVersionAndTransport.first == -1) {
3571         std::string msg = fmt::sprintf("Unknown camera ID %s", cameraId.c_str());
3572         ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3573         return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
3574     }
3575     if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
3576         int deviceVersion = deviceVersionAndTransport.first;
3577         switch (deviceVersion) {
3578             case CAMERA_DEVICE_API_VERSION_1_0:
3579             case CAMERA_DEVICE_API_VERSION_3_0:
3580             case CAMERA_DEVICE_API_VERSION_3_1:
3581                 if (apiVersion == API_VERSION_2) {
3582                     ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without "
3583                             "shim", __FUNCTION__, cameraId.c_str(), deviceVersion);
3584                     *isSupported = false;
3585                 } else { // if (apiVersion == API_VERSION_1) {
3586                     ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always "
3587                             "supported", __FUNCTION__, cameraId.c_str());
3588                     *isSupported = true;
3589                 }
3590                 break;
3591             case CAMERA_DEVICE_API_VERSION_3_2:
3592             case CAMERA_DEVICE_API_VERSION_3_3:
3593             case CAMERA_DEVICE_API_VERSION_3_4:
3594             case CAMERA_DEVICE_API_VERSION_3_5:
3595             case CAMERA_DEVICE_API_VERSION_3_6:
3596             case CAMERA_DEVICE_API_VERSION_3_7:
3597                 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
3598                         __FUNCTION__, cameraId.c_str());
3599                 *isSupported = true;
3600                 break;
3601             default: {
3602                 std::string msg = fmt::sprintf("Unknown device version %x for device %s",
3603                         deviceVersion, cameraId.c_str());
3604                 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3605                 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.c_str());
3606             }
3607         }
3608     } else {
3609         *isSupported = true;
3610     }
3611     return Status::ok();
3612 }
3613 
isHiddenPhysicalCamera(const std::string & cameraId,bool * isSupported)3614 Status CameraService::isHiddenPhysicalCamera(const std::string& cameraId,
3615         /*out*/ bool *isSupported) {
3616     ATRACE_CALL();
3617 
3618     ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
3619     *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(cameraId);
3620 
3621     return Status::ok();
3622 }
3623 
injectCamera(const std::string & packageName,const std::string & internalCamId,const std::string & externalCamId,const sp<ICameraInjectionCallback> & callback,sp<ICameraInjectionSession> * cameraInjectionSession)3624 Status CameraService::injectCamera(
3625         const std::string& packageName, const std::string& internalCamId,
3626         const std::string& externalCamId,
3627         const sp<ICameraInjectionCallback>& callback,
3628         /*out*/
3629         sp<ICameraInjectionSession>* cameraInjectionSession) {
3630     ATRACE_CALL();
3631 
3632     if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
3633         const int pid = getCallingPid();
3634         const int uid = getCallingUid();
3635         ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
3636         return STATUS_ERROR(ERROR_PERMISSION_DENIED,
3637                 "Permission Denial: no permission to inject camera");
3638     }
3639 
3640     // Do not allow any camera injection that injects or replaces a virtual camera.
3641     auto [deviceIdForInternalCamera, _] =
3642             mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(internalCamId);
3643     if (deviceIdForInternalCamera != kDefaultDeviceId) {
3644         return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3645                 "Cannot replace a virtual camera");
3646     }
3647     [[maybe_unused]] auto [deviceIdForExternalCamera, unusedMappedCameraId] =
3648             mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(externalCamId);
3649     if (deviceIdForExternalCamera != kDefaultDeviceId) {
3650         return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3651                 "Cannot inject a virtual camera to replace an internal camera");
3652     }
3653 
3654     ALOGV(
3655         "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
3656         "%s",
3657         __FUNCTION__, packageName.c_str(),
3658         internalCamId.c_str(), externalCamId.c_str());
3659 
3660     {
3661         Mutex::Autolock lock(mInjectionParametersLock);
3662         mInjectionInternalCamId = internalCamId;
3663         mInjectionExternalCamId = externalCamId;
3664         mInjectionStatusListener->addListener(callback);
3665         *cameraInjectionSession = new CameraInjectionSession(this);
3666         status_t res = NO_ERROR;
3667         auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
3668         // If the client already exists, we can directly connect to the camera device through the
3669         // client's injectCamera(), otherwise we need to wait until the client is established
3670         // (execute connectHelper()) before injecting the camera to the camera device.
3671         if (clientDescriptor != nullptr) {
3672             mInjectionInitPending = false;
3673             sp<BasicClient> clientSp = clientDescriptor->getValue();
3674             res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
3675             if(res != OK) {
3676                 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
3677                         "No camera device with ID \"%s\" currently available",
3678                         mInjectionExternalCamId.c_str());
3679             }
3680             res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
3681             if (res != OK) {
3682                 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
3683             }
3684         } else {
3685             mInjectionInitPending = true;
3686         }
3687     }
3688 
3689     return binder::Status::ok();
3690 }
3691 
reportExtensionSessionStats(const hardware::CameraExtensionSessionStats & stats,std::string * sessionKey)3692 Status CameraService::reportExtensionSessionStats(
3693         const hardware::CameraExtensionSessionStats& stats, std::string* sessionKey /*out*/) {
3694     ALOGV("%s: reported %s", __FUNCTION__, stats.toString().c_str());
3695     *sessionKey = mCameraServiceProxyWrapper->updateExtensionStats(stats);
3696     return Status::ok();
3697 }
3698 
removeByClient(const BasicClient * client)3699 void CameraService::removeByClient(const BasicClient* client) {
3700     Mutex::Autolock lock(mServiceLock);
3701     for (auto& i : mActiveClientManager.getAll()) {
3702         auto clientSp = i->getValue();
3703         if (clientSp.get() == client) {
3704             cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
3705             mActiveClientManager.remove(i);
3706         }
3707     }
3708     updateAudioRestrictionLocked();
3709 }
3710 
evictClientIdByRemote(const wp<IBinder> & remote)3711 bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
3712     bool ret = false;
3713     {
3714         // Acquire mServiceLock and prevent other clients from connecting
3715         std::unique_ptr<AutoConditionLock> lock =
3716                 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
3717 
3718         std::vector<sp<BasicClient>> evicted;
3719         for (auto& i : mActiveClientManager.getAll()) {
3720             auto clientSp = i->getValue();
3721             if (clientSp.get() == nullptr) {
3722                 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3723                 mActiveClientManager.remove(i);
3724                 continue;
3725             }
3726             if (remote == clientSp->getRemote()) {
3727                 mActiveClientManager.remove(i);
3728                 evicted.push_back(clientSp);
3729 
3730                 // Notify the client of disconnection
3731                 clientSp->notifyError(
3732                         hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
3733                         CaptureResultExtras());
3734             }
3735         }
3736 
3737         // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
3738         // other clients from connecting in mServiceLockWrapper if held
3739         mServiceLock.unlock();
3740 
3741         // Do not clear caller identity, remote caller should be client proccess
3742 
3743         for (auto& i : evicted) {
3744             if (i.get() != nullptr) {
3745                 i->disconnect();
3746                 ret = true;
3747             }
3748         }
3749 
3750         // Reacquire mServiceLock
3751         mServiceLock.lock();
3752 
3753     } // lock is destroyed, allow further connect calls
3754 
3755     return ret;
3756 }
3757 
getCameraState(const std::string & cameraId) const3758 std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
3759         const std::string& cameraId) const {
3760     std::shared_ptr<CameraState> state;
3761     {
3762         Mutex::Autolock lock(mCameraStatesLock);
3763         auto iter = mCameraStates.find(cameraId);
3764         if (iter != mCameraStates.end()) {
3765             state = iter->second;
3766         }
3767     }
3768     return state;
3769 }
3770 
removeClientLocked(const std::string & cameraId)3771 sp<CameraService::BasicClient> CameraService::removeClientLocked(const std::string& cameraId) {
3772     // Remove from active clients list
3773     auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
3774     if (clientDescriptorPtr == nullptr) {
3775         ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
3776                 cameraId.c_str());
3777         return sp<BasicClient>{nullptr};
3778     }
3779 
3780     sp<BasicClient> client = clientDescriptorPtr->getValue();
3781     if (client.get() != nullptr) {
3782         cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
3783     }
3784     return client;
3785 }
3786 
doUserSwitch(const std::vector<int32_t> & newUserIds)3787 void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
3788     // Acquire mServiceLock and prevent other clients from connecting
3789     std::unique_ptr<AutoConditionLock> lock =
3790             AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
3791 
3792     std::set<userid_t> newAllowedUsers;
3793     for (size_t i = 0; i < newUserIds.size(); i++) {
3794         if (newUserIds[i] < 0) {
3795             ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
3796                     __FUNCTION__, newUserIds[i]);
3797             return;
3798         }
3799         newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
3800     }
3801 
3802 
3803     if (newAllowedUsers == mAllowedUsers) {
3804         ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
3805         return;
3806     }
3807 
3808     logUserSwitch(mAllowedUsers, newAllowedUsers);
3809 
3810     mAllowedUsers = std::move(newAllowedUsers);
3811 
3812     // Current user has switched, evict all current clients.
3813     std::vector<sp<BasicClient>> evicted;
3814     for (auto& i : mActiveClientManager.getAll()) {
3815         auto clientSp = i->getValue();
3816 
3817         if (clientSp.get() == nullptr) {
3818             ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3819             continue;
3820         }
3821 
3822         // Don't evict clients that are still allowed.
3823         uid_t clientUid = clientSp->getClientUid();
3824         userid_t clientUserId = multiuser_get_user_id(clientUid);
3825         if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
3826             continue;
3827         }
3828 
3829         evicted.push_back(clientSp);
3830 
3831         ALOGE("Evicting conflicting client for camera ID %s due to user change",
3832                 i->getKey().c_str());
3833 
3834         // Log the clients evicted
3835         logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID %"
3836                 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n   - Evicted due"
3837                 " to user switch.", i->getKey().c_str(),
3838                 clientSp->getPackageName().c_str(),
3839                 i->getOwnerId(), i->getPriority().getScore(),
3840                 i->getPriority().getState()));
3841 
3842     }
3843 
3844     // Do not hold mServiceLock while disconnecting clients, but retain the condition
3845     // blocking other clients from connecting in mServiceLockWrapper if held.
3846     mServiceLock.unlock();
3847 
3848     // Clear caller identity temporarily so client disconnect PID checks work correctly
3849     int64_t token = clearCallingIdentity();
3850 
3851     for (auto& i : evicted) {
3852         i->disconnect();
3853     }
3854 
3855     restoreCallingIdentity(token);
3856 
3857     // Reacquire mServiceLock
3858     mServiceLock.lock();
3859 }
3860 
logEvent(const std::string & event)3861 void CameraService::logEvent(const std::string &event) {
3862     std::string curTime = getFormattedCurrentTime();
3863     Mutex::Autolock l(mLogLock);
3864     std::string msg = curTime + " : " + event;
3865     // For service error events, print the msg only once.
3866     if (msg.find("SERVICE ERROR") != std::string::npos) {
3867         mEventLog.add(msg);
3868     } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
3869         // Error event not added to the dumpsys log before
3870         mEventLog.add(msg);
3871         sServiceErrorEventSet.insert(msg);
3872     }
3873 }
3874 
logDisconnected(const std::string & cameraId,int clientPid,const std::string & clientPackage)3875 void CameraService::logDisconnected(const std::string &cameraId, int clientPid,
3876         const std::string &clientPackage) {
3877     // Log the clients evicted
3878     logEvent(fmt::sprintf("DISCONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3879             clientPackage.c_str(), clientPid));
3880 }
3881 
logDisconnectedOffline(const std::string & cameraId,int clientPid,const std::string & clientPackage)3882 void CameraService::logDisconnectedOffline(const std::string &cameraId, int clientPid,
3883         const std::string &clientPackage) {
3884     // Log the clients evicted
3885     logEvent(fmt::sprintf("DISCONNECT offline device %s client for package %s (PID %d)",
3886             cameraId.c_str(), clientPackage.c_str(), clientPid));
3887 }
3888 
logConnected(const std::string & cameraId,int clientPid,const std::string & clientPackage)3889 void CameraService::logConnected(const std::string &cameraId, int clientPid,
3890         const std::string &clientPackage) {
3891     // Log the clients evicted
3892     logEvent(fmt::sprintf("CONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3893             clientPackage.c_str(), clientPid));
3894 }
3895 
logConnectedOffline(const std::string & cameraId,int clientPid,const std::string & clientPackage)3896 void CameraService::logConnectedOffline(const std::string &cameraId, int clientPid,
3897         const std::string &clientPackage) {
3898     // Log the clients evicted
3899     logEvent(fmt::sprintf("CONNECT offline device %s client for package %s (PID %d)",
3900             cameraId.c_str(), clientPackage.c_str(), clientPid));
3901 }
3902 
logRejected(const std::string & cameraId,int clientPid,const std::string & clientPackage,const std::string & reason)3903 void CameraService::logRejected(const std::string &cameraId, int clientPid,
3904         const std::string &clientPackage, const std::string &reason) {
3905     // Log the client rejected
3906     logEvent(fmt::sprintf("REJECT device %s client for package %s (PID %d), reason: (%s)",
3907             cameraId.c_str(), clientPackage.c_str(), clientPid, reason.c_str()));
3908 }
3909 
logTorchEvent(const std::string & cameraId,const std::string & torchState,int clientPid)3910 void CameraService::logTorchEvent(const std::string &cameraId, const std::string &torchState,
3911         int clientPid) {
3912     // Log torch event
3913     logEvent(fmt::sprintf("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3914             torchState.c_str(), clientPid));
3915 }
3916 
logUserSwitch(const std::set<userid_t> & oldUserIds,const std::set<userid_t> & newUserIds)3917 void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
3918         const std::set<userid_t>& newUserIds) {
3919     std::string newUsers = toString(newUserIds);
3920     std::string oldUsers = toString(oldUserIds);
3921     if (oldUsers.size() == 0) {
3922         oldUsers = "<None>";
3923     }
3924     // Log the new and old users
3925     logEvent(fmt::sprintf("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
3926             oldUsers.c_str(), newUsers.c_str()));
3927 }
3928 
logDeviceRemoved(const std::string & cameraId,const std::string & reason)3929 void CameraService::logDeviceRemoved(const std::string &cameraId, const std::string &reason) {
3930     // Log the device removal
3931     logEvent(fmt::sprintf("REMOVE device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
3932 }
3933 
logDeviceAdded(const std::string & cameraId,const std::string & reason)3934 void CameraService::logDeviceAdded(const std::string &cameraId, const std::string &reason) {
3935     // Log the device removal
3936     logEvent(fmt::sprintf("ADD device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
3937 }
3938 
logClientDied(int clientPid,const std::string & reason)3939 void CameraService::logClientDied(int clientPid, const std::string &reason) {
3940     // Log the device removal
3941     logEvent(fmt::sprintf("DIED client(s) with PID %d, reason: (%s)", clientPid, reason.c_str()));
3942 }
3943 
logServiceError(const std::string & msg,int errorCode)3944 void CameraService::logServiceError(const std::string &msg, int errorCode) {
3945     logEvent(fmt::sprintf("SERVICE ERROR: %s : %d (%s)", msg.c_str(), errorCode,
3946             strerror(-errorCode)));
3947 }
3948 
onTransact(uint32_t code,const Parcel & data,Parcel * reply,uint32_t flags)3949 status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
3950         uint32_t flags) {
3951 
3952     // Permission checks
3953     switch (code) {
3954         case SHELL_COMMAND_TRANSACTION: {
3955             int in = data.readFileDescriptor();
3956             int out = data.readFileDescriptor();
3957             int err = data.readFileDescriptor();
3958             int argc = data.readInt32();
3959             Vector<String16> args;
3960             for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
3961                args.add(data.readString16());
3962             }
3963             sp<IBinder> unusedCallback;
3964             sp<IResultReceiver> resultReceiver;
3965             status_t status;
3966             if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
3967                 return status;
3968             }
3969             if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
3970                 return status;
3971             }
3972             status = shellCommand(in, out, err, args);
3973             if (resultReceiver != nullptr) {
3974                 resultReceiver->send(status);
3975             }
3976             return NO_ERROR;
3977         }
3978     }
3979 
3980     return BnCameraService::onTransact(code, data, reply, flags);
3981 }
3982 
3983 // We share the media players for shutter and recording sound for all clients.
3984 // A reference count is kept to determine when we will actually release the
3985 // media players.
newMediaPlayer(const char * file)3986 sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
3987     sp<MediaPlayer> mp = new MediaPlayer();
3988     status_t error;
3989     if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
3990         mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
3991         error = mp->prepare();
3992     }
3993     if (error != NO_ERROR) {
3994         ALOGE("Failed to load CameraService sounds: %s", file);
3995         mp->disconnect();
3996         mp.clear();
3997         return nullptr;
3998     }
3999     return mp;
4000 }
4001 
increaseSoundRef()4002 void CameraService::increaseSoundRef() {
4003     Mutex::Autolock lock(mSoundLock);
4004     mSoundRef++;
4005 }
4006 
loadSoundLocked(sound_kind kind)4007 void CameraService::loadSoundLocked(sound_kind kind) {
4008     ATRACE_CALL();
4009 
4010     LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
4011     if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
4012         mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
4013         if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
4014             mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
4015         }
4016     } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] ==  NULL) {
4017         mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
4018         if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
4019             mSoundPlayer[SOUND_RECORDING_START] =
4020                 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
4021         }
4022     } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
4023         mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
4024         if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
4025             mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
4026         }
4027     }
4028 }
4029 
decreaseSoundRef()4030 void CameraService::decreaseSoundRef() {
4031     Mutex::Autolock lock(mSoundLock);
4032     LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
4033     if (--mSoundRef) return;
4034 
4035     for (int i = 0; i < NUM_SOUNDS; i++) {
4036         if (mSoundPlayer[i] != 0) {
4037             mSoundPlayer[i]->disconnect();
4038             mSoundPlayer[i].clear();
4039         }
4040     }
4041 }
4042 
playSound(sound_kind kind)4043 void CameraService::playSound(sound_kind kind) {
4044     ATRACE_CALL();
4045 
4046     LOG1("playSound(%d)", kind);
4047     if (kind < 0 || kind >= NUM_SOUNDS) {
4048         ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
4049         return;
4050     }
4051 
4052     Mutex::Autolock lock(mSoundLock);
4053     loadSoundLocked(kind);
4054     sp<MediaPlayer> player = mSoundPlayer[kind];
4055     if (player != 0) {
4056         player->seekTo(0);
4057         player->start();
4058     }
4059 }
4060 
4061 // ----------------------------------------------------------------------------
4062 
Client(const sp<CameraService> & cameraService,const sp<ICameraClient> & cameraClient,std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,const std::string & clientPackageName,bool systemNativeClient,const std::optional<std::string> & clientFeatureId,const std::string & cameraIdStr,int api1CameraId,int cameraFacing,int sensorOrientation,int clientPid,uid_t clientUid,int servicePid,int rotationOverride)4063 CameraService::Client::Client(const sp<CameraService>& cameraService,
4064         const sp<ICameraClient>& cameraClient,
4065         std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
4066         const std::string& clientPackageName, bool systemNativeClient,
4067         const std::optional<std::string>& clientFeatureId,
4068         const std::string& cameraIdStr,
4069         int api1CameraId, int cameraFacing, int sensorOrientation,
4070         int clientPid, uid_t clientUid,
4071         int servicePid, int rotationOverride) :
4072         CameraService::BasicClient(cameraService,
4073                 IInterface::asBinder(cameraClient),
4074                 attributionAndPermissionUtils,
4075                 clientPackageName, systemNativeClient, clientFeatureId,
4076                 cameraIdStr, cameraFacing, sensorOrientation,
4077                 clientPid, clientUid,
4078                 servicePid, rotationOverride),
4079         mCameraId(api1CameraId)
4080 {
4081     int callingPid = getCallingPid();
4082     LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
4083 
4084     mRemoteCallback = cameraClient;
4085 
4086     cameraService->increaseSoundRef();
4087 
4088     LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
4089 }
4090 
4091 // tear down the client
~Client()4092 CameraService::Client::~Client() {
4093     ALOGV("~Client");
4094     mDestructionStarted = true;
4095 
4096     sCameraService->decreaseSoundRef();
4097     // unconditionally disconnect. function is idempotent
4098     Client::disconnect();
4099 }
4100 
4101 sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
4102 
BasicClient(const sp<CameraService> & cameraService,const sp<IBinder> & remoteCallback,std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,const std::string & clientPackageName,bool nativeClient,const std::optional<std::string> & clientFeatureId,const std::string & cameraIdStr,int cameraFacing,int sensorOrientation,int clientPid,uid_t clientUid,int servicePid,int rotationOverride)4103 CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
4104         const sp<IBinder>& remoteCallback,
4105         std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
4106         const std::string& clientPackageName, bool nativeClient,
4107         const std::optional<std::string>& clientFeatureId, const std::string& cameraIdStr,
4108         int cameraFacing, int sensorOrientation, int clientPid, uid_t clientUid,
4109         int servicePid, int rotationOverride):
4110         AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils),
4111         mDestructionStarted(false),
4112         mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
4113         mClientPackageName(clientPackageName), mSystemNativeClient(nativeClient),
4114         mClientFeatureId(clientFeatureId),
4115         mClientPid(clientPid), mClientUid(clientUid),
4116         mServicePid(servicePid),
4117         mDisconnected(false), mUidIsTrusted(false),
4118         mRotationOverride(rotationOverride),
4119         mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
4120         mRemoteBinder(remoteCallback),
4121         mOpsActive(false),
4122         mOpsStreaming(false)
4123 {
4124     if (sCameraService == nullptr) {
4125         sCameraService = cameraService;
4126     }
4127 
4128     // There are 2 scenarios in which a client won't have AppOps operations
4129     // (both scenarios : native clients)
4130     //    1) It's an system native client*, the package name will be empty
4131     //       and it will return from this function in the previous if condition
4132     //       (This is the same as the previously existing behavior).
4133     //    2) It is a system native client, but its package name has been
4134     //       modified for debugging, however it still must not use AppOps since
4135     //       the package name is not a real one.
4136     //
4137     //       * system native client - native client with UID < AID_APP_START. It
4138     //         doesn't exclude clients not on the system partition.
4139     if (!mSystemNativeClient) {
4140         mAppOpsManager = std::make_unique<AppOpsManager>();
4141     }
4142 
4143     mUidIsTrusted = isTrustedCallingUid(mClientUid);
4144 }
4145 
~BasicClient()4146 CameraService::BasicClient::~BasicClient() {
4147     ALOGV("~BasicClient");
4148     mDestructionStarted = true;
4149 }
4150 
disconnect()4151 binder::Status CameraService::BasicClient::disconnect() {
4152     binder::Status res = Status::ok();
4153     if (mDisconnected) {
4154         return res;
4155     }
4156     mDisconnected = true;
4157 
4158     sCameraService->removeByClient(this);
4159     sCameraService->logDisconnected(mCameraIdStr, mClientPid, mClientPackageName);
4160     sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
4161             mCameraIdStr);
4162 
4163     sp<IBinder> remote = getRemote();
4164     if (remote != nullptr) {
4165         remote->unlinkToDeath(sCameraService);
4166     }
4167 
4168     finishCameraOps();
4169     // Notify flashlight that a camera device is closed.
4170     sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
4171     ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.c_str(),
4172             mClientPid);
4173 
4174     // client shouldn't be able to call into us anymore
4175     mClientPid = 0;
4176 
4177     const auto& mActivityManager = getActivityManager();
4178     if (mActivityManager) {
4179         mActivityManager->logFgsApiEnd(LOG_FGS_CAMERA_API,
4180             getCallingUid(),
4181             getCallingPid());
4182     }
4183 
4184     return res;
4185 }
4186 
dump(int,const Vector<String16> &)4187 status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
4188     // No dumping of clients directly over Binder,
4189     // must go through CameraService::dump
4190     android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
4191             getCallingUid(), NULL, 0);
4192     return OK;
4193 }
4194 
startWatchingTags(const std::string &,int)4195 status_t CameraService::BasicClient::startWatchingTags(const std::string&, int) {
4196     // Can't watch tags directly, must go through CameraService::startWatchingTags
4197     return OK;
4198 }
4199 
stopWatchingTags(int)4200 status_t CameraService::BasicClient::stopWatchingTags(int) {
4201     // Can't watch tags directly, must go through CameraService::stopWatchingTags
4202     return OK;
4203 }
4204 
dumpWatchedEventsToVector(std::vector<std::string> &)4205 status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
4206     // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
4207     return OK;
4208 }
4209 
getPackageName() const4210 std::string CameraService::BasicClient::getPackageName() const {
4211     return mClientPackageName;
4212 }
4213 
getCameraFacing() const4214 int CameraService::BasicClient::getCameraFacing() const {
4215     return mCameraFacing;
4216 }
4217 
getCameraOrientation() const4218 int CameraService::BasicClient::getCameraOrientation() const {
4219     return mOrientation;
4220 }
4221 
getClientPid() const4222 int CameraService::BasicClient::getClientPid() const {
4223     return mClientPid;
4224 }
4225 
getClientUid() const4226 uid_t CameraService::BasicClient::getClientUid() const {
4227     return mClientUid;
4228 }
4229 
canCastToApiClient(apiLevel level) const4230 bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
4231     // Defaults to API2.
4232     return level == API_2;
4233 }
4234 
setAudioRestriction(int32_t mode)4235 status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
4236     {
4237         Mutex::Autolock l(mAudioRestrictionLock);
4238         mAudioRestriction = mode;
4239     }
4240     sCameraService->updateAudioRestriction();
4241     return OK;
4242 }
4243 
getServiceAudioRestriction() const4244 int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
4245     return sCameraService->updateAudioRestriction();
4246 }
4247 
getAudioRestriction() const4248 int32_t CameraService::BasicClient::getAudioRestriction() const {
4249     Mutex::Autolock l(mAudioRestrictionLock);
4250     return mAudioRestriction;
4251 }
4252 
isValidAudioRestriction(int32_t mode)4253 bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
4254     switch (mode) {
4255         case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
4256         case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
4257         case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
4258             return true;
4259         default:
4260             return false;
4261     }
4262 }
4263 
handleAppOpMode(int32_t mode)4264 status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
4265     if (mode == AppOpsManager::MODE_ERRORED) {
4266         ALOGI("Camera %s: Access for \"%s\" has been revoked",
4267                 mCameraIdStr.c_str(), mClientPackageName.c_str());
4268         return PERMISSION_DENIED;
4269     } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
4270         // If the calling Uid is trusted (a native service), the AppOpsManager could
4271         // return MODE_IGNORED. Do not treat such case as error.
4272         bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
4273                 mClientPackageName);
4274 
4275         bool isCameraPrivacyEnabled;
4276         if (flags::camera_privacy_allowlist()) {
4277             isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4278                     toString16(mClientPackageName), std::string(), mClientPid, mClientUid);
4279         } else {
4280             isCameraPrivacyEnabled =
4281                 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
4282         }
4283         // We don't want to return EACCESS if the CameraPrivacy is enabled.
4284         // We prefer to successfully open the camera and perform camera muting
4285         // or blocking in connectHelper as handleAppOpMode can be called before the
4286         // connection has been fully established and at that time camera muting
4287         // capabilities are unknown.
4288         if (!isUidActive || !isCameraPrivacyEnabled) {
4289             ALOGI("Camera %s: Access for \"%s\" has been restricted."
4290                     "uid active: %s, privacy enabled: %s", mCameraIdStr.c_str(),
4291                     mClientPackageName.c_str(), isUidActive ? "true" : "false",
4292                     isCameraPrivacyEnabled ? "true" : "false");
4293             // Return the same error as for device policy manager rejection
4294             return -EACCES;
4295         }
4296     }
4297     return OK;
4298 }
4299 
startCameraOps()4300 status_t CameraService::BasicClient::startCameraOps() {
4301     ATRACE_CALL();
4302 
4303     {
4304         ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
4305               __FUNCTION__, mClientPackageName.c_str(), mClientUid);
4306     }
4307     if (mAppOpsManager != nullptr) {
4308         // Notify app ops that the camera is not available
4309         mOpsCallback = new OpsCallback(this);
4310 
4311         if (flags::watch_foreground_changes()) {
4312             mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
4313                 toString16(mClientPackageName),
4314                 AppOpsManager::WATCH_FOREGROUND_CHANGES, mOpsCallback);
4315         } else {
4316             mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
4317                 toString16(mClientPackageName), mOpsCallback);
4318         }
4319 
4320         // Just check for camera acccess here on open - delay startOp until
4321         // camera frames start streaming in startCameraStreamingOps
4322         int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
4323                 toString16(mClientPackageName));
4324         status_t res = handleAppOpMode(mode);
4325         if (res != OK) {
4326             return res;
4327         }
4328     }
4329 
4330     mOpsActive = true;
4331 
4332     // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
4333     sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
4334 
4335     sCameraService->mUidPolicy->registerMonitorUid(mClientUid, /*openCamera*/true);
4336 
4337     // Notify listeners of camera open/close status
4338     sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
4339 
4340     return OK;
4341 }
4342 
startCameraStreamingOps()4343 status_t CameraService::BasicClient::startCameraStreamingOps() {
4344     ATRACE_CALL();
4345 
4346     if (!mOpsActive) {
4347         ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4348         return INVALID_OPERATION;
4349     }
4350     if (mOpsStreaming) {
4351         ALOGV("%s: Streaming already active!", __FUNCTION__);
4352         return OK;
4353     }
4354 
4355     ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
4356             __FUNCTION__, mClientPackageName.c_str(), mClientUid);
4357 
4358     if (mAppOpsManager != nullptr) {
4359         int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
4360                 toString16(mClientPackageName), /*startIfModeDefault*/ false,
4361                 toString16(mClientFeatureId),
4362                 toString16("start camera ") + toString16(mCameraIdStr));
4363         status_t res = handleAppOpMode(mode);
4364         if (res != OK) {
4365             return res;
4366         }
4367     }
4368 
4369     mOpsStreaming = true;
4370 
4371     return OK;
4372 }
4373 
noteAppOp()4374 status_t CameraService::BasicClient::noteAppOp() {
4375     ATRACE_CALL();
4376 
4377     ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d",
4378             __FUNCTION__, mClientPackageName.c_str(), mClientUid);
4379 
4380     // noteAppOp is only used for when camera mute is not supported, in order
4381     // to trigger the sensor privacy "Unblock" dialog
4382     if (mAppOpsManager != nullptr) {
4383         int32_t mode = mAppOpsManager->noteOp(AppOpsManager::OP_CAMERA, mClientUid,
4384                 toString16(mClientPackageName), toString16(mClientFeatureId),
4385                 toString16("start camera ") + toString16(mCameraIdStr));
4386         status_t res = handleAppOpMode(mode);
4387         if (res != OK) {
4388             return res;
4389         }
4390     }
4391 
4392     return OK;
4393 }
4394 
finishCameraStreamingOps()4395 status_t CameraService::BasicClient::finishCameraStreamingOps() {
4396     ATRACE_CALL();
4397 
4398     if (!mOpsActive) {
4399         ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4400         return INVALID_OPERATION;
4401     }
4402     if (!mOpsStreaming) {
4403         ALOGV("%s: Streaming not active!", __FUNCTION__);
4404         return OK;
4405     }
4406 
4407     if (mAppOpsManager != nullptr) {
4408         mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
4409                 toString16(mClientPackageName), toString16(mClientFeatureId));
4410         mOpsStreaming = false;
4411     }
4412 
4413     return OK;
4414 }
4415 
finishCameraOps()4416 status_t CameraService::BasicClient::finishCameraOps() {
4417     ATRACE_CALL();
4418 
4419     if (mOpsStreaming) {
4420         // Make sure we've notified everyone about camera stopping
4421         finishCameraStreamingOps();
4422     }
4423 
4424     // Check if startCameraOps succeeded, and if so, finish the camera op
4425     if (mOpsActive) {
4426         mOpsActive = false;
4427 
4428         // This function is called when a client disconnects. This should
4429         // release the camera, but actually only if it was in a proper
4430         // functional state, i.e. with status NOT_AVAILABLE
4431         std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
4432                 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
4433 
4434         // Transition to PRESENT if the camera is not in either of the rejected states
4435         sCameraService->updateStatus(StatusInternal::PRESENT,
4436                 mCameraIdStr, rejected);
4437     }
4438     // Always stop watching, even if no camera op is active
4439     if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
4440         mAppOpsManager->stopWatchingMode(mOpsCallback);
4441     }
4442     mOpsCallback.clear();
4443 
4444     sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid, /*closeCamera*/true);
4445 
4446     // Notify listeners of camera open/close status
4447     sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
4448 
4449     return OK;
4450 }
4451 
opChanged(int32_t op,const String16 &)4452 void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
4453     ATRACE_CALL();
4454     if (mAppOpsManager == nullptr) {
4455         return;
4456     }
4457     // TODO : add offline camera session case
4458     if (op != AppOpsManager::OP_CAMERA) {
4459         ALOGW("Unexpected app ops notification received: %d", op);
4460         return;
4461     }
4462 
4463     int32_t res;
4464     res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
4465             mClientUid, toString16(mClientPackageName));
4466     ALOGV("checkOp returns: %d, %s ", res,
4467             res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
4468             res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
4469             res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
4470             "UNKNOWN");
4471 
4472     if (res == AppOpsManager::MODE_ERRORED) {
4473         ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.c_str(),
4474               mClientPackageName.c_str());
4475         block();
4476     } else if (res == AppOpsManager::MODE_IGNORED) {
4477         bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
4478 
4479         // Uid may be active, but not visible to the user (e.g. PROCESS_STATE_FOREGROUND_SERVICE).
4480         // If not visible, but still active, then we want to block instead of muting the camera.
4481         int32_t procState = sCameraService->mUidPolicy->getProcState(mClientUid);
4482         bool isUidVisible = (procState <= ActivityManager::PROCESS_STATE_BOUND_TOP);
4483 
4484         bool isCameraPrivacyEnabled;
4485         if (flags::camera_privacy_allowlist()) {
4486             isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4487                     toString16(mClientPackageName),std::string(),mClientPid,mClientUid);
4488         } else {
4489             isCameraPrivacyEnabled =
4490                 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
4491         }
4492 
4493         ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d"
4494                 " isUidVisible %d, isCameraPrivacyEnabled %d", mCameraIdStr.c_str(),
4495                 mClientPackageName.c_str(), mUidIsTrusted, isUidActive, isUidVisible,
4496                 isCameraPrivacyEnabled);
4497         // If the calling Uid is trusted (a native service), or the client Uid is active / visible
4498         // (WAR for b/175320666)the AppOpsManager could return MODE_IGNORED. Do not treat such
4499         // cases as error.
4500         if (!mUidIsTrusted) {
4501             if (flags::watch_foreground_changes()) {
4502                 if (isUidVisible && isCameraPrivacyEnabled && supportsCameraMute()) {
4503                     setCameraMute(true);
4504                 } else {
4505                     block();
4506                 }
4507             } else {
4508                 if (isUidActive && isCameraPrivacyEnabled && supportsCameraMute()) {
4509                     setCameraMute(true);
4510                 } else if (!isUidActive
4511                     || (isCameraPrivacyEnabled && !supportsCameraMute())) {
4512                     block();
4513                 }
4514             }
4515         }
4516     } else if (res == AppOpsManager::MODE_ALLOWED) {
4517         setCameraMute(sCameraService->mOverrideCameraMuteMode);
4518     }
4519 }
4520 
block()4521 void CameraService::BasicClient::block() {
4522     ATRACE_CALL();
4523 
4524     // Reset the client PID to allow server-initiated disconnect,
4525     // and to prevent further calls by client.
4526     mClientPid = getCallingPid();
4527     CaptureResultExtras resultExtras; // a dummy result (invalid)
4528     notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
4529     disconnect();
4530 }
4531 
4532 // ----------------------------------------------------------------------------
4533 
notifyError(int32_t errorCode,const CaptureResultExtras & resultExtras)4534 void CameraService::Client::notifyError(int32_t errorCode,
4535         [[maybe_unused]] const CaptureResultExtras& resultExtras) {
4536     if (mRemoteCallback != NULL) {
4537         int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
4538         if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
4539             api1ErrorCode = CAMERA_ERROR_DISABLED;
4540         }
4541         mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
4542     } else {
4543         ALOGE("mRemoteCallback is NULL!!");
4544     }
4545 }
4546 
4547 // NOTE: function is idempotent
disconnect()4548 binder::Status CameraService::Client::disconnect() {
4549     ALOGV("Client::disconnect");
4550     return BasicClient::disconnect();
4551 }
4552 
canCastToApiClient(apiLevel level) const4553 bool CameraService::Client::canCastToApiClient(apiLevel level) const {
4554     return level == API_1;
4555 }
4556 
OpsCallback(wp<BasicClient> client)4557 CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
4558         mClient(client) {
4559 }
4560 
opChanged(int32_t op,const String16 & packageName)4561 void CameraService::Client::OpsCallback::opChanged(int32_t op,
4562         const String16& packageName) {
4563     sp<BasicClient> client = mClient.promote();
4564     if (client != NULL) {
4565         client->opChanged(op, packageName);
4566     }
4567 }
4568 
4569 // ----------------------------------------------------------------------------
4570 //                  UidPolicy
4571 // ----------------------------------------------------------------------------
4572 
registerWithActivityManager()4573 void CameraService::UidPolicy::registerWithActivityManager() {
4574     Mutex::Autolock _l(mUidLock);
4575     int32_t emptyUidArray[] = { };
4576 
4577     if (mRegistered) return;
4578     status_t res = mAm.linkToDeath(this);
4579     mAm.registerUidObserverForUids(this, ActivityManager::UID_OBSERVER_GONE
4580             | ActivityManager::UID_OBSERVER_IDLE
4581             | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE
4582             | ActivityManager::UID_OBSERVER_PROC_OOM_ADJ,
4583             ActivityManager::PROCESS_STATE_UNKNOWN,
4584             toString16(kServiceName), emptyUidArray, 0, mObserverToken);
4585     if (res == OK) {
4586         mRegistered = true;
4587         ALOGV("UidPolicy: Registered with ActivityManager");
4588     } else {
4589         ALOGE("UidPolicy: Failed to register with ActivityManager: 0x%08x", res);
4590     }
4591 }
4592 
onServiceRegistration(const String16 & name,const sp<IBinder> &)4593 void CameraService::UidPolicy::onServiceRegistration(const String16& name, const sp<IBinder>&) {
4594     if (name != toString16(kActivityServiceName)) {
4595         return;
4596     }
4597 
4598     registerWithActivityManager();
4599 }
4600 
registerSelf()4601 void CameraService::UidPolicy::registerSelf() {
4602     // Use check service to see if the activity service is available
4603     // If not available then register for notifications, instead of blocking
4604     // till the service is ready
4605     sp<IServiceManager> sm = defaultServiceManager();
4606     sp<IBinder> binder = sm->checkService(toString16(kActivityServiceName));
4607     if (!binder) {
4608         sm->registerForNotifications(toString16(kActivityServiceName), this);
4609     } else {
4610         registerWithActivityManager();
4611     }
4612 }
4613 
unregisterSelf()4614 void CameraService::UidPolicy::unregisterSelf() {
4615     Mutex::Autolock _l(mUidLock);
4616 
4617     mAm.unregisterUidObserver(this);
4618     mAm.unlinkToDeath(this);
4619     mRegistered = false;
4620     mActiveUids.clear();
4621     ALOGV("UidPolicy: Unregistered with ActivityManager");
4622 }
4623 
onUidGone(uid_t uid,bool disabled)4624 void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
4625     onUidIdle(uid, disabled);
4626 }
4627 
onUidActive(uid_t uid)4628 void CameraService::UidPolicy::onUidActive(uid_t uid) {
4629     Mutex::Autolock _l(mUidLock);
4630     mActiveUids.insert(uid);
4631 }
4632 
onUidIdle(uid_t uid,bool)4633 void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
4634     bool deleted = false;
4635     {
4636         Mutex::Autolock _l(mUidLock);
4637         if (mActiveUids.erase(uid) > 0) {
4638             deleted = true;
4639         }
4640     }
4641     if (deleted) {
4642         sp<CameraService> service = mService.promote();
4643         if (service != nullptr) {
4644             service->blockClientsForUid(uid);
4645         }
4646     }
4647 }
4648 
onUidStateChanged(uid_t uid,int32_t procState,int64_t procStateSeq __unused,int32_t capability __unused)4649 void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
4650         int64_t procStateSeq __unused, int32_t capability __unused) {
4651     bool procStateChange = false;
4652     {
4653         Mutex::Autolock _l(mUidLock);
4654         if (mMonitoredUids.find(uid) != mMonitoredUids.end() &&
4655                 mMonitoredUids[uid].procState != procState) {
4656             mMonitoredUids[uid].procState = procState;
4657             procStateChange = true;
4658         }
4659     }
4660 
4661     if (procStateChange) {
4662         sp<CameraService> service = mService.promote();
4663         if (service != nullptr) {
4664             service->notifyMonitoredUids();
4665         }
4666     }
4667 }
4668 
4669 /**
4670  * When the OOM adj of the uid owning the camera changes, a different uid waiting on camera
4671  * privileges may take precedence if the owner's new OOM adj is greater than the waiting package.
4672  * Here, we track which monitoredUid has the camera, and track its adj relative to other
4673  * monitoredUids. If it is revised above some other monitoredUid, signal
4674  * onCameraAccessPrioritiesChanged. This only needs to capture the case where there are two
4675  * foreground apps in split screen - state changes will capture all other cases.
4676  */
onUidProcAdjChanged(uid_t uid,int32_t adj)4677 void CameraService::UidPolicy::onUidProcAdjChanged(uid_t uid, int32_t adj) {
4678     std::unordered_set<uid_t> notifyUidSet;
4679     {
4680         Mutex::Autolock _l(mUidLock);
4681         auto it = mMonitoredUids.find(uid);
4682 
4683         if (it != mMonitoredUids.end()) {
4684             if (it->second.hasCamera) {
4685                 for (auto &monitoredUid : mMonitoredUids) {
4686                     if (monitoredUid.first != uid && adj > monitoredUid.second.procAdj) {
4687                         ALOGV("%s: notify uid %d", __FUNCTION__, monitoredUid.first);
4688                         notifyUidSet.emplace(monitoredUid.first);
4689                     }
4690                 }
4691                 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
4692                 notifyUidSet.emplace(uid);
4693             } else {
4694                 for (auto &monitoredUid : mMonitoredUids) {
4695                     if (monitoredUid.second.hasCamera && adj < monitoredUid.second.procAdj) {
4696                         ALOGV("%s: notify uid %d", __FUNCTION__, uid);
4697                         notifyUidSet.emplace(uid);
4698                     }
4699                 }
4700             }
4701             it->second.procAdj = adj;
4702         }
4703     }
4704 
4705     if (notifyUidSet.size() > 0) {
4706         sp<CameraService> service = mService.promote();
4707         if (service != nullptr) {
4708             service->notifyMonitoredUids(notifyUidSet);
4709         }
4710     }
4711 }
4712 
4713 /**
4714  * Register a uid for monitoring, and note whether it owns a camera.
4715  */
registerMonitorUid(uid_t uid,bool openCamera)4716 void CameraService::UidPolicy::registerMonitorUid(uid_t uid, bool openCamera) {
4717     Mutex::Autolock _l(mUidLock);
4718     auto it = mMonitoredUids.find(uid);
4719     if (it != mMonitoredUids.end()) {
4720         it->second.refCount++;
4721     } else {
4722         MonitoredUid monitoredUid;
4723         monitoredUid.procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
4724         monitoredUid.procAdj = resource_policy::UNKNOWN_ADJ;
4725         monitoredUid.refCount = 1;
4726         it = mMonitoredUids.emplace(std::pair<uid_t, MonitoredUid>(uid, monitoredUid)).first;
4727         status_t res = mAm.addUidToObserver(mObserverToken, toString16(kServiceName), uid);
4728         if (res != OK) {
4729             ALOGE("UidPolicy: Failed to add uid to observer: 0x%08x", res);
4730         }
4731     }
4732 
4733     if (openCamera) {
4734         it->second.hasCamera = true;
4735     }
4736 }
4737 
4738 /**
4739  * Unregister a uid for monitoring, and note whether it lost ownership of a camera.
4740  */
unregisterMonitorUid(uid_t uid,bool closeCamera)4741 void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid, bool closeCamera) {
4742     Mutex::Autolock _l(mUidLock);
4743     auto it = mMonitoredUids.find(uid);
4744     if (it != mMonitoredUids.end()) {
4745         it->second.refCount--;
4746         if (it->second.refCount == 0) {
4747             mMonitoredUids.erase(it);
4748             status_t res = mAm.removeUidFromObserver(mObserverToken, toString16(kServiceName), uid);
4749             if (res != OK) {
4750                 ALOGE("UidPolicy: Failed to remove uid from observer: 0x%08x", res);
4751             }
4752         } else if (closeCamera) {
4753             it->second.hasCamera = false;
4754         }
4755     } else {
4756         ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
4757     }
4758 }
4759 
isUidActive(uid_t uid,const std::string & callingPackage)4760 bool CameraService::UidPolicy::isUidActive(uid_t uid, const std::string &callingPackage) {
4761     Mutex::Autolock _l(mUidLock);
4762     return isUidActiveLocked(uid, callingPackage);
4763 }
4764 
4765 static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
4766 static const int64_t kPollUidActiveTimeoutMillis = 50;
4767 
isUidActiveLocked(uid_t uid,const std::string & callingPackage)4768 bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, const std::string &callingPackage) {
4769     // Non-app UIDs are considered always active
4770     // If activity manager is unreachable, assume everything is active
4771     if (uid < FIRST_APPLICATION_UID || !mRegistered) {
4772         return true;
4773     }
4774     auto it = mOverrideUids.find(uid);
4775     if (it != mOverrideUids.end()) {
4776         return it->second;
4777     }
4778     bool active = mActiveUids.find(uid) != mActiveUids.end();
4779     if (!active) {
4780         // We want active UIDs to always access camera with their first attempt since
4781         // there is no guarantee the app is robustly written and would retry getting
4782         // the camera on failure. The inverse case is not a problem as we would take
4783         // camera away soon once we get the callback that the uid is no longer active.
4784         ActivityManager am;
4785         // Okay to access with a lock held as UID changes are dispatched without
4786         // a lock and we are a higher level component.
4787         int64_t startTimeMillis = 0;
4788         do {
4789             // TODO: Fix this b/109950150!
4790             // Okay this is a hack. There is a race between the UID turning active and
4791             // activity being resumed. The proper fix is very risky, so we temporary add
4792             // some polling which should happen pretty rarely anyway as the race is hard
4793             // to hit.
4794             active = mActiveUids.find(uid) != mActiveUids.end();
4795             if (!active) active = am.isUidActive(uid, toString16(callingPackage));
4796             if (active) {
4797                 break;
4798             }
4799             if (startTimeMillis <= 0) {
4800                 startTimeMillis = uptimeMillis();
4801             }
4802             int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
4803             int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
4804             if (remainingTimeMillis <= 0) {
4805                 break;
4806             }
4807             remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
4808 
4809             mUidLock.unlock();
4810             usleep(remainingTimeMillis * 1000);
4811             mUidLock.lock();
4812         } while (true);
4813 
4814         if (active) {
4815             // Now that we found out the UID is actually active, cache that
4816             mActiveUids.insert(uid);
4817         }
4818     }
4819     return active;
4820 }
4821 
getProcState(uid_t uid)4822 int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
4823     Mutex::Autolock _l(mUidLock);
4824     return getProcStateLocked(uid);
4825 }
4826 
getProcStateLocked(uid_t uid)4827 int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
4828     int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
4829     if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
4830         procState = mMonitoredUids[uid].procState;
4831     }
4832     return procState;
4833 }
4834 
addOverrideUid(uid_t uid,const std::string & callingPackage,bool active)4835 void CameraService::UidPolicy::addOverrideUid(uid_t uid,
4836         const std::string &callingPackage, bool active) {
4837     updateOverrideUid(uid, callingPackage, active, true);
4838 }
4839 
removeOverrideUid(uid_t uid,const std::string & callingPackage)4840 void CameraService::UidPolicy::removeOverrideUid(uid_t uid, const std::string &callingPackage) {
4841     updateOverrideUid(uid, callingPackage, false, false);
4842 }
4843 
binderDied(const wp<IBinder> &)4844 void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
4845     Mutex::Autolock _l(mUidLock);
4846     ALOGV("UidPolicy: ActivityManager has died");
4847     mRegistered = false;
4848     mActiveUids.clear();
4849 }
4850 
updateOverrideUid(uid_t uid,const std::string & callingPackage,bool active,bool insert)4851 void CameraService::UidPolicy::updateOverrideUid(uid_t uid, const std::string &callingPackage,
4852         bool active, bool insert) {
4853     bool wasActive = false;
4854     bool isActive = false;
4855     {
4856         Mutex::Autolock _l(mUidLock);
4857         wasActive = isUidActiveLocked(uid, callingPackage);
4858         mOverrideUids.erase(uid);
4859         if (insert) {
4860             mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
4861         }
4862         isActive = isUidActiveLocked(uid, callingPackage);
4863     }
4864     if (wasActive != isActive && !isActive) {
4865         sp<CameraService> service = mService.promote();
4866         if (service != nullptr) {
4867             service->blockClientsForUid(uid);
4868         }
4869     }
4870 }
4871 
4872 // ----------------------------------------------------------------------------
4873 //                  SensorPrivacyPolicy
4874 // ----------------------------------------------------------------------------
4875 
registerWithSensorPrivacyManager()4876 void CameraService::SensorPrivacyPolicy::registerWithSensorPrivacyManager()
4877 {
4878     Mutex::Autolock _l(mSensorPrivacyLock);
4879     if (mRegistered) {
4880         return;
4881     }
4882     hasCameraPrivacyFeature(); // Called so the result is cached
4883     mSpm.addSensorPrivacyListener(this);
4884     if (isAutomotiveDevice()) {
4885         mSpm.addToggleSensorPrivacyListener(this);
4886     }
4887     mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
4888     if (flags::camera_privacy_allowlist()) {
4889         mCameraPrivacyState = mSpm.getToggleSensorPrivacyState(
4890                 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE,
4891                 SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4892     }
4893     status_t res = mSpm.linkToDeath(this);
4894     if (res == OK) {
4895         mRegistered = true;
4896         ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
4897     }
4898 }
4899 
onServiceRegistration(const String16 & name,const sp<IBinder> &)4900 void CameraService::SensorPrivacyPolicy::onServiceRegistration(const String16& name,
4901                                                                const sp<IBinder>&) {
4902     if (name != toString16(kSensorPrivacyServiceName)) {
4903         return;
4904     }
4905 
4906     registerWithSensorPrivacyManager();
4907 }
4908 
registerSelf()4909 void CameraService::SensorPrivacyPolicy::registerSelf() {
4910     // Use checkservice to see if the sensor_privacy service is available
4911     // If service is not available then register for notification
4912     sp<IServiceManager> sm = defaultServiceManager();
4913     sp<IBinder> binder = sm->checkService(toString16(kSensorPrivacyServiceName));
4914     if (!binder) {
4915         sm->registerForNotifications(toString16(kSensorPrivacyServiceName),this);
4916     } else {
4917         registerWithSensorPrivacyManager();
4918     }
4919 }
4920 
unregisterSelf()4921 void CameraService::SensorPrivacyPolicy::unregisterSelf() {
4922     Mutex::Autolock _l(mSensorPrivacyLock);
4923     mSpm.removeSensorPrivacyListener(this);
4924     if (isAutomotiveDevice()) {
4925         mSpm.removeToggleSensorPrivacyListener(this);
4926     }
4927     mSpm.unlinkToDeath(this);
4928     mRegistered = false;
4929     ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
4930 }
4931 
isSensorPrivacyEnabled()4932 bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
4933     if (!mRegistered) {
4934       registerWithSensorPrivacyManager();
4935     }
4936 
4937     Mutex::Autolock _l(mSensorPrivacyLock);
4938     return mSensorPrivacyEnabled;
4939 }
4940 
getCameraPrivacyState()4941 int CameraService::SensorPrivacyPolicy::getCameraPrivacyState() {
4942     if (!mRegistered) {
4943         registerWithSensorPrivacyManager();
4944     }
4945 
4946     Mutex::Autolock _l(mSensorPrivacyLock);
4947     return mCameraPrivacyState;
4948 }
4949 
isCameraPrivacyEnabled()4950 bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled() {
4951     if (!hasCameraPrivacyFeature()) {
4952         return false;
4953     }
4954     return mSpm.isToggleSensorPrivacyEnabled(SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4955 }
4956 
isCameraPrivacyEnabled(const String16 & packageName)4957 bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled(const String16& packageName) {
4958     if (!hasCameraPrivacyFeature()) {
4959         return false;
4960     }
4961     return mSpm.isCameraPrivacyEnabled(packageName);
4962 }
4963 
onSensorPrivacyChanged(int toggleType,int sensor,bool enabled)4964 binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(
4965     int toggleType, int sensor, bool enabled) {
4966     if ((toggleType == SensorPrivacyManager::TOGGLE_TYPE_UNKNOWN)
4967             && (sensor == SensorPrivacyManager::TOGGLE_SENSOR_UNKNOWN)) {
4968         {
4969             Mutex::Autolock _l(mSensorPrivacyLock);
4970             mSensorPrivacyEnabled = enabled;
4971         }
4972         // if sensor privacy is enabled then block all clients from accessing the camera
4973         if (enabled) {
4974             sp<CameraService> service = mService.promote();
4975             if (service != nullptr) {
4976                 service->blockAllClients();
4977             }
4978         }
4979     }
4980     return binder::Status::ok();
4981 }
4982 
onSensorPrivacyStateChanged(int,int sensor,int state)4983 binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyStateChanged(
4984     int, int sensor, int state) {
4985     if (!flags::camera_privacy_allowlist()
4986             || (sensor != SensorPrivacyManager::TOGGLE_SENSOR_CAMERA)) {
4987         return binder::Status::ok();
4988     }
4989     {
4990         Mutex::Autolock _l(mSensorPrivacyLock);
4991         mCameraPrivacyState = state;
4992     }
4993     sp<CameraService> service = mService.promote();
4994     if (!service) {
4995         return binder::Status::ok();
4996     }
4997     // if sensor privacy is enabled then block all clients from accessing the camera
4998     if (state == SensorPrivacyManager::ENABLED) {
4999         service->blockAllClients();
5000     } else if (state == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
5001         service->blockPrivacyEnabledClients();
5002     }
5003     return binder::Status::ok();
5004 }
5005 
binderDied(const wp<IBinder> &)5006 void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
5007     Mutex::Autolock _l(mSensorPrivacyLock);
5008     ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
5009     mRegistered = false;
5010 }
5011 
hasCameraPrivacyFeature()5012 bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
5013     bool supportsSoftwareToggle = mSpm.supportsSensorToggle(
5014             SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5015     bool supportsHardwareToggle = mSpm.supportsSensorToggle(
5016             SensorPrivacyManager::TOGGLE_TYPE_HARDWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5017     return supportsSoftwareToggle || supportsHardwareToggle;
5018 }
5019 
5020 // ----------------------------------------------------------------------------
5021 //                  CameraState
5022 // ----------------------------------------------------------------------------
5023 
CameraState(const std::string & id,int cost,const std::set<std::string> & conflicting,SystemCameraKind systemCameraKind,const std::vector<std::string> & physicalCameras)5024 CameraService::CameraState::CameraState(const std::string& id, int cost,
5025         const std::set<std::string>& conflicting, SystemCameraKind systemCameraKind,
5026         const std::vector<std::string>& physicalCameras) : mId(id),
5027         mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
5028         mSystemCameraKind(systemCameraKind), mPhysicalCameras(physicalCameras) {}
5029 
~CameraState()5030 CameraService::CameraState::~CameraState() {}
5031 
getStatus() const5032 CameraService::StatusInternal CameraService::CameraState::getStatus() const {
5033     Mutex::Autolock lock(mStatusLock);
5034     return mStatus;
5035 }
5036 
getUnavailablePhysicalIds() const5037 std::vector<std::string> CameraService::CameraState::getUnavailablePhysicalIds() const {
5038     Mutex::Autolock lock(mStatusLock);
5039     std::vector<std::string> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
5040     return res;
5041 }
5042 
getShimParams() const5043 CameraParameters CameraService::CameraState::getShimParams() const {
5044     return mShimParams;
5045 }
5046 
setShimParams(const CameraParameters & params)5047 void CameraService::CameraState::setShimParams(const CameraParameters& params) {
5048     mShimParams = params;
5049 }
5050 
getCost() const5051 int CameraService::CameraState::getCost() const {
5052     return mCost;
5053 }
5054 
getConflicting() const5055 std::set<std::string> CameraService::CameraState::getConflicting() const {
5056     return mConflicting;
5057 }
5058 
getSystemCameraKind() const5059 SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
5060     return mSystemCameraKind;
5061 }
5062 
containsPhysicalCamera(const std::string & physicalCameraId) const5063 bool CameraService::CameraState::containsPhysicalCamera(const std::string& physicalCameraId) const {
5064     return std::find(mPhysicalCameras.begin(), mPhysicalCameras.end(), physicalCameraId)
5065             != mPhysicalCameras.end();
5066 }
5067 
addUnavailablePhysicalId(const std::string & physicalId)5068 bool CameraService::CameraState::addUnavailablePhysicalId(const std::string& physicalId) {
5069     Mutex::Autolock lock(mStatusLock);
5070     auto result = mUnavailablePhysicalIds.insert(physicalId);
5071     return result.second;
5072 }
5073 
removeUnavailablePhysicalId(const std::string & physicalId)5074 bool CameraService::CameraState::removeUnavailablePhysicalId(const std::string& physicalId) {
5075     Mutex::Autolock lock(mStatusLock);
5076     auto count = mUnavailablePhysicalIds.erase(physicalId);
5077     return count > 0;
5078 }
5079 
setClientPackage(const std::string & clientPackage)5080 void CameraService::CameraState::setClientPackage(const std::string& clientPackage) {
5081     Mutex::Autolock lock(mStatusLock);
5082     mClientPackage = clientPackage;
5083 }
5084 
getClientPackage() const5085 std::string CameraService::CameraState::getClientPackage() const {
5086     Mutex::Autolock lock(mStatusLock);
5087     return mClientPackage;
5088 }
5089 
5090 // ----------------------------------------------------------------------------
5091 //                  ClientEventListener
5092 // ----------------------------------------------------------------------------
5093 
onClientAdded(const resource_policy::ClientDescriptor<std::string,sp<CameraService::BasicClient>> & descriptor)5094 void CameraService::ClientEventListener::onClientAdded(
5095         const resource_policy::ClientDescriptor<std::string,
5096         sp<CameraService::BasicClient>>& descriptor) {
5097     const auto& basicClient = descriptor.getValue();
5098     if (basicClient.get() != nullptr) {
5099         BatteryNotifier& notifier(BatteryNotifier::getInstance());
5100         notifier.noteStartCamera(toString8(descriptor.getKey()),
5101                 static_cast<int>(basicClient->getClientUid()));
5102     }
5103 }
5104 
onClientRemoved(const resource_policy::ClientDescriptor<std::string,sp<CameraService::BasicClient>> & descriptor)5105 void CameraService::ClientEventListener::onClientRemoved(
5106         const resource_policy::ClientDescriptor<std::string,
5107         sp<CameraService::BasicClient>>& descriptor) {
5108     const auto& basicClient = descriptor.getValue();
5109     if (basicClient.get() != nullptr) {
5110         BatteryNotifier& notifier(BatteryNotifier::getInstance());
5111         notifier.noteStopCamera(toString8(descriptor.getKey()),
5112                 static_cast<int>(basicClient->getClientUid()));
5113     }
5114 }
5115 
5116 // ----------------------------------------------------------------------------
5117 //                  CameraClientManager
5118 // ----------------------------------------------------------------------------
5119 
CameraClientManager()5120 CameraService::CameraClientManager::CameraClientManager() {
5121     setListener(std::make_shared<ClientEventListener>());
5122 }
5123 
~CameraClientManager()5124 CameraService::CameraClientManager::~CameraClientManager() {}
5125 
getCameraClient(const std::string & id) const5126 sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
5127         const std::string& id) const {
5128     auto descriptor = get(id);
5129     if (descriptor == nullptr) {
5130         return sp<BasicClient>{nullptr};
5131     }
5132     return descriptor->getValue();
5133 }
5134 
toString() const5135 std::string CameraService::CameraClientManager::toString() const {
5136     auto all = getAll();
5137     std::ostringstream ret;
5138     ret << "[";
5139     bool hasAny = false;
5140     for (auto& i : all) {
5141         hasAny = true;
5142         std::string key = i->getKey();
5143         int32_t cost = i->getCost();
5144         int32_t pid = i->getOwnerId();
5145         int32_t score = i->getPriority().getScore();
5146         int32_t state = i->getPriority().getState();
5147         auto conflicting = i->getConflicting();
5148         auto clientSp = i->getValue();
5149         std::string packageName;
5150         userid_t clientUserId = 0;
5151         if (clientSp.get() != nullptr) {
5152             packageName = clientSp->getPackageName();
5153             uid_t clientUid = clientSp->getClientUid();
5154             clientUserId = multiuser_get_user_id(clientUid);
5155         }
5156         ret << fmt::sprintf("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
5157                 PRId32 ", State: %" PRId32, key.c_str(), cost, pid, score, state);
5158 
5159         if (clientSp.get() != nullptr) {
5160             ret << fmt::sprintf("User Id: %d, ", clientUserId);
5161         }
5162         if (packageName.size() != 0) {
5163             ret << fmt::sprintf("Client Package Name: %s", packageName.c_str());
5164         }
5165 
5166         ret << ", Conflicting Client Devices: {";
5167         for (auto& j : conflicting) {
5168             ret << fmt::sprintf("%s, ", j.c_str());
5169         }
5170         ret << "})";
5171     }
5172     if (hasAny) ret << "\n";
5173     ret << "]\n";
5174     return std::move(ret.str());
5175 }
5176 
makeClientDescriptor(const std::string & key,const sp<BasicClient> & value,int32_t cost,const std::set<std::string> & conflictingKeys,int32_t score,int32_t ownerId,int32_t state,int32_t oomScoreOffset,bool systemNativeClient)5177 CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
5178         const std::string& key, const sp<BasicClient>& value, int32_t cost,
5179         const std::set<std::string>& conflictingKeys, int32_t score, int32_t ownerId,
5180         int32_t state, int32_t oomScoreOffset, bool systemNativeClient) {
5181 
5182     int32_t score_adj = systemNativeClient ? kSystemNativeClientScore : score;
5183     int32_t state_adj = systemNativeClient ? kSystemNativeClientState : state;
5184 
5185     return std::make_shared<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>(
5186             key, value, cost, conflictingKeys, score_adj, ownerId, state_adj,
5187             systemNativeClient, oomScoreOffset);
5188 }
5189 
makeClientDescriptor(const sp<BasicClient> & value,const CameraService::DescriptorPtr & partial,int32_t oomScoreOffset,bool systemNativeClient)5190 CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
5191         const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
5192         int32_t oomScoreOffset, bool systemNativeClient) {
5193     return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
5194             partial->getConflicting(), partial->getPriority().getScore(),
5195             partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset,
5196             systemNativeClient);
5197 }
5198 
5199 // ----------------------------------------------------------------------------
5200 //                  InjectionStatusListener
5201 // ----------------------------------------------------------------------------
5202 
addListener(const sp<ICameraInjectionCallback> & callback)5203 void CameraService::InjectionStatusListener::addListener(
5204         const sp<ICameraInjectionCallback>& callback) {
5205     Mutex::Autolock lock(mListenerLock);
5206     if (mCameraInjectionCallback) return;
5207     status_t res = IInterface::asBinder(callback)->linkToDeath(this);
5208     if (res == OK) {
5209         mCameraInjectionCallback = callback;
5210     }
5211 }
5212 
removeListener()5213 void CameraService::InjectionStatusListener::removeListener() {
5214     Mutex::Autolock lock(mListenerLock);
5215     if (mCameraInjectionCallback == nullptr) {
5216         ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5217         return;
5218     }
5219     IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
5220     mCameraInjectionCallback = nullptr;
5221 }
5222 
notifyInjectionError(const std::string & injectedCamId,status_t err)5223 void CameraService::InjectionStatusListener::notifyInjectionError(
5224         const std::string &injectedCamId, status_t err) {
5225     if (mCameraInjectionCallback == nullptr) {
5226         ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5227         return;
5228     }
5229 
5230     switch (err) {
5231         case -ENODEV:
5232             mCameraInjectionCallback->onInjectionError(
5233                     ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5234             ALOGE("No camera device with ID \"%s\" currently available!",
5235                     injectedCamId.c_str());
5236             break;
5237         case -EBUSY:
5238             mCameraInjectionCallback->onInjectionError(
5239                     ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5240             ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
5241                     injectedCamId.c_str());
5242             break;
5243         case DEAD_OBJECT:
5244             mCameraInjectionCallback->onInjectionError(
5245                     ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5246             ALOGE("Camera ID \"%s\" object is dead!",
5247                     injectedCamId.c_str());
5248             break;
5249         case INVALID_OPERATION:
5250             mCameraInjectionCallback->onInjectionError(
5251                     ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5252             ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
5253                     injectedCamId.c_str());
5254             break;
5255         case UNKNOWN_TRANSACTION:
5256             mCameraInjectionCallback->onInjectionError(
5257                     ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
5258             ALOGE("Camera ID \"%s\" method doesn't support!",
5259                     injectedCamId.c_str());
5260             break;
5261         default:
5262             mCameraInjectionCallback->onInjectionError(
5263                     ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
5264             ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
5265                     strerror(-err), err, injectedCamId.c_str());
5266     }
5267 }
5268 
binderDied(const wp<IBinder> &)5269 void CameraService::InjectionStatusListener::binderDied(
5270         const wp<IBinder>& /*who*/) {
5271     ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
5272     auto parent = mParent.promote();
5273     if (parent != nullptr) {
5274         auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5275         if (clientDescriptor != nullptr) {
5276             BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5277             baseClientPtr->stopInjection();
5278         }
5279         parent->clearInjectionParameters();
5280     }
5281 }
5282 
5283 // ----------------------------------------------------------------------------
5284 //                  CameraInjectionSession
5285 // ----------------------------------------------------------------------------
5286 
stopInjection()5287 binder::Status CameraService::CameraInjectionSession::stopInjection() {
5288     Mutex::Autolock lock(mInjectionSessionLock);
5289     auto parent = mParent.promote();
5290     if (parent == nullptr) {
5291         ALOGE("CameraInjectionSession: Parent is gone");
5292         return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
5293                 "Camera service encountered error");
5294     }
5295 
5296     status_t res = NO_ERROR;
5297     auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5298     if (clientDescriptor != nullptr) {
5299         BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5300         res = baseClientPtr->stopInjection();
5301         if (res != OK) {
5302             ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
5303                 " ret != NO_ERROR: %d", res);
5304             return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
5305                 "Camera session encountered error");
5306         }
5307     }
5308     parent->clearInjectionParameters();
5309     return binder::Status::ok();
5310 }
5311 
5312 // ----------------------------------------------------------------------------
5313 
5314 static const int kDumpLockRetries = 50;
5315 static const int kDumpLockSleep = 60000;
5316 
tryLock(Mutex & mutex)5317 static bool tryLock(Mutex& mutex)
5318 {
5319     bool locked = false;
5320     for (int i = 0; i < kDumpLockRetries; ++i) {
5321         if (mutex.tryLock() == NO_ERROR) {
5322             locked = true;
5323             break;
5324         }
5325         usleep(kDumpLockSleep);
5326     }
5327     return locked;
5328 }
5329 
cacheDump()5330 void CameraService::cacheDump() {
5331     if (mMemFd != -1) {
5332         const Vector<String16> args;
5333         ATRACE_CALL();
5334         // Acquiring service lock here will avoid the deadlock since
5335         // cacheDump will not be called during the second disconnect.
5336         Mutex::Autolock lock(mServiceLock);
5337 
5338         Mutex::Autolock l(mCameraStatesLock);
5339         // Start collecting the info for open sessions and store it in temp file.
5340         for (const auto& state : mCameraStates) {
5341             std::string cameraId = state.first;
5342             auto clientDescriptor = mActiveClientManager.get(cameraId);
5343             if (clientDescriptor != nullptr) {
5344                 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
5345                 // Log the current open session info before device is disconnected.
5346                 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
5347             }
5348         }
5349     }
5350 }
5351 
dump(int fd,const Vector<String16> & args)5352 status_t CameraService::dump(int fd, const Vector<String16>& args) {
5353     ATRACE_CALL();
5354 
5355     if (checkCallingPermission(toString16(sDumpPermission)) == false) {
5356         dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
5357                 getCallingPid(),
5358                 getCallingUid());
5359         return NO_ERROR;
5360     }
5361     bool locked = tryLock(mServiceLock);
5362     // failed to lock - CameraService is probably deadlocked
5363     if (!locked) {
5364         dprintf(fd, "!! CameraService may be deadlocked !!\n");
5365     }
5366 
5367     if (!mInitialized) {
5368         dprintf(fd, "!! No camera HAL available !!\n");
5369 
5370         // Dump event log for error information
5371         dumpEventLog(fd);
5372 
5373         if (locked) mServiceLock.unlock();
5374         return NO_ERROR;
5375     }
5376     dprintf(fd, "\n== Service global info: ==\n\n");
5377     dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
5378     dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
5379     dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
5380             mNormalDeviceIdsWithoutSystemCamera.size());
5381     for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
5382         dprintf(fd, "    Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
5383     }
5384     std::string activeClientString = mActiveClientManager.toString();
5385     dprintf(fd, "Active Camera Clients:\n%s", activeClientString.c_str());
5386     dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).c_str());
5387     if (mStreamUseCaseOverrides.size() > 0) {
5388         dprintf(fd, "Active stream use case overrides:");
5389         for (int64_t useCaseOverride : mStreamUseCaseOverrides) {
5390             dprintf(fd, " %" PRId64, useCaseOverride);
5391         }
5392         dprintf(fd, "\n");
5393     }
5394 
5395     dumpEventLog(fd);
5396 
5397     bool stateLocked = tryLock(mCameraStatesLock);
5398     if (!stateLocked) {
5399         dprintf(fd, "CameraStates in use, may be deadlocked\n");
5400     }
5401 
5402     int argSize = args.size();
5403     for (int i = 0; i < argSize; i++) {
5404         if (args[i] == toString16(TagMonitor::kMonitorOption)) {
5405             if (i + 1 < argSize) {
5406                 mMonitorTags = toStdString(args[i + 1]);
5407             }
5408             break;
5409         }
5410     }
5411 
5412     for (auto& state : mCameraStates) {
5413         const std::string &cameraId = state.first;
5414 
5415         dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
5416 
5417         CameraParameters p = state.second->getShimParams();
5418         if (!p.isEmpty()) {
5419             dprintf(fd, "  Camera1 API shim is using parameters:\n        ");
5420             p.dump(fd, args);
5421         }
5422 
5423         auto clientDescriptor = mActiveClientManager.get(cameraId);
5424         if (clientDescriptor != nullptr) {
5425             // log the current open session info
5426             dumpOpenSessionClientLogs(fd, args, cameraId);
5427         } else {
5428             dumpClosedSessionClientLogs(fd, cameraId);
5429         }
5430 
5431     }
5432 
5433     if (stateLocked) mCameraStatesLock.unlock();
5434 
5435     if (locked) mServiceLock.unlock();
5436 
5437     mCameraProviderManager->dump(fd, args);
5438 
5439     dprintf(fd, "\n== Vendor tags: ==\n\n");
5440 
5441     sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
5442     if (desc == NULL) {
5443         sp<VendorTagDescriptorCache> cache =
5444                 VendorTagDescriptorCache::getGlobalVendorTagCache();
5445         if (cache == NULL) {
5446             dprintf(fd, "No vendor tags.\n");
5447         } else {
5448             cache->dump(fd, /*verbosity*/2, /*indentation*/2);
5449         }
5450     } else {
5451         desc->dump(fd, /*verbosity*/2, /*indentation*/2);
5452     }
5453 
5454     // Dump camera traces if there were any
5455     dprintf(fd, "\n");
5456     camera3::CameraTraces::dump(fd);
5457 
5458     // Process dump arguments, if any
5459     int n = args.size();
5460     String16 verboseOption("-v");
5461     String16 unreachableOption("--unreachable");
5462     for (int i = 0; i < n; i++) {
5463         if (args[i] == verboseOption) {
5464             // change logging level
5465             if (i + 1 >= n) continue;
5466             std::string levelStr = toStdString(args[i+1]);
5467             int level = atoi(levelStr.c_str());
5468             dprintf(fd, "\nSetting log level to %d.\n", level);
5469             setLogLevel(level);
5470         } else if (args[i] == unreachableOption) {
5471             // Dump memory analysis
5472             // TODO - should limit be an argument parameter?
5473             UnreachableMemoryInfo info;
5474             bool success = GetUnreachableMemory(info, /*limit*/ 10000);
5475             if (!success) {
5476                 dprintf(fd, "\n== Unable to dump unreachable memory. "
5477                         "Try disabling SELinux enforcement. ==\n");
5478             } else {
5479                 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
5480                 std::string s = info.ToString(/*log_contents*/ true);
5481                 write(fd, s.c_str(), s.size());
5482             }
5483         }
5484     }
5485 
5486     bool serviceLocked = tryLock(mServiceLock);
5487 
5488     // Dump info from previous open sessions.
5489     // Reposition the offset to beginning of the file before reading
5490 
5491     if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
5492         dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
5493         ssize_t size_read;
5494         char buf[4096];
5495         while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
5496             // Read data from file to a small buffer and write it to fd.
5497             write(fd, buf, size_read);
5498             if (size_read == -1) {
5499                 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5500                 break;
5501             }
5502         }
5503         dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
5504     } else {
5505         ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5506     }
5507 
5508     if (serviceLocked) mServiceLock.unlock();
5509     return NO_ERROR;
5510 }
5511 
dumpOpenSessionClientLogs(int fd,const Vector<String16> & args,const std::string & cameraId)5512 void CameraService::dumpOpenSessionClientLogs(int fd,
5513         const Vector<String16>& args, const std::string& cameraId) {
5514     auto clientDescriptor = mActiveClientManager.get(cameraId);
5515     dprintf(fd, "  %s : Device %s is open. Client instance dump:\n",
5516             getFormattedCurrentTime().c_str(),
5517             cameraId.c_str());
5518     dprintf(fd, "    Client priority score: %d state: %d\n",
5519         clientDescriptor->getPriority().getScore(),
5520         clientDescriptor->getPriority().getState());
5521     dprintf(fd, "    Client PID: %d\n", clientDescriptor->getOwnerId());
5522 
5523     auto client = clientDescriptor->getValue();
5524     dprintf(fd, "    Client package: %s\n",
5525         client->getPackageName().c_str());
5526 
5527     client->dumpClient(fd, args);
5528 }
5529 
dumpClosedSessionClientLogs(int fd,const std::string & cameraId)5530 void CameraService::dumpClosedSessionClientLogs(int fd, const std::string& cameraId) {
5531     dprintf(fd, "  Device %s is closed, no client instance\n",
5532                     cameraId.c_str());
5533 }
5534 
dumpEventLog(int fd)5535 void CameraService::dumpEventLog(int fd) {
5536     dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
5537 
5538     Mutex::Autolock l(mLogLock);
5539     for (const auto& msg : mEventLog) {
5540         dprintf(fd, "  %s\n", msg.c_str());
5541     }
5542 
5543     if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
5544         dprintf(fd, "  ...\n");
5545     } else if (mEventLog.size() == 0) {
5546         dprintf(fd, "  [no events yet]\n");
5547     }
5548     dprintf(fd, "\n");
5549 }
5550 
cacheClientTagDumpIfNeeded(const std::string & cameraId,BasicClient * client)5551 void CameraService::cacheClientTagDumpIfNeeded(const std::string &cameraId, BasicClient* client) {
5552     Mutex::Autolock lock(mLogLock);
5553     if (!isClientWatchedLocked(client)) { return; }
5554 
5555     std::vector<std::string> dumpVector;
5556     client->dumpWatchedEventsToVector(dumpVector);
5557 
5558     if (dumpVector.empty()) { return; }
5559 
5560     std::ostringstream dumpString;
5561 
5562     std::string currentTime = getFormattedCurrentTime();
5563     dumpString << "Cached @ ";
5564     dumpString << currentTime;
5565     dumpString << "\n"; // First line is the timestamp of when client is cached.
5566 
5567     size_t i = dumpVector.size();
5568 
5569     // Store the string in reverse order (latest last)
5570     while (i > 0) {
5571          i--;
5572          dumpString << cameraId;
5573          dumpString << ":";
5574          dumpString << client->getPackageName();
5575          dumpString << "  ";
5576          dumpString << dumpVector[i]; // implicitly ends with '\n'
5577     }
5578 
5579     mWatchedClientsDumpCache[client->getPackageName()] = dumpString.str();
5580 }
5581 
handleTorchClientBinderDied(const wp<IBinder> & who)5582 void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
5583     Mutex::Autolock al(mTorchClientMapMutex);
5584     for (size_t i = 0; i < mTorchClientMap.size(); i++) {
5585         if (mTorchClientMap[i] == who) {
5586             // turn off the torch mode that was turned on by dead client
5587             std::string cameraId = mTorchClientMap.keyAt(i);
5588             status_t res = mFlashlight->setTorchMode(cameraId, false);
5589             if (res) {
5590                 ALOGE("%s: torch client died but couldn't turn off torch: "
5591                     "%s (%d)", __FUNCTION__, strerror(-res), res);
5592                 return;
5593             }
5594             mTorchClientMap.removeItemsAt(i);
5595             break;
5596         }
5597     }
5598 }
5599 
binderDied(const wp<IBinder> & who)5600 /*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
5601 
5602     /**
5603       * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
5604       * binder driver
5605       */
5606     // PID here is approximate and can be wrong.
5607     logClientDied(getCallingPid(), "Binder died unexpectedly");
5608 
5609     // check torch client
5610     handleTorchClientBinderDied(who);
5611 
5612     // check camera device client
5613     if(!evictClientIdByRemote(who)) {
5614         ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
5615         return;
5616     }
5617 
5618     ALOGE("%s: Java client's binder died, removing it from the list of active clients",
5619             __FUNCTION__);
5620 }
5621 
updateStatus(StatusInternal status,const std::string & cameraId)5622 void CameraService::updateStatus(StatusInternal status, const std::string& cameraId) {
5623     updateStatus(status, cameraId, {});
5624 }
5625 
updateStatus(StatusInternal status,const std::string & cameraId,std::initializer_list<StatusInternal> rejectSourceStates)5626 void CameraService::updateStatus(StatusInternal status, const std::string& cameraId,
5627         std::initializer_list<StatusInternal> rejectSourceStates) {
5628     // Do not lock mServiceLock here or can get into a deadlock from
5629     // connect() -> disconnect -> updateStatus
5630 
5631     auto state = getCameraState(cameraId);
5632 
5633     if (state == nullptr) {
5634         ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
5635                 cameraId.c_str());
5636         return;
5637     }
5638 
5639     // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
5640     SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
5641     if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
5642         ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
5643         return;
5644     }
5645 
5646     if (vd_flags::camera_device_awareness() && status == StatusInternal::PRESENT) {
5647         CameraMetadata cameraInfo;
5648         status_t res = mCameraProviderManager->getCameraCharacteristics(
5649                 cameraId, false, &cameraInfo, hardware::ICameraService::ROTATION_OVERRIDE_NONE);
5650         if (res != OK) {
5651             ALOGW("%s: Not able to get camera characteristics for camera id %s",
5652                   __FUNCTION__, cameraId.c_str());
5653         } else {
5654             int32_t deviceId = getDeviceId(cameraInfo);
5655             if (deviceId != kDefaultDeviceId) {
5656                 const auto &lensFacingEntry = cameraInfo.find(ANDROID_LENS_FACING);
5657                 camera_metadata_enum_android_lens_facing_t androidLensFacing =
5658                         static_cast<camera_metadata_enum_android_lens_facing_t>(
5659                                 lensFacingEntry.data.u8[0]);
5660                 std::string mappedCameraId;
5661                 if (androidLensFacing == ANDROID_LENS_FACING_BACK) {
5662                     mappedCameraId = kVirtualDeviceBackCameraId;
5663                 } else if (androidLensFacing == ANDROID_LENS_FACING_FRONT) {
5664                     mappedCameraId = kVirtualDeviceFrontCameraId;
5665                 } else {
5666                     ALOGD("%s: Not adding entry for an external camera of a virtual device",
5667                           __func__);
5668                 }
5669                 if (!mappedCameraId.empty()) {
5670                     mVirtualDeviceCameraIdMapper.addCamera(cameraId, deviceId, mappedCameraId);
5671                 }
5672             }
5673         }
5674     }
5675 
5676     // Collect the logical cameras without holding mStatusLock in updateStatus
5677     // as that can lead to a deadlock(b/162192331).
5678     auto logicalCameraIds = getLogicalCameras(cameraId);
5679     // Update the status for this camera state, then send the onStatusChangedCallbacks to each
5680     // of the listeners with both the mStatusLock and mStatusListenerLock held
5681     state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
5682                         &logicalCameraIds]
5683             (const std::string& cameraId, StatusInternal status) {
5684                 // Get the device id and app-visible camera id for the given HAL-visible camera id.
5685                 auto [deviceId, mappedCameraId] =
5686                         mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
5687 
5688                 if (status != StatusInternal::ENUMERATING) {
5689                     // Update torch status if it has a flash unit.
5690                     Mutex::Autolock al(mTorchStatusMutex);
5691                     TorchModeStatus torchStatus;
5692                     if (getTorchStatusLocked(cameraId, &torchStatus) !=
5693                             NAME_NOT_FOUND) {
5694                         TorchModeStatus newTorchStatus =
5695                                 status == StatusInternal::PRESENT ?
5696                                 TorchModeStatus::AVAILABLE_OFF :
5697                                 TorchModeStatus::NOT_AVAILABLE;
5698                         if (torchStatus != newTorchStatus) {
5699                             onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
5700                         }
5701                     }
5702                 }
5703 
5704                 Mutex::Autolock lock(mStatusListenerLock);
5705                 notifyPhysicalCameraStatusLocked(mapToInterface(status), mappedCameraId,
5706                         logicalCameraIds, deviceKind, deviceId);
5707 
5708                 for (auto& listener : mListenerList) {
5709                     bool isVendorListener = listener->isVendorListener();
5710                     if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
5711                             listener->getListenerPid(), listener->getListenerUid())) {
5712                         ALOGV("Skipping discovery callback for system-only camera device %s",
5713                               cameraId.c_str());
5714                         continue;
5715                     }
5716 
5717                     auto ret = listener->getListener()->onStatusChanged(mapToInterface(status),
5718                             mappedCameraId, deviceId);
5719                     listener->handleBinderStatus(ret,
5720                             "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
5721                             __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5722                             ret.exceptionCode());
5723                 }
5724             });
5725 }
5726 
updateOpenCloseStatus(const std::string & cameraId,bool open,const std::string & clientPackageName)5727 void CameraService::updateOpenCloseStatus(const std::string& cameraId, bool open,
5728         const std::string& clientPackageName) {
5729     auto state = getCameraState(cameraId);
5730     if (state == nullptr) {
5731         ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
5732                 cameraId.c_str());
5733         return;
5734     }
5735     if (open) {
5736         state->setClientPackage(clientPackageName);
5737     } else {
5738         state->setClientPackage(std::string());
5739     }
5740 
5741     // Get the device id and app-visible camera id for the given HAL-visible camera id.
5742     auto [deviceId, mappedCameraId] =
5743             mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
5744 
5745     Mutex::Autolock lock(mStatusListenerLock);
5746 
5747     for (const auto& it : mListenerList) {
5748         if (!it->isOpenCloseCallbackAllowed()) {
5749             continue;
5750         }
5751 
5752         binder::Status ret;
5753         if (open) {
5754             ret = it->getListener()->onCameraOpened(mappedCameraId, clientPackageName,
5755                     deviceId);
5756         } else {
5757             ret = it->getListener()->onCameraClosed(mappedCameraId, deviceId);
5758         }
5759 
5760         it->handleBinderStatus(ret,
5761                 "%s: Failed to trigger onCameraOpened/onCameraClosed callback for %d:%d: %d",
5762                 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
5763     }
5764 }
5765 
5766 template<class Func>
updateStatus(StatusInternal status,const std::string & cameraId,std::initializer_list<StatusInternal> rejectSourceStates,Func onStatusUpdatedLocked)5767 void CameraService::CameraState::updateStatus(StatusInternal status,
5768         const std::string& cameraId,
5769         std::initializer_list<StatusInternal> rejectSourceStates,
5770         Func onStatusUpdatedLocked) {
5771     Mutex::Autolock lock(mStatusLock);
5772     StatusInternal oldStatus = mStatus;
5773     mStatus = status;
5774 
5775     if (oldStatus == status) {
5776         return;
5777     }
5778 
5779     ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
5780             cameraId.c_str(), oldStatus, status);
5781 
5782     if (oldStatus == StatusInternal::NOT_PRESENT &&
5783             (status != StatusInternal::PRESENT &&
5784              status != StatusInternal::ENUMERATING)) {
5785 
5786         ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
5787                 __FUNCTION__);
5788         mStatus = oldStatus;
5789         return;
5790     }
5791 
5792     /**
5793      * Sometimes we want to conditionally do a transition.
5794      * For example if a client disconnects, we want to go to PRESENT
5795      * only if we weren't already in NOT_PRESENT or ENUMERATING.
5796      */
5797     for (auto& rejectStatus : rejectSourceStates) {
5798         if (oldStatus == rejectStatus) {
5799             ALOGV("%s: Rejecting status transition for Camera ID %s,  since the source "
5800                     "state was was in one of the bad states.", __FUNCTION__, cameraId.c_str());
5801             mStatus = oldStatus;
5802             return;
5803         }
5804     }
5805 
5806     onStatusUpdatedLocked(cameraId, status);
5807 }
5808 
getTorchStatusLocked(const std::string & cameraId,TorchModeStatus * status) const5809 status_t CameraService::getTorchStatusLocked(
5810         const std::string& cameraId,
5811         TorchModeStatus *status) const {
5812     if (!status) {
5813         return BAD_VALUE;
5814     }
5815     ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5816     if (index == NAME_NOT_FOUND) {
5817         // invalid camera ID or the camera doesn't have a flash unit
5818         return NAME_NOT_FOUND;
5819     }
5820 
5821     *status = mTorchStatusMap.valueAt(index);
5822     return OK;
5823 }
5824 
setTorchStatusLocked(const std::string & cameraId,TorchModeStatus status)5825 status_t CameraService::setTorchStatusLocked(const std::string& cameraId,
5826         TorchModeStatus status) {
5827     ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5828     if (index == NAME_NOT_FOUND) {
5829         return BAD_VALUE;
5830     }
5831     mTorchStatusMap.editValueAt(index) = status;
5832 
5833     return OK;
5834 }
5835 
getLogicalCameras(const std::string & physicalCameraId)5836 std::list<std::string> CameraService::getLogicalCameras(
5837         const std::string& physicalCameraId) {
5838     std::list<std::string> retList;
5839     Mutex::Autolock lock(mCameraStatesLock);
5840     for (const auto& state : mCameraStates) {
5841         if (state.second->containsPhysicalCamera(physicalCameraId)) {
5842             retList.emplace_back(state.first);
5843         }
5844     }
5845     return retList;
5846 }
5847 
notifyPhysicalCameraStatusLocked(int32_t status,const std::string & physicalCameraId,const std::list<std::string> & logicalCameraIds,SystemCameraKind deviceKind,int32_t deviceId)5848 void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
5849         const std::string& physicalCameraId, const std::list<std::string>& logicalCameraIds,
5850         SystemCameraKind deviceKind, int32_t deviceId) {
5851     // mStatusListenerLock is expected to be locked
5852     for (const auto& logicalCameraId : logicalCameraIds) {
5853         for (auto& listener : mListenerList) {
5854             // Note: we check only the deviceKind of the physical camera id
5855             // since, logical camera ids and their physical camera ids are
5856             // guaranteed to have the same system camera kind.
5857             if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
5858                     listener->getListenerPid(), listener->getListenerUid())) {
5859                 ALOGV("Skipping discovery callback for system-only camera device %s",
5860                         physicalCameraId.c_str());
5861                 continue;
5862             }
5863             auto ret = listener->getListener()->onPhysicalCameraStatusChanged(status,
5864                     logicalCameraId, physicalCameraId, deviceId);
5865             listener->handleBinderStatus(ret,
5866                     "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
5867                     __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5868                     ret.exceptionCode());
5869         }
5870     }
5871 }
5872 
blockClientsForUid(uid_t uid)5873 void CameraService::blockClientsForUid(uid_t uid) {
5874     const auto clients = mActiveClientManager.getAll();
5875     for (auto& current : clients) {
5876         if (current != nullptr) {
5877             const auto basicClient = current->getValue();
5878             if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
5879                 basicClient->block();
5880             }
5881         }
5882     }
5883 }
5884 
blockAllClients()5885 void CameraService::blockAllClients() {
5886     const auto clients = mActiveClientManager.getAll();
5887     for (auto& current : clients) {
5888         if (current != nullptr) {
5889             const auto basicClient = current->getValue();
5890             if (basicClient.get() != nullptr) {
5891                 basicClient->block();
5892             }
5893         }
5894     }
5895 }
5896 
blockPrivacyEnabledClients()5897 void CameraService::blockPrivacyEnabledClients() {
5898     const auto clients = mActiveClientManager.getAll();
5899     for (auto& current : clients) {
5900         if (current != nullptr) {
5901             const auto basicClient = current->getValue();
5902             if (basicClient.get() != nullptr) {
5903                 std::string pkgName = basicClient->getPackageName();
5904                 bool cameraPrivacyEnabled =
5905                         mSensorPrivacyPolicy->isCameraPrivacyEnabled(toString16(pkgName));
5906                 if (cameraPrivacyEnabled) {
5907                     basicClient->block();
5908                 }
5909            }
5910         }
5911     }
5912 }
5913 
5914 // NOTE: This is a remote API - make sure all args are validated
shellCommand(int in,int out,int err,const Vector<String16> & args)5915 status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
5916     if (!checkCallingPermission(toString16(sManageCameraPermission), nullptr, nullptr)) {
5917         return PERMISSION_DENIED;
5918     }
5919     if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
5920         return BAD_VALUE;
5921     }
5922     if (args.size() >= 3 && args[0] == toString16("set-uid-state")) {
5923         return handleSetUidState(args, err);
5924     } else if (args.size() >= 2 && args[0] == toString16("reset-uid-state")) {
5925         return handleResetUidState(args, err);
5926     } else if (args.size() >= 2 && args[0] == toString16("get-uid-state")) {
5927         return handleGetUidState(args, out, err);
5928     } else if (args.size() >= 2 && args[0] == toString16("set-rotate-and-crop")) {
5929         return handleSetRotateAndCrop(args);
5930     } else if (args.size() >= 1 && args[0] == toString16("get-rotate-and-crop")) {
5931         return handleGetRotateAndCrop(out);
5932     } else if (args.size() >= 2 && args[0] == toString16("set-autoframing")) {
5933         return handleSetAutoframing(args);
5934     } else if (args.size() >= 1 && args[0] == toString16("get-autoframing")) {
5935         return handleGetAutoframing(out);
5936     } else if (args.size() >= 2 && args[0] == toString16("set-image-dump-mask")) {
5937         return handleSetImageDumpMask(args);
5938     } else if (args.size() >= 1 && args[0] == toString16("get-image-dump-mask")) {
5939         return handleGetImageDumpMask(out);
5940     } else if (args.size() >= 2 && args[0] == toString16("set-camera-mute")) {
5941         return handleSetCameraMute(args);
5942     } else if (args.size() >= 2 && args[0] == toString16("set-stream-use-case-override")) {
5943         return handleSetStreamUseCaseOverrides(args);
5944     } else if (args.size() >= 1 && args[0] == toString16("clear-stream-use-case-override")) {
5945         handleClearStreamUseCaseOverrides();
5946         return OK;
5947     } else if (args.size() >= 1 && args[0] == toString16("set-zoom-override")) {
5948         return handleSetZoomOverride(args);
5949     } else if (args.size() >= 2 && args[0] == toString16("watch")) {
5950         return handleWatchCommand(args, in, out);
5951     } else if (args.size() >= 2 && args[0] == toString16("set-watchdog")) {
5952         return handleSetCameraServiceWatchdog(args);
5953     } else if (args.size() == 1 && args[0] == toString16("help")) {
5954         printHelp(out);
5955         return OK;
5956     }
5957     printHelp(err);
5958     return BAD_VALUE;
5959 }
5960 
handleSetUidState(const Vector<String16> & args,int err)5961 status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
5962     std::string packageName = toStdString(args[1]);
5963 
5964     bool active = false;
5965     if (args[2] == toString16("active")) {
5966         active = true;
5967     } else if ((args[2] != toString16("idle"))) {
5968         ALOGE("Expected active or idle but got: '%s'", toStdString(args[2]).c_str());
5969         return BAD_VALUE;
5970     }
5971 
5972     int userId = 0;
5973     if (args.size() >= 5 && args[3] == toString16("--user")) {
5974         userId = atoi(toStdString(args[4]).c_str());
5975     }
5976 
5977     uid_t uid;
5978     if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
5979         return BAD_VALUE;
5980     }
5981 
5982     mUidPolicy->addOverrideUid(uid, packageName, active);
5983     return NO_ERROR;
5984 }
5985 
handleResetUidState(const Vector<String16> & args,int err)5986 status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
5987     std::string packageName = toStdString(args[1]);
5988 
5989     int userId = 0;
5990     if (args.size() >= 4 && args[2] == toString16("--user")) {
5991         userId = atoi(toStdString(args[3]).c_str());
5992     }
5993 
5994     uid_t uid;
5995     if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
5996         return BAD_VALUE;
5997     }
5998 
5999     mUidPolicy->removeOverrideUid(uid, packageName);
6000     return NO_ERROR;
6001 }
6002 
handleGetUidState(const Vector<String16> & args,int out,int err)6003 status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
6004     std::string packageName = toStdString(args[1]);
6005 
6006     int userId = 0;
6007     if (args.size() >= 4 && args[2] == toString16("--user")) {
6008         userId = atoi(toStdString(args[3]).c_str());
6009     }
6010 
6011     uid_t uid;
6012     if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
6013         return BAD_VALUE;
6014     }
6015 
6016     if (mUidPolicy->isUidActive(uid, packageName)) {
6017         return dprintf(out, "active\n");
6018     } else {
6019         return dprintf(out, "idle\n");
6020     }
6021 }
6022 
handleSetRotateAndCrop(const Vector<String16> & args)6023 status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
6024     int rotateValue = atoi(toStdString(args[1]).c_str());
6025     if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
6026             rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
6027     Mutex::Autolock lock(mServiceLock);
6028 
6029     mOverrideRotateAndCropMode = rotateValue;
6030 
6031     if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
6032 
6033     const auto clients = mActiveClientManager.getAll();
6034     for (auto& current : clients) {
6035         if (current != nullptr) {
6036             const auto basicClient = current->getValue();
6037             if (basicClient.get() != nullptr) {
6038                 basicClient->setRotateAndCropOverride(rotateValue);
6039             }
6040         }
6041     }
6042 
6043     return OK;
6044 }
6045 
handleSetAutoframing(const Vector<String16> & args)6046 status_t CameraService::handleSetAutoframing(const Vector<String16>& args) {
6047     char* end;
6048     int autoframingValue = (int) strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
6049     if ((*end != '\0') ||
6050             (autoframingValue != ANDROID_CONTROL_AUTOFRAMING_OFF &&
6051              autoframingValue != ANDROID_CONTROL_AUTOFRAMING_ON &&
6052              autoframingValue != ANDROID_CONTROL_AUTOFRAMING_AUTO)) {
6053         return BAD_VALUE;
6054     }
6055 
6056     Mutex::Autolock lock(mServiceLock);
6057     mOverrideAutoframingMode = autoframingValue;
6058 
6059     if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) return OK;
6060 
6061     const auto clients = mActiveClientManager.getAll();
6062     for (auto& current : clients) {
6063         if (current != nullptr) {
6064             const auto basicClient = current->getValue();
6065             if (basicClient.get() != nullptr) {
6066                 basicClient->setAutoframingOverride(autoframingValue);
6067             }
6068         }
6069     }
6070 
6071     return OK;
6072 }
6073 
handleSetCameraServiceWatchdog(const Vector<String16> & args)6074 status_t CameraService::handleSetCameraServiceWatchdog(const Vector<String16>& args) {
6075     int enableWatchdog = atoi(toStdString(args[1]).c_str());
6076 
6077     if (enableWatchdog < 0 || enableWatchdog > 1) return BAD_VALUE;
6078 
6079     Mutex::Autolock lock(mServiceLock);
6080 
6081     mCameraServiceWatchdogEnabled = enableWatchdog;
6082 
6083     const auto clients = mActiveClientManager.getAll();
6084     for (auto& current : clients) {
6085         if (current != nullptr) {
6086             const auto basicClient = current->getValue();
6087             if (basicClient.get() != nullptr) {
6088                 basicClient->setCameraServiceWatchdog(enableWatchdog);
6089             }
6090         }
6091     }
6092 
6093     return OK;
6094 }
6095 
handleGetRotateAndCrop(int out)6096 status_t CameraService::handleGetRotateAndCrop(int out) {
6097     Mutex::Autolock lock(mServiceLock);
6098 
6099     return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
6100 }
6101 
handleGetAutoframing(int out)6102 status_t CameraService::handleGetAutoframing(int out) {
6103     Mutex::Autolock lock(mServiceLock);
6104 
6105     return dprintf(out, "autoframing override: %d\n", mOverrideAutoframingMode);
6106 }
6107 
handleSetImageDumpMask(const Vector<String16> & args)6108 status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
6109     char *endPtr;
6110     errno = 0;
6111     std::string maskString = toStdString(args[1]);
6112     long maskValue = strtol(maskString.c_str(), &endPtr, 10);
6113 
6114     if (errno != 0) return BAD_VALUE;
6115     if (endPtr != maskString.c_str() + maskString.size()) return BAD_VALUE;
6116     if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
6117 
6118     Mutex::Autolock lock(mServiceLock);
6119 
6120     mImageDumpMask = maskValue;
6121 
6122     return OK;
6123 }
6124 
handleGetImageDumpMask(int out)6125 status_t CameraService::handleGetImageDumpMask(int out) {
6126     Mutex::Autolock lock(mServiceLock);
6127 
6128     return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
6129 }
6130 
handleSetCameraMute(const Vector<String16> & args)6131 status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
6132     int muteValue = strtol(toStdString(args[1]).c_str(), nullptr, 10);
6133     if (errno != 0) return BAD_VALUE;
6134 
6135     if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
6136     Mutex::Autolock lock(mServiceLock);
6137 
6138     mOverrideCameraMuteMode = (muteValue == 1);
6139 
6140     const auto clients = mActiveClientManager.getAll();
6141     for (auto& current : clients) {
6142         if (current != nullptr) {
6143             const auto basicClient = current->getValue();
6144             if (basicClient.get() != nullptr) {
6145                 if (basicClient->supportsCameraMute()) {
6146                     basicClient->setCameraMute(mOverrideCameraMuteMode);
6147                 }
6148             }
6149         }
6150     }
6151 
6152     return OK;
6153 }
6154 
handleSetStreamUseCaseOverrides(const Vector<String16> & args)6155 status_t CameraService::handleSetStreamUseCaseOverrides(const Vector<String16>& args) {
6156     std::vector<int64_t> useCasesOverride;
6157     for (size_t i = 1; i < args.size(); i++) {
6158         int64_t useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
6159         std::string arg = toStdString(args[i]);
6160         if (arg == "DEFAULT") {
6161             useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
6162         } else if (arg == "PREVIEW") {
6163             useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW;
6164         } else if (arg == "STILL_CAPTURE") {
6165             useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_STILL_CAPTURE;
6166         } else if (arg == "VIDEO_RECORD") {
6167             useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_RECORD;
6168         } else if (arg == "PREVIEW_VIDEO_STILL") {
6169             useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW_VIDEO_STILL;
6170         } else if (arg == "VIDEO_CALL") {
6171             useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_CALL;
6172         } else if (arg == "CROPPED_RAW") {
6173             useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW;
6174         } else {
6175             ALOGE("%s: Invalid stream use case %s", __FUNCTION__, arg.c_str());
6176             return BAD_VALUE;
6177         }
6178         useCasesOverride.push_back(useCase);
6179     }
6180 
6181     Mutex::Autolock lock(mServiceLock);
6182     mStreamUseCaseOverrides = std::move(useCasesOverride);
6183 
6184     return OK;
6185 }
6186 
handleClearStreamUseCaseOverrides()6187 void CameraService::handleClearStreamUseCaseOverrides() {
6188     Mutex::Autolock lock(mServiceLock);
6189     mStreamUseCaseOverrides.clear();
6190 }
6191 
handleSetZoomOverride(const Vector<String16> & args)6192 status_t CameraService::handleSetZoomOverride(const Vector<String16>& args) {
6193     char* end;
6194     int zoomOverrideValue = strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
6195     if ((*end != '\0') ||
6196             (zoomOverrideValue != -1 &&
6197              zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_OFF &&
6198              zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_ZOOM)) {
6199         return BAD_VALUE;
6200     }
6201 
6202     Mutex::Autolock lock(mServiceLock);
6203     mZoomOverrideValue = zoomOverrideValue;
6204 
6205     const auto clients = mActiveClientManager.getAll();
6206     for (auto& current : clients) {
6207         if (current != nullptr) {
6208             const auto basicClient = current->getValue();
6209             if (basicClient.get() != nullptr) {
6210                 if (basicClient->supportsZoomOverride()) {
6211                     basicClient->setZoomOverride(mZoomOverrideValue);
6212                 }
6213             }
6214         }
6215     }
6216 
6217     return OK;
6218 }
6219 
handleWatchCommand(const Vector<String16> & args,int inFd,int outFd)6220 status_t CameraService::handleWatchCommand(const Vector<String16>& args, int inFd, int outFd) {
6221     if (args.size() >= 3 && args[1] == toString16("start")) {
6222         return startWatchingTags(args, outFd);
6223     } else if (args.size() == 2 && args[1] == toString16("stop")) {
6224         return stopWatchingTags(outFd);
6225     } else if (args.size() == 2 && args[1] == toString16("dump")) {
6226         return printWatchedTags(outFd);
6227     } else if (args.size() >= 2 && args[1] == toString16("live")) {
6228         return printWatchedTagsUntilInterrupt(args, inFd, outFd);
6229     } else if (args.size() == 2 && args[1] == toString16("clear")) {
6230         return clearCachedMonitoredTagDumps(outFd);
6231     }
6232     dprintf(outFd, "Camera service watch commands:\n"
6233                  "  start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
6234                  "        starts watching the provided tags for clients with provided package\n"
6235                  "        recognizes tag shorthands like '3a'\n"
6236                  "        watches all clients if no client is passed, or if 'all' is listed\n"
6237                  "  dump dumps the monitoring information and exits\n"
6238                  "  stop stops watching all tags\n"
6239                  "  live [-n <refresh_interval_ms>]\n"
6240                  "        prints the monitored information in real time\n"
6241                  "        Hit return to exit\n"
6242                  "  clear clears all buffers storing information for watch command");
6243     return BAD_VALUE;
6244 }
6245 
startWatchingTags(const Vector<String16> & args,int outFd)6246 status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
6247     Mutex::Autolock lock(mLogLock);
6248     size_t tagsIdx; // index of '-m'
6249     String16 tags("");
6250     for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != toString16("-m"); tagsIdx++);
6251     if (tagsIdx < args.size() - 1) {
6252         tags = args[tagsIdx + 1];
6253     } else {
6254         dprintf(outFd, "No tags provided.\n");
6255         return BAD_VALUE;
6256     }
6257 
6258     size_t clientsIdx; // index of '-c'
6259     // watch all clients if no clients are provided
6260     String16 clients = toString16(kWatchAllClientsFlag);
6261     for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != toString16("-c");
6262          clientsIdx++);
6263     if (clientsIdx < args.size() - 1) {
6264         clients = args[clientsIdx + 1];
6265     }
6266     parseClientsToWatchLocked(toStdString(clients));
6267 
6268     // track tags to initialize future clients with the monitoring information
6269     mMonitorTags = toStdString(tags);
6270 
6271     bool serviceLock = tryLock(mServiceLock);
6272     int numWatchedClients = 0;
6273     auto cameraClients = mActiveClientManager.getAll();
6274     for (const auto &clientDescriptor: cameraClients) {
6275         if (clientDescriptor == nullptr) { continue; }
6276         sp<BasicClient> client = clientDescriptor->getValue();
6277         if (client.get() == nullptr) { continue; }
6278 
6279         if (isClientWatchedLocked(client.get())) {
6280             client->startWatchingTags(mMonitorTags, outFd);
6281             numWatchedClients++;
6282         }
6283     }
6284     dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
6285 
6286     if (serviceLock) { mServiceLock.unlock(); }
6287     return OK;
6288 }
6289 
stopWatchingTags(int outFd)6290 status_t CameraService::stopWatchingTags(int outFd) {
6291     // clear mMonitorTags to prevent new clients from monitoring tags at initialization
6292     Mutex::Autolock lock(mLogLock);
6293     mMonitorTags = "";
6294 
6295     mWatchedClientPackages.clear();
6296     mWatchedClientsDumpCache.clear();
6297 
6298     bool serviceLock = tryLock(mServiceLock);
6299     auto cameraClients = mActiveClientManager.getAll();
6300     for (const auto &clientDescriptor : cameraClients) {
6301         if (clientDescriptor == nullptr) { continue; }
6302         sp<BasicClient> client = clientDescriptor->getValue();
6303         if (client.get() == nullptr) { continue; }
6304         client->stopWatchingTags(outFd);
6305     }
6306     dprintf(outFd, "Stopped watching all clients.\n");
6307     if (serviceLock) { mServiceLock.unlock(); }
6308     return OK;
6309 }
6310 
clearCachedMonitoredTagDumps(int outFd)6311 status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
6312     Mutex::Autolock lock(mLogLock);
6313     size_t clearedSize = mWatchedClientsDumpCache.size();
6314     mWatchedClientsDumpCache.clear();
6315     dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
6316     return OK;
6317 }
6318 
printWatchedTags(int outFd)6319 status_t CameraService::printWatchedTags(int outFd) {
6320     Mutex::Autolock logLock(mLogLock);
6321     std::set<std::string> connectedMonitoredClients;
6322 
6323     bool printedSomething = false; // tracks if any monitoring information was printed
6324                                    // (from either cached or active clients)
6325 
6326     bool serviceLock = tryLock(mServiceLock);
6327     // get all watched clients that are currently connected
6328     for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
6329         if (clientDescriptor == nullptr) { continue; }
6330 
6331         sp<BasicClient> client = clientDescriptor->getValue();
6332         if (client.get() == nullptr) { continue; }
6333         if (!isClientWatchedLocked(client.get())) { continue; }
6334 
6335         std::vector<std::string> dumpVector;
6336         client->dumpWatchedEventsToVector(dumpVector);
6337 
6338         size_t printIdx = dumpVector.size();
6339         if (printIdx == 0) {
6340             continue;
6341         }
6342 
6343         // Print tag dumps for active client
6344         const std::string &cameraId = clientDescriptor->getKey();
6345         dprintf(outFd, "Client: %s (active)\n", client->getPackageName().c_str());
6346         while(printIdx > 0) {
6347             printIdx--;
6348             dprintf(outFd, "%s:%s  %s", cameraId.c_str(), client->getPackageName().c_str(),
6349                     dumpVector[printIdx].c_str());
6350         }
6351         dprintf(outFd, "\n");
6352         printedSomething = true;
6353 
6354         connectedMonitoredClients.emplace(client->getPackageName());
6355     }
6356     if (serviceLock) { mServiceLock.unlock(); }
6357 
6358     // Print entries in mWatchedClientsDumpCache for clients that are not connected
6359     for (const auto &kv: mWatchedClientsDumpCache) {
6360         const std::string &package = kv.first;
6361         if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
6362             continue;
6363         }
6364 
6365         dprintf(outFd, "Client: %s (cached)\n", package.c_str());
6366         dprintf(outFd, "%s\n", kv.second.c_str());
6367         printedSomething = true;
6368     }
6369 
6370     if (!printedSomething) {
6371         dprintf(outFd, "No monitoring information to print.\n");
6372     }
6373 
6374     return OK;
6375 }
6376 
6377 // Print all events in vector `events' that came after lastPrintedEvent
printNewWatchedEvents(int outFd,const std::string & cameraId,const std::string & packageName,const std::vector<std::string> & events,const std::string & lastPrintedEvent)6378 void printNewWatchedEvents(int outFd,
6379                            const std::string &cameraId,
6380                            const std::string &packageName,
6381                            const std::vector<std::string> &events,
6382                            const std::string &lastPrintedEvent) {
6383     if (events.empty()) { return; }
6384 
6385     // index of lastPrintedEvent in events.
6386     // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
6387     size_t lastPrintedIdx;
6388     for (lastPrintedIdx = 0;
6389          lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
6390          lastPrintedIdx++);
6391 
6392     if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
6393 
6394     // print events in chronological order (latest event last)
6395     size_t idxToPrint = lastPrintedIdx;
6396     do {
6397         idxToPrint--;
6398         dprintf(outFd, "%s:%s  %s", cameraId.c_str(), packageName.c_str(),
6399                 events[idxToPrint].c_str());
6400     } while (idxToPrint != 0);
6401 }
6402 
6403 // Returns true if adb shell cmd watch should be interrupted based on data in inFd. The watch
6404 // command should be interrupted if the user presses the return key, or if user loses any way to
6405 // signal interrupt.
6406 // If timeoutMs == 0, this function will always return false
shouldInterruptWatchCommand(int inFd,int outFd,long timeoutMs)6407 bool shouldInterruptWatchCommand(int inFd, int outFd, long timeoutMs) {
6408     struct timeval startTime;
6409     int startTimeError = gettimeofday(&startTime, nullptr);
6410     if (startTimeError) {
6411         dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6412         return true;
6413     }
6414 
6415     const nfds_t numFds = 1;
6416     struct pollfd pollFd = { .fd = inFd, .events = POLLIN, .revents = 0 };
6417 
6418     struct timeval currTime;
6419     char buffer[2];
6420     while(true) {
6421         int currTimeError = gettimeofday(&currTime, nullptr);
6422         if (currTimeError) {
6423             dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6424             return true;
6425         }
6426 
6427         long elapsedTimeMs = ((currTime.tv_sec - startTime.tv_sec) * 1000L)
6428                 + ((currTime.tv_usec - startTime.tv_usec) / 1000L);
6429         int remainingTimeMs = (int) (timeoutMs - elapsedTimeMs);
6430 
6431         if (remainingTimeMs <= 0) {
6432             // No user interrupt within timeoutMs, don't interrupt watch command
6433             return false;
6434         }
6435 
6436         int numFdsUpdated = poll(&pollFd, numFds, remainingTimeMs);
6437         if (numFdsUpdated < 0) {
6438             dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6439             return true;
6440         }
6441 
6442         if (numFdsUpdated == 0) {
6443             // No user input within timeoutMs, don't interrupt watch command
6444             return false;
6445         }
6446 
6447         if (!(pollFd.revents & POLLIN)) {
6448             dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6449             return true;
6450         }
6451 
6452         ssize_t sizeRead = read(inFd, buffer, sizeof(buffer) - 1);
6453         if (sizeRead < 0) {
6454             dprintf(outFd, "Error reading user input. Exiting.\n");
6455             return true;
6456         }
6457 
6458         if (sizeRead == 0) {
6459             // Reached end of input fd (can happen if input is piped)
6460             // User has no way to signal an interrupt, so interrupt here
6461             return true;
6462         }
6463 
6464         if (buffer[0] == '\n') {
6465             // User pressed return, interrupt watch command.
6466             return true;
6467         }
6468     }
6469 }
6470 
printWatchedTagsUntilInterrupt(const Vector<String16> & args,int inFd,int outFd)6471 status_t CameraService::printWatchedTagsUntilInterrupt(const Vector<String16> &args,
6472                                                        int inFd, int outFd) {
6473     // Figure out refresh interval, if present in args
6474     long refreshTimeoutMs = 1000L; // refresh every 1s by default
6475     if (args.size() > 2) {
6476         size_t intervalIdx; // index of '-n'
6477         for (intervalIdx = 2; intervalIdx < args.size() && toString16("-n") != args[intervalIdx];
6478              intervalIdx++);
6479 
6480         size_t intervalValIdx = intervalIdx + 1;
6481         if (intervalValIdx < args.size()) {
6482             refreshTimeoutMs = strtol(toStdString(args[intervalValIdx]).c_str(), nullptr, 10);
6483             if (errno) { return BAD_VALUE; }
6484         }
6485     }
6486 
6487     // Set min timeout of 10ms. This prevents edge cases in polling when timeout of 0 is passed.
6488     refreshTimeoutMs = refreshTimeoutMs < 10 ? 10 : refreshTimeoutMs;
6489 
6490     dprintf(outFd, "Press return to exit...\n\n");
6491     std::map<std::string, std::string> packageNameToLastEvent;
6492 
6493     while (true) {
6494         bool serviceLock = tryLock(mServiceLock);
6495         auto cameraClients = mActiveClientManager.getAll();
6496         if (serviceLock) { mServiceLock.unlock(); }
6497 
6498         for (const auto& clientDescriptor : cameraClients) {
6499             Mutex::Autolock lock(mLogLock);
6500             if (clientDescriptor == nullptr) { continue; }
6501 
6502             sp<BasicClient> client = clientDescriptor->getValue();
6503             if (client.get() == nullptr) { continue; }
6504             if (!isClientWatchedLocked(client.get())) { continue; }
6505 
6506             const std::string &packageName = client->getPackageName();
6507             // This also initializes the map entries with an empty string
6508             const std::string& lastPrintedEvent = packageNameToLastEvent[packageName];
6509 
6510             std::vector<std::string> latestEvents;
6511             client->dumpWatchedEventsToVector(latestEvents);
6512 
6513             if (!latestEvents.empty()) {
6514                 printNewWatchedEvents(outFd,
6515                                       clientDescriptor->getKey(),
6516                                       packageName,
6517                                       latestEvents,
6518                                       lastPrintedEvent);
6519                 packageNameToLastEvent[packageName] = latestEvents[0];
6520             }
6521         }
6522         if (shouldInterruptWatchCommand(inFd, outFd, refreshTimeoutMs)) {
6523             break;
6524         }
6525     }
6526     return OK;
6527 }
6528 
parseClientsToWatchLocked(const std::string & clients)6529 void CameraService::parseClientsToWatchLocked(const std::string &clients) {
6530     mWatchedClientPackages.clear();
6531 
6532     std::istringstream iss(clients);
6533     std::string nextClient;
6534 
6535     while (std::getline(iss, nextClient, ',')) {
6536         if (nextClient == kWatchAllClientsFlag) {
6537             // Don't need to track any other package if 'all' is present
6538             mWatchedClientPackages.clear();
6539             mWatchedClientPackages.emplace(kWatchAllClientsFlag);
6540             break;
6541         }
6542 
6543         // track package names
6544         mWatchedClientPackages.emplace(nextClient);
6545     }
6546 }
6547 
printHelp(int out)6548 status_t CameraService::printHelp(int out) {
6549     return dprintf(out, "Camera service commands:\n"
6550         "  get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
6551         "  set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
6552         "  reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
6553         "  set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
6554         "      Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
6555         "  get-rotate-and-crop returns the current override rotate-and-crop value\n"
6556         "  set-autoframing <VALUE> overrides the autoframing value for AUTO\n"
6557         "      Valid values 0=false, 1=true, 2=auto\n"
6558         "  get-autoframing returns the current override autoframing value\n"
6559         "  set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
6560         "      Valid values 0=OFF, 1=ON for JPEG\n"
6561         "  get-image-dump-mask returns the current image-dump-mask value\n"
6562         "  set-camera-mute <0/1> enable or disable camera muting\n"
6563         "  set-stream-use-case-override <usecase1> <usecase2> ... override stream use cases\n"
6564         "      Use cases applied in descending resolutions. So usecase1 is assigned to the\n"
6565         "      largest resolution, usecase2 is assigned to the 2nd largest resolution, and so\n"
6566         "      on. In case the number of usecases is smaller than the number of streams, the\n"
6567         "      last use case is assigned to all the remaining streams. In case of multiple\n"
6568         "      streams with the same resolution, the tie-breaker is (JPEG, RAW, YUV, and PRIV)\n"
6569         "      Valid values are (case sensitive): DEFAULT, PREVIEW, STILL_CAPTURE, VIDEO_RECORD,\n"
6570         "      PREVIEW_VIDEO_STILL, VIDEO_CALL, CROPPED_RAW\n"
6571         "  clear-stream-use-case-override clear the stream use case override\n"
6572         "  set-zoom-override <-1/0/1> enable or disable zoom override\n"
6573         "      Valid values -1: do not override, 0: override to OFF, 1: override to ZOOM\n"
6574         "  set-watchdog <VALUE> enables or disables the camera service watchdog\n"
6575         "      Valid values 0=disable, 1=enable\n"
6576         "  watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
6577         "  help print this message\n");
6578 }
6579 
isClientWatched(const BasicClient * client)6580 bool CameraService::isClientWatched(const BasicClient *client) {
6581     Mutex::Autolock lock(mLogLock);
6582     return isClientWatchedLocked(client);
6583 }
6584 
isClientWatchedLocked(const BasicClient * client)6585 bool CameraService::isClientWatchedLocked(const BasicClient *client) {
6586     return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
6587            mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
6588 }
6589 
updateAudioRestriction()6590 int32_t CameraService::updateAudioRestriction() {
6591     Mutex::Autolock lock(mServiceLock);
6592     return updateAudioRestrictionLocked();
6593 }
6594 
updateAudioRestrictionLocked()6595 int32_t CameraService::updateAudioRestrictionLocked() {
6596     int32_t mode = 0;
6597     // iterate through all active client
6598     for (const auto& i : mActiveClientManager.getAll()) {
6599         const auto clientSp = i->getValue();
6600         mode |= clientSp->getAudioRestriction();
6601     }
6602 
6603     bool modeChanged = (mAudioRestriction != mode);
6604     mAudioRestriction = mode;
6605     if (modeChanged) {
6606         mAppOps.setCameraAudioRestriction(mode);
6607     }
6608     return mode;
6609 }
6610 
checkIfInjectionCameraIsPresent(const std::string & externalCamId,sp<BasicClient> clientSp)6611 status_t CameraService::checkIfInjectionCameraIsPresent(const std::string& externalCamId,
6612         sp<BasicClient> clientSp) {
6613     std::unique_ptr<AutoConditionLock> lock =
6614             AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
6615     status_t res = NO_ERROR;
6616     if ((res = checkIfDeviceIsUsable(externalCamId)) != NO_ERROR) {
6617         ALOGW("Device %s is not usable!", externalCamId.c_str());
6618         mInjectionStatusListener->notifyInjectionError(
6619                 externalCamId, UNKNOWN_TRANSACTION);
6620         clientSp->notifyError(
6621                 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
6622                 CaptureResultExtras());
6623 
6624         // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
6625         // other clients from connecting in mServiceLockWrapper if held
6626         mServiceLock.unlock();
6627 
6628         // Clear caller identity temporarily so client disconnect PID checks work correctly
6629         int64_t token = clearCallingIdentity();
6630         clientSp->disconnect();
6631         restoreCallingIdentity(token);
6632 
6633         // Reacquire mServiceLock
6634         mServiceLock.lock();
6635     }
6636 
6637     return res;
6638 }
6639 
clearInjectionParameters()6640 void CameraService::clearInjectionParameters() {
6641     {
6642         Mutex::Autolock lock(mInjectionParametersLock);
6643         mInjectionInitPending = false;
6644         mInjectionInternalCamId = "";
6645     }
6646     mInjectionExternalCamId = "";
6647     mInjectionStatusListener->removeListener();
6648 }
6649 
6650 } // namespace android
6651