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