• 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 
32 #include <android/hardware/ICamera.h>
33 #include <android/hardware/ICameraClient.h>
34 
35 #include <android-base/macros.h>
36 #include <android-base/parseint.h>
37 #include <android-base/stringprintf.h>
38 #include <binder/ActivityManager.h>
39 #include <binder/AppOpsManager.h>
40 #include <binder/IPCThreadState.h>
41 #include <binder/MemoryBase.h>
42 #include <binder/MemoryHeapBase.h>
43 #include <binder/PermissionController.h>
44 #include <binder/IResultReceiver.h>
45 #include <binderthreadstate/CallerUtils.h>
46 #include <cutils/atomic.h>
47 #include <cutils/properties.h>
48 #include <cutils/misc.h>
49 #include <gui/Surface.h>
50 #include <hardware/hardware.h>
51 #include "hidl/HidlCameraService.h"
52 #include <hidl/HidlTransportSupport.h>
53 #include <hwbinder/IPCThreadState.h>
54 #include <memunreachable/memunreachable.h>
55 #include <media/AudioSystem.h>
56 #include <media/IMediaHTTPService.h>
57 #include <media/mediaplayer.h>
58 #include <mediautils/BatteryNotifier.h>
59 #include <processinfo/ProcessInfoService.h>
60 #include <utils/Errors.h>
61 #include <utils/Log.h>
62 #include <utils/String16.h>
63 #include <utils/SystemClock.h>
64 #include <utils/Trace.h>
65 #include <utils/CallStack.h>
66 #include <private/android_filesystem_config.h>
67 #include <system/camera_vendor_tags.h>
68 #include <system/camera_metadata.h>
69 
70 #include <system/camera.h>
71 
72 #include "CameraService.h"
73 #include "api1/Camera2Client.h"
74 #include "api2/CameraDeviceClient.h"
75 #include "utils/CameraTraces.h"
76 #include "utils/TagMonitor.h"
77 #include "utils/CameraThreadState.h"
78 #include "utils/CameraServiceProxyWrapper.h"
79 
80 namespace {
81     const char* kPermissionServiceName = "permission";
82 }; // namespace anonymous
83 
84 namespace android {
85 
86 using base::StringPrintf;
87 using binder::Status;
88 using camera3::SessionConfigurationUtils;
89 using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService;
90 using hardware::ICamera;
91 using hardware::ICameraClient;
92 using hardware::ICameraServiceListener;
93 using hardware::camera::common::V1_0::CameraDeviceStatus;
94 using hardware::camera::common::V1_0::TorchModeStatus;
95 using hardware::camera2::ICameraInjectionCallback;
96 using hardware::camera2::ICameraInjectionSession;
97 using hardware::camera2::utils::CameraIdAndSessionConfiguration;
98 using hardware::camera2::utils::ConcurrentCameraIdCombination;
99 
100 // ----------------------------------------------------------------------------
101 // Logging support -- this is for debugging only
102 // Use "adb shell dumpsys media.camera -v 1" to change it.
103 volatile int32_t gLogLevel = 0;
104 
105 #define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
106 #define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
107 
setLogLevel(int level)108 static void setLogLevel(int level) {
109     android_atomic_write(level, &gLogLevel);
110 }
111 
112 // Convenience methods for constructing binder::Status objects for error returns
113 
114 #define STATUS_ERROR(errorCode, errorString) \
115     binder::Status::fromServiceSpecificError(errorCode, \
116             String8::format("%s:%d: %s", __FUNCTION__, __LINE__, errorString))
117 
118 #define STATUS_ERROR_FMT(errorCode, errorString, ...) \
119     binder::Status::fromServiceSpecificError(errorCode, \
120             String8::format("%s:%d: " errorString, __FUNCTION__, __LINE__, \
121                     __VA_ARGS__))
122 
123 // ----------------------------------------------------------------------------
124 
125 static const String16 sDumpPermission("android.permission.DUMP");
126 static const String16 sManageCameraPermission("android.permission.MANAGE_CAMERA");
127 static const String16 sCameraPermission("android.permission.CAMERA");
128 static const String16 sSystemCameraPermission("android.permission.SYSTEM_CAMERA");
129 static const String16
130         sCameraSendSystemEventsPermission("android.permission.CAMERA_SEND_SYSTEM_EVENTS");
131 static const String16 sCameraOpenCloseListenerPermission(
132         "android.permission.CAMERA_OPEN_CLOSE_LISTENER");
133 static const String16
134         sCameraInjectExternalCameraPermission("android.permission.CAMERA_INJECT_EXTERNAL_CAMERA");
135 const char *sFileName = "lastOpenSessionDumpFile";
136 static constexpr int32_t kVendorClientScore = resource_policy::PERCEPTIBLE_APP_ADJ;
137 static constexpr int32_t kVendorClientState = ActivityManager::PROCESS_STATE_PERSISTENT_UI;
138 
139 const String8 CameraService::kOfflineDevice("offline-");
140 
141 // Set to keep track of logged service error events.
142 static std::set<String8> sServiceErrorEventSet;
143 
CameraService()144 CameraService::CameraService() :
145         mEventLog(DEFAULT_EVENT_LOG_LENGTH),
146         mNumberOfCameras(0),
147         mNumberOfCamerasWithoutSystemCamera(0),
148         mSoundRef(0), mInitialized(false),
149         mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
150     ALOGI("CameraService started (pid=%d)", getpid());
151     mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
152     mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
153     if (mMemFd == -1) {
154         ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
155     }
156 }
157 
onFirstRef()158 void CameraService::onFirstRef()
159 {
160 
161     ALOGI("CameraService process starting");
162 
163     BnCameraService::onFirstRef();
164 
165     // Update battery life tracking if service is restarting
166     BatteryNotifier& notifier(BatteryNotifier::getInstance());
167     notifier.noteResetCamera();
168     notifier.noteResetFlashlight();
169 
170     status_t res = INVALID_OPERATION;
171 
172     res = enumerateProviders();
173     if (res == OK) {
174         mInitialized = true;
175     }
176 
177     mUidPolicy = new UidPolicy(this);
178     mUidPolicy->registerSelf();
179     mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
180     mSensorPrivacyPolicy->registerSelf();
181     mInjectionStatusListener = new InjectionStatusListener(this);
182     mAppOps.setCameraAudioRestriction(mAudioRestriction);
183     sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
184     if (hcs->registerAsService() != android::OK) {
185         ALOGE("%s: Failed to register default android.frameworks.cameraservice.service@1.0",
186               __FUNCTION__);
187     }
188 
189     // This needs to be last call in this function, so that it's as close to
190     // ServiceManager::addService() as possible.
191     CameraServiceProxyWrapper::pingCameraServiceProxy();
192     ALOGI("CameraService pinged cameraservice proxy");
193 }
194 
enumerateProviders()195 status_t CameraService::enumerateProviders() {
196     status_t res;
197 
198     std::vector<std::string> deviceIds;
199     {
200         Mutex::Autolock l(mServiceLock);
201 
202         if (nullptr == mCameraProviderManager.get()) {
203             mCameraProviderManager = new CameraProviderManager();
204             res = mCameraProviderManager->initialize(this);
205             if (res != OK) {
206                 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
207                         __FUNCTION__, strerror(-res), res);
208                 logServiceError(String8::format("Unable to initialize camera provider manager"),
209                 ERROR_DISCONNECTED);
210                 return res;
211             }
212         }
213 
214 
215         // Setup vendor tags before we call get_camera_info the first time
216         // because HAL might need to setup static vendor keys in get_camera_info
217         // TODO: maybe put this into CameraProviderManager::initialize()?
218         mCameraProviderManager->setUpVendorTags();
219 
220         if (nullptr == mFlashlight.get()) {
221             mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
222         }
223 
224         res = mFlashlight->findFlashUnits();
225         if (res != OK) {
226             ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
227         }
228 
229         deviceIds = mCameraProviderManager->getCameraDeviceIds();
230     }
231 
232 
233     for (auto& cameraId : deviceIds) {
234         String8 id8 = String8(cameraId.c_str());
235         if (getCameraState(id8) == nullptr) {
236             onDeviceStatusChanged(id8, CameraDeviceStatus::PRESENT);
237         }
238     }
239 
240     // Derive primary rear/front cameras, and filter their charactierstics.
241     // This needs to be done after all cameras are enumerated and camera ids are sorted.
242     if (SessionConfigurationUtils::IS_PERF_CLASS) {
243         // Assume internal cameras are advertised from the same
244         // provider. If multiple providers are registered at different time,
245         // and each provider contains multiple internal color cameras, the current
246         // logic may filter the characteristics of more than one front/rear color
247         // cameras.
248         Mutex::Autolock l(mServiceLock);
249         filterSPerfClassCharacteristicsLocked();
250     }
251 
252     return OK;
253 }
254 
broadcastTorchModeStatus(const String8 & cameraId,TorchModeStatus status,SystemCameraKind systemCameraKind)255 void CameraService::broadcastTorchModeStatus(const String8& cameraId, TorchModeStatus status,
256         SystemCameraKind systemCameraKind) {
257     Mutex::Autolock lock(mStatusListenerLock);
258     for (auto& i : mListenerList) {
259         if (shouldSkipStatusUpdates(systemCameraKind, i->isVendorListener(), i->getListenerPid(),
260                 i->getListenerUid())) {
261             ALOGV("Skipping torch callback for system-only camera device %s",
262                     cameraId.c_str());
263             continue;
264         }
265         i->getListener()->onTorchStatusChanged(mapToInterface(status), String16{cameraId});
266     }
267 }
268 
~CameraService()269 CameraService::~CameraService() {
270     VendorTagDescriptor::clearGlobalVendorTagDescriptor();
271     mUidPolicy->unregisterSelf();
272     mSensorPrivacyPolicy->unregisterSelf();
273     mInjectionStatusListener->removeListener();
274 }
275 
onNewProviderRegistered()276 void CameraService::onNewProviderRegistered() {
277     enumerateProviders();
278 }
279 
filterAPI1SystemCameraLocked(const std::vector<std::string> & normalDeviceIds)280 void CameraService::filterAPI1SystemCameraLocked(
281         const std::vector<std::string> &normalDeviceIds) {
282     mNormalDeviceIdsWithoutSystemCamera.clear();
283     for (auto &deviceId : normalDeviceIds) {
284         SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
285         if (getSystemCameraKind(String8(deviceId.c_str()), &deviceKind) != OK) {
286             ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, deviceId.c_str());
287             continue;
288         }
289         if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
290             // All system camera ids will necessarily come after public camera
291             // device ids as per the HAL interface contract.
292             break;
293         }
294         mNormalDeviceIdsWithoutSystemCamera.push_back(deviceId);
295     }
296     ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
297               mNormalDeviceIdsWithoutSystemCamera.size());
298 }
299 
getSystemCameraKind(const String8 & cameraId,SystemCameraKind * kind) const300 status_t CameraService::getSystemCameraKind(const String8& cameraId, SystemCameraKind *kind) const {
301     auto state = getCameraState(cameraId);
302     if (state != nullptr) {
303         *kind = state->getSystemCameraKind();
304         return OK;
305     }
306     // Hidden physical camera ids won't have CameraState
307     return mCameraProviderManager->getSystemCameraKind(cameraId.c_str(), kind);
308 }
309 
updateCameraNumAndIds()310 void CameraService::updateCameraNumAndIds() {
311     Mutex::Autolock l(mServiceLock);
312     std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
313     // Excludes hidden secure cameras
314     mNumberOfCameras =
315             systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
316     mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
317     mNormalDeviceIds =
318             mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
319     filterAPI1SystemCameraLocked(mNormalDeviceIds);
320 }
321 
filterSPerfClassCharacteristicsLocked()322 void CameraService::filterSPerfClassCharacteristicsLocked() {
323     // To claim to be S Performance primary cameras, the cameras must be
324     // backward compatible. So performance class primary camera Ids must be API1
325     // compatible.
326     bool firstRearCameraSeen = false, firstFrontCameraSeen = false;
327     for (const auto& cameraId : mNormalDeviceIdsWithoutSystemCamera) {
328         int facing = -1;
329         int orientation = 0;
330         String8 cameraId8(cameraId.c_str());
331         getDeviceVersion(cameraId8, /*out*/&facing, /*out*/&orientation);
332         if (facing == -1) {
333             ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
334             return;
335         }
336 
337         if ((facing == hardware::CAMERA_FACING_BACK && !firstRearCameraSeen) ||
338                 (facing == hardware::CAMERA_FACING_FRONT && !firstFrontCameraSeen)) {
339             status_t res = mCameraProviderManager->filterSmallJpegSizes(cameraId);
340             if (res == OK) {
341                 mPerfClassPrimaryCameraIds.insert(cameraId);
342             } else {
343                 ALOGE("%s: Failed to filter small JPEG sizes for performance class primary "
344                         "camera %s: %s(%d)", __FUNCTION__, cameraId.c_str(), strerror(-res), res);
345                 break;
346             }
347 
348             if (facing == hardware::CAMERA_FACING_BACK) {
349                 firstRearCameraSeen = true;
350             }
351             if (facing == hardware::CAMERA_FACING_FRONT) {
352                 firstFrontCameraSeen = true;
353             }
354         }
355 
356         if (firstRearCameraSeen && firstFrontCameraSeen) {
357             break;
358         }
359     }
360 }
361 
addStates(const String8 id)362 void CameraService::addStates(const String8 id) {
363     std::string cameraId(id.c_str());
364     hardware::camera::common::V1_0::CameraResourceCost cost;
365     status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
366     SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
367     if (res != OK) {
368         ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
369         return;
370     }
371     res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
372     if (res != OK) {
373         ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
374         return;
375     }
376     std::set<String8> conflicting;
377     for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
378         conflicting.emplace(String8(cost.conflictingDevices[i].c_str()));
379     }
380 
381     {
382         Mutex::Autolock lock(mCameraStatesLock);
383         mCameraStates.emplace(id, std::make_shared<CameraState>(id, cost.resourceCost,
384                                                                 conflicting, deviceKind));
385     }
386 
387     if (mFlashlight->hasFlashUnit(id)) {
388         Mutex::Autolock al(mTorchStatusMutex);
389         mTorchStatusMap.add(id, TorchModeStatus::AVAILABLE_OFF);
390 
391         broadcastTorchModeStatus(id, TorchModeStatus::AVAILABLE_OFF, deviceKind);
392     }
393 
394     updateCameraNumAndIds();
395     logDeviceAdded(id, "Device added");
396 }
397 
removeStates(const String8 id)398 void CameraService::removeStates(const String8 id) {
399     updateCameraNumAndIds();
400     if (mFlashlight->hasFlashUnit(id)) {
401         Mutex::Autolock al(mTorchStatusMutex);
402         mTorchStatusMap.removeItem(id);
403     }
404 
405     {
406         Mutex::Autolock lock(mCameraStatesLock);
407         mCameraStates.erase(id);
408     }
409 }
410 
onDeviceStatusChanged(const String8 & id,CameraDeviceStatus newHalStatus)411 void CameraService::onDeviceStatusChanged(const String8& id,
412         CameraDeviceStatus newHalStatus) {
413     ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
414             id.string(), newHalStatus);
415 
416     StatusInternal newStatus = mapToInternal(newHalStatus);
417 
418     std::shared_ptr<CameraState> state = getCameraState(id);
419 
420     if (state == nullptr) {
421         if (newStatus == StatusInternal::PRESENT) {
422             ALOGI("%s: Unknown camera ID %s, a new camera is added",
423                     __FUNCTION__, id.string());
424 
425             // First add as absent to make sure clients are notified below
426             addStates(id);
427 
428             updateStatus(newStatus, id);
429         } else {
430             ALOGE("%s: Bad camera ID %s", __FUNCTION__, id.string());
431         }
432         return;
433     }
434 
435     StatusInternal oldStatus = state->getStatus();
436 
437     if (oldStatus == newStatus) {
438         ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
439         return;
440     }
441 
442     if (newStatus == StatusInternal::NOT_PRESENT) {
443         logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
444                 newStatus));
445 
446         // Set the device status to NOT_PRESENT, clients will no longer be able to connect
447         // to this device until the status changes
448         updateStatus(StatusInternal::NOT_PRESENT, id);
449 
450         sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
451         {
452             // Don't do this in updateStatus to avoid deadlock over mServiceLock
453             Mutex::Autolock lock(mServiceLock);
454 
455             // Remove cached shim parameters
456             state->setShimParams(CameraParameters());
457 
458             // Remove online as well as offline client from the list of active clients,
459             // if they are present
460             clientToDisconnectOnline = removeClientLocked(id);
461             clientToDisconnectOffline = removeClientLocked(kOfflineDevice + id);
462         }
463 
464         disconnectClient(id, clientToDisconnectOnline);
465         disconnectClient(kOfflineDevice + id, clientToDisconnectOffline);
466 
467         removeStates(id);
468     } else {
469         if (oldStatus == StatusInternal::NOT_PRESENT) {
470             logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
471                     newStatus));
472         }
473         updateStatus(newStatus, id);
474     }
475 }
476 
onDeviceStatusChanged(const String8 & id,const String8 & physicalId,CameraDeviceStatus newHalStatus)477 void CameraService::onDeviceStatusChanged(const String8& id,
478         const String8& physicalId,
479         CameraDeviceStatus newHalStatus) {
480     ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
481             __FUNCTION__, id.string(), physicalId.string(), newHalStatus);
482 
483     StatusInternal newStatus = mapToInternal(newHalStatus);
484 
485     std::shared_ptr<CameraState> state = getCameraState(id);
486 
487     if (state == nullptr) {
488         ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
489                 __FUNCTION__, id.string(), physicalId.string());
490         return;
491     }
492 
493     StatusInternal logicalCameraStatus = state->getStatus();
494     if (logicalCameraStatus != StatusInternal::PRESENT &&
495             logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
496         ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
497                 __FUNCTION__, physicalId.string(), newHalStatus, logicalCameraStatus);
498         return;
499     }
500 
501     bool updated = false;
502     if (newStatus == StatusInternal::PRESENT) {
503         updated = state->removeUnavailablePhysicalId(physicalId);
504     } else {
505         updated = state->addUnavailablePhysicalId(physicalId);
506     }
507 
508     if (updated) {
509         String8 idCombo = id + " : " + physicalId;
510         if (newStatus == StatusInternal::PRESENT) {
511             logDeviceAdded(idCombo,
512                     String8::format("Device status changed to %d", newStatus));
513         } else {
514             logDeviceRemoved(idCombo,
515                     String8::format("Device status changed to %d", newStatus));
516         }
517         // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
518         SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
519         if (getSystemCameraKind(id, &deviceKind) != OK) {
520             ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.string());
521             return;
522         }
523         String16 id16(id), physicalId16(physicalId);
524         Mutex::Autolock lock(mStatusListenerLock);
525         for (auto& listener : mListenerList) {
526             if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
527                     listener->getListenerPid(), listener->getListenerUid())) {
528                 ALOGV("Skipping discovery callback for system-only camera device %s",
529                         id.c_str());
530                 continue;
531             }
532             listener->getListener()->onPhysicalCameraStatusChanged(mapToInterface(newStatus),
533                     id16, physicalId16);
534         }
535     }
536 }
537 
disconnectClient(const String8 & id,sp<BasicClient> clientToDisconnect)538 void CameraService::disconnectClient(const String8& id, sp<BasicClient> clientToDisconnect) {
539     if (clientToDisconnect.get() != nullptr) {
540         ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
541                 __FUNCTION__, id.string());
542         // Notify the client of disconnection
543         clientToDisconnect->notifyError(
544                 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
545                 CaptureResultExtras{});
546         clientToDisconnect->disconnect();
547     }
548 }
549 
onTorchStatusChanged(const String8 & cameraId,TorchModeStatus newStatus)550 void CameraService::onTorchStatusChanged(const String8& cameraId,
551         TorchModeStatus newStatus) {
552     SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
553     status_t res = getSystemCameraKind(cameraId, &systemCameraKind);
554     if (res != OK) {
555         ALOGE("%s: Could not get system camera kind for camera id %s", __FUNCTION__,
556                 cameraId.string());
557         return;
558     }
559     Mutex::Autolock al(mTorchStatusMutex);
560     onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
561 }
562 
onTorchStatusChangedLocked(const String8 & cameraId,TorchModeStatus newStatus,SystemCameraKind systemCameraKind)563 void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
564         TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
565     ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
566             __FUNCTION__, cameraId.string(), newStatus);
567 
568     TorchModeStatus status;
569     status_t res = getTorchStatusLocked(cameraId, &status);
570     if (res) {
571         ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
572                 __FUNCTION__, cameraId.string(), strerror(-res), res);
573         return;
574     }
575     if (status == newStatus) {
576         return;
577     }
578 
579     res = setTorchStatusLocked(cameraId, newStatus);
580     if (res) {
581         ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
582                 (uint32_t)newStatus, strerror(-res), res);
583         return;
584     }
585 
586     {
587         // Update battery life logging for flashlight
588         Mutex::Autolock al(mTorchUidMapMutex);
589         auto iter = mTorchUidMap.find(cameraId);
590         if (iter != mTorchUidMap.end()) {
591             int oldUid = iter->second.second;
592             int newUid = iter->second.first;
593             BatteryNotifier& notifier(BatteryNotifier::getInstance());
594             if (oldUid != newUid) {
595                 // If the UID has changed, log the status and update current UID in mTorchUidMap
596                 if (status == TorchModeStatus::AVAILABLE_ON) {
597                     notifier.noteFlashlightOff(cameraId, oldUid);
598                 }
599                 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
600                     notifier.noteFlashlightOn(cameraId, newUid);
601                 }
602                 iter->second.second = newUid;
603             } else {
604                 // If the UID has not changed, log the status
605                 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
606                     notifier.noteFlashlightOn(cameraId, oldUid);
607                 } else {
608                     notifier.noteFlashlightOff(cameraId, oldUid);
609                 }
610             }
611         }
612     }
613     broadcastTorchModeStatus(cameraId, newStatus, systemCameraKind);
614 }
615 
hasPermissionsForSystemCamera(int callingPid,int callingUid)616 static bool hasPermissionsForSystemCamera(int callingPid, int callingUid) {
617     return checkPermission(sSystemCameraPermission, callingPid, callingUid) &&
618             checkPermission(sCameraPermission, callingPid, callingUid);
619 }
620 
getNumberOfCameras(int32_t type,int32_t * numCameras)621 Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
622     ATRACE_CALL();
623     Mutex::Autolock l(mServiceLock);
624     bool hasSystemCameraPermissions =
625             hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
626                     CameraThreadState::getCallingUid());
627     switch (type) {
628         case CAMERA_TYPE_BACKWARD_COMPATIBLE:
629             if (hasSystemCameraPermissions) {
630                 *numCameras = static_cast<int>(mNormalDeviceIds.size());
631             } else {
632                 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
633             }
634             break;
635         case CAMERA_TYPE_ALL:
636             if (hasSystemCameraPermissions) {
637                 *numCameras = mNumberOfCameras;
638             } else {
639                 *numCameras = mNumberOfCamerasWithoutSystemCamera;
640             }
641             break;
642         default:
643             ALOGW("%s: Unknown camera type %d",
644                     __FUNCTION__, type);
645             return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
646                     "Unknown camera type %d", type);
647     }
648     return Status::ok();
649 }
650 
getCameraInfo(int cameraId,CameraInfo * cameraInfo)651 Status CameraService::getCameraInfo(int cameraId,
652         CameraInfo* cameraInfo) {
653     ATRACE_CALL();
654     Mutex::Autolock l(mServiceLock);
655     std::string cameraIdStr = cameraIdIntToStrLocked(cameraId);
656     if (shouldRejectSystemCameraConnection(String8(cameraIdStr.c_str()))) {
657         return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
658                 "characteristics for system only device %s: ", cameraIdStr.c_str());
659     }
660 
661     if (!mInitialized) {
662         logServiceError(String8::format("Camera subsystem is not available"),ERROR_DISCONNECTED);
663         return STATUS_ERROR(ERROR_DISCONNECTED,
664                 "Camera subsystem is not available");
665     }
666     bool hasSystemCameraPermissions =
667             hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
668                     CameraThreadState::getCallingUid());
669     int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
670     if (hasSystemCameraPermissions) {
671         cameraIdBound = mNumberOfCameras;
672     }
673     if (cameraId < 0 || cameraId >= cameraIdBound) {
674         return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
675                 "CameraId is not valid");
676     }
677 
678     Status ret = Status::ok();
679     status_t err = mCameraProviderManager->getCameraInfo(
680             cameraIdStr.c_str(), cameraInfo);
681     if (err != OK) {
682         ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
683                 "Error retrieving camera info from device %d: %s (%d)", cameraId,
684                 strerror(-err), err);
685         logServiceError(String8::format("Error retrieving camera info from device %d",cameraId),
686             ERROR_INVALID_OPERATION);
687     }
688 
689     return ret;
690 }
691 
cameraIdIntToStrLocked(int cameraIdInt)692 std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
693     const std::vector<std::string> *deviceIds = &mNormalDeviceIdsWithoutSystemCamera;
694     auto callingPid = CameraThreadState::getCallingPid();
695     auto callingUid = CameraThreadState::getCallingUid();
696     if (checkPermission(sSystemCameraPermission, callingPid, callingUid) ||
697             getpid() == callingPid) {
698         deviceIds = &mNormalDeviceIds;
699     }
700     if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(deviceIds->size())) {
701         ALOGE("%s: input id %d invalid: valid range  (0, %zu)",
702                 __FUNCTION__, cameraIdInt, deviceIds->size());
703         return std::string{};
704     }
705 
706     return (*deviceIds)[cameraIdInt];
707 }
708 
cameraIdIntToStr(int cameraIdInt)709 String8 CameraService::cameraIdIntToStr(int cameraIdInt) {
710     Mutex::Autolock lock(mServiceLock);
711     return String8(cameraIdIntToStrLocked(cameraIdInt).c_str());
712 }
713 
getCameraCharacteristics(const String16 & cameraId,int targetSdkVersion,CameraMetadata * cameraInfo)714 Status CameraService::getCameraCharacteristics(const String16& cameraId,
715         int targetSdkVersion, CameraMetadata* cameraInfo) {
716     ATRACE_CALL();
717     if (!cameraInfo) {
718         ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
719         return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
720     }
721 
722     if (!mInitialized) {
723         ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
724         logServiceError(String8::format("Camera subsystem is not available"),ERROR_DISCONNECTED);
725         return STATUS_ERROR(ERROR_DISCONNECTED,
726                 "Camera subsystem is not available");;
727     }
728 
729     if (shouldRejectSystemCameraConnection(String8(cameraId))) {
730         return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
731                 "characteristics for system only device %s: ", String8(cameraId).string());
732     }
733 
734     Status ret{};
735 
736 
737     std::string cameraIdStr = String8(cameraId).string();
738     bool overrideForPerfClass =
739             SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
740                     cameraIdStr, targetSdkVersion);
741     status_t res = mCameraProviderManager->getCameraCharacteristics(
742             cameraIdStr, overrideForPerfClass, cameraInfo);
743     if (res != OK) {
744         if (res == NAME_NOT_FOUND) {
745             return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
746                     "characteristics for unknown device %s: %s (%d)", String8(cameraId).string(),
747                     strerror(-res), res);
748         } else {
749             logServiceError(String8::format("Unable to retrieve camera characteristics for "
750             "device %s.", String8(cameraId).string()),ERROR_INVALID_OPERATION);
751             return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
752                     "characteristics for device %s: %s (%d)", String8(cameraId).string(),
753                     strerror(-res), res);
754         }
755     }
756     SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
757     if (getSystemCameraKind(String8(cameraId), &deviceKind) != OK) {
758         ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, String8(cameraId).string());
759         return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera kind "
760                 "for device %s", String8(cameraId).string());
761     }
762     int callingPid = CameraThreadState::getCallingPid();
763     int callingUid = CameraThreadState::getCallingUid();
764     std::vector<int32_t> tagsRemoved;
765     // If it's not calling from cameraserver, check the permission only if
766     // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
767     // it would've already been checked in shouldRejectSystemCameraConnection.
768     if ((callingPid != getpid()) &&
769             (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
770             !checkPermission(sCameraPermission, callingPid, callingUid)) {
771         res = cameraInfo->removePermissionEntries(
772                 mCameraProviderManager->getProviderTagIdLocked(String8(cameraId).string()),
773                 &tagsRemoved);
774         if (res != OK) {
775             cameraInfo->clear();
776             return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
777                     " characteristics needing camera permission for device %s: %s (%d)",
778                     String8(cameraId).string(), strerror(-res), res);
779         }
780     }
781 
782     if (!tagsRemoved.empty()) {
783         res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
784                 tagsRemoved.data(), tagsRemoved.size());
785         if (res != OK) {
786             cameraInfo->clear();
787             return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
788                     "keys needing permission for device %s: %s (%d)", String8(cameraId).string(),
789                     strerror(-res), res);
790         }
791     }
792 
793     return ret;
794 }
795 
getFormattedCurrentTime()796 String8 CameraService::getFormattedCurrentTime() {
797     time_t now = time(nullptr);
798     char formattedTime[64];
799     strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
800     return String8(formattedTime);
801 }
802 
getCameraVendorTagDescriptor(hardware::camera2::params::VendorTagDescriptor * desc)803 Status CameraService::getCameraVendorTagDescriptor(
804         /*out*/
805         hardware::camera2::params::VendorTagDescriptor* desc) {
806     ATRACE_CALL();
807     if (!mInitialized) {
808         ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
809         return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
810     }
811     sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
812     if (globalDescriptor != nullptr) {
813         *desc = *(globalDescriptor.get());
814     }
815     return Status::ok();
816 }
817 
getCameraVendorTagCache(hardware::camera2::params::VendorTagDescriptorCache * cache)818 Status CameraService::getCameraVendorTagCache(
819         /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
820     ATRACE_CALL();
821     if (!mInitialized) {
822         ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
823         return STATUS_ERROR(ERROR_DISCONNECTED,
824                 "Camera subsystem not available");
825     }
826     sp<VendorTagDescriptorCache> globalCache =
827             VendorTagDescriptorCache::getGlobalVendorTagCache();
828     if (globalCache != nullptr) {
829         *cache = *(globalCache.get());
830     }
831     return Status::ok();
832 }
833 
clearCachedVariables()834 void CameraService::clearCachedVariables() {
835     BasicClient::BasicClient::sCameraService = nullptr;
836 }
837 
getDeviceVersion(const String8 & cameraId,int * facing,int * orientation)838 int CameraService::getDeviceVersion(const String8& cameraId, int* facing, int* orientation) {
839     ATRACE_CALL();
840 
841     int deviceVersion = 0;
842 
843     status_t res;
844     hardware::hidl_version maxVersion{0,0};
845     res = mCameraProviderManager->getHighestSupportedVersion(cameraId.string(),
846             &maxVersion);
847     if (res != OK) return -1;
848     deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
849 
850     hardware::CameraInfo info;
851     if (facing) {
852         res = mCameraProviderManager->getCameraInfo(cameraId.string(), &info);
853         if (res != OK) return -1;
854         *facing = info.facing;
855         if (orientation) {
856             *orientation = info.orientation;
857         }
858     }
859 
860     return deviceVersion;
861 }
862 
filterGetInfoErrorCode(status_t err)863 Status CameraService::filterGetInfoErrorCode(status_t err) {
864     switch(err) {
865         case NO_ERROR:
866             return Status::ok();
867         case BAD_VALUE:
868             return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
869                     "CameraId is not valid for HAL module");
870         case NO_INIT:
871             return STATUS_ERROR(ERROR_DISCONNECTED,
872                     "Camera device not available");
873         default:
874             return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
875                     "Camera HAL encountered error %d: %s",
876                     err, strerror(-err));
877     }
878 }
879 
makeClient(const sp<CameraService> & cameraService,const sp<IInterface> & cameraCb,const String16 & packageName,const std::optional<String16> & featureId,const String8 & cameraId,int api1CameraId,int facing,int sensorOrientation,int clientPid,uid_t clientUid,int servicePid,int deviceVersion,apiLevel effectiveApiLevel,bool overrideForPerfClass,sp<BasicClient> * client)880 Status CameraService::makeClient(const sp<CameraService>& cameraService,
881         const sp<IInterface>& cameraCb, const String16& packageName,
882         const std::optional<String16>& featureId,  const String8& cameraId,
883         int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
884         int servicePid, int deviceVersion, apiLevel effectiveApiLevel, bool overrideForPerfClass,
885         /*out*/sp<BasicClient>* client) {
886 
887     // Create CameraClient based on device version reported by the HAL.
888     switch(deviceVersion) {
889         case CAMERA_DEVICE_API_VERSION_1_0:
890             ALOGE("Camera using old HAL version: %d", deviceVersion);
891             return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
892                     "Camera device \"%s\" HAL version %d no longer supported",
893                     cameraId.string(), deviceVersion);
894             break;
895         case CAMERA_DEVICE_API_VERSION_3_0:
896         case CAMERA_DEVICE_API_VERSION_3_1:
897         case CAMERA_DEVICE_API_VERSION_3_2:
898         case CAMERA_DEVICE_API_VERSION_3_3:
899         case CAMERA_DEVICE_API_VERSION_3_4:
900         case CAMERA_DEVICE_API_VERSION_3_5:
901         case CAMERA_DEVICE_API_VERSION_3_6:
902         case CAMERA_DEVICE_API_VERSION_3_7:
903             if (effectiveApiLevel == API_1) { // Camera1 API route
904                 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
905                 *client = new Camera2Client(cameraService, tmp, packageName, featureId,
906                         cameraId, api1CameraId,
907                         facing, sensorOrientation, clientPid, clientUid,
908                         servicePid, overrideForPerfClass);
909             } else { // Camera2 API route
910                 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
911                         static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
912                 *client = new CameraDeviceClient(cameraService, tmp, packageName, featureId,
913                         cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid,
914                         overrideForPerfClass);
915             }
916             break;
917         default:
918             // Should not be reachable
919             ALOGE("Unknown camera device HAL version: %d", deviceVersion);
920             return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
921                     "Camera device \"%s\" has unknown HAL version %d",
922                     cameraId.string(), deviceVersion);
923     }
924     return Status::ok();
925 }
926 
toString(std::set<userid_t> intSet)927 String8 CameraService::toString(std::set<userid_t> intSet) {
928     String8 s("");
929     bool first = true;
930     for (userid_t i : intSet) {
931         if (first) {
932             s.appendFormat("%d", i);
933             first = false;
934         } else {
935             s.appendFormat(", %d", i);
936         }
937     }
938     return s;
939 }
940 
mapToInterface(TorchModeStatus status)941 int32_t CameraService::mapToInterface(TorchModeStatus status) {
942     int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
943     switch (status) {
944         case TorchModeStatus::NOT_AVAILABLE:
945             serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
946             break;
947         case TorchModeStatus::AVAILABLE_OFF:
948             serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
949             break;
950         case TorchModeStatus::AVAILABLE_ON:
951             serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
952             break;
953         default:
954             ALOGW("Unknown new flash status: %d", status);
955     }
956     return serviceStatus;
957 }
958 
mapToInternal(CameraDeviceStatus status)959 CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
960     StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
961     switch (status) {
962         case CameraDeviceStatus::NOT_PRESENT:
963             serviceStatus = StatusInternal::NOT_PRESENT;
964             break;
965         case CameraDeviceStatus::PRESENT:
966             serviceStatus = StatusInternal::PRESENT;
967             break;
968         case CameraDeviceStatus::ENUMERATING:
969             serviceStatus = StatusInternal::ENUMERATING;
970             break;
971         default:
972             ALOGW("Unknown new HAL device status: %d", status);
973     }
974     return serviceStatus;
975 }
976 
mapToInterface(StatusInternal status)977 int32_t CameraService::mapToInterface(StatusInternal status) {
978     int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
979     switch (status) {
980         case StatusInternal::NOT_PRESENT:
981             serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
982             break;
983         case StatusInternal::PRESENT:
984             serviceStatus = ICameraServiceListener::STATUS_PRESENT;
985             break;
986         case StatusInternal::ENUMERATING:
987             serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
988             break;
989         case StatusInternal::NOT_AVAILABLE:
990             serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
991             break;
992         case StatusInternal::UNKNOWN:
993             serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
994             break;
995         default:
996             ALOGW("Unknown new internal device status: %d", status);
997     }
998     return serviceStatus;
999 }
1000 
initializeShimMetadata(int cameraId)1001 Status CameraService::initializeShimMetadata(int cameraId) {
1002     int uid = CameraThreadState::getCallingUid();
1003 
1004     String16 internalPackageName("cameraserver");
1005     String8 id = String8::format("%d", cameraId);
1006     Status ret = Status::ok();
1007     sp<Client> tmp = nullptr;
1008     if (!(ret = connectHelper<ICameraClient,Client>(
1009             sp<ICameraClient>{nullptr}, id, cameraId,
1010             internalPackageName, {}, uid, USE_CALLING_PID,
1011             API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0,
1012             /*targetSdkVersion*/ __ANDROID_API_FUTURE__, /*out*/ tmp)
1013             ).isOk()) {
1014         ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
1015     }
1016     return ret;
1017 }
1018 
getLegacyParametersLazy(int cameraId,CameraParameters * parameters)1019 Status CameraService::getLegacyParametersLazy(int cameraId,
1020         /*out*/
1021         CameraParameters* parameters) {
1022 
1023     ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1024 
1025     Status ret = Status::ok();
1026 
1027     if (parameters == NULL) {
1028         ALOGE("%s: parameters must not be null", __FUNCTION__);
1029         return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
1030     }
1031 
1032     String8 id = String8::format("%d", cameraId);
1033 
1034     // Check if we already have parameters
1035     {
1036         // Scope for service lock
1037         Mutex::Autolock lock(mServiceLock);
1038         auto cameraState = getCameraState(id);
1039         if (cameraState == nullptr) {
1040             ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
1041             return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1042                     "Invalid camera ID: %s", id.string());
1043         }
1044         CameraParameters p = cameraState->getShimParams();
1045         if (!p.isEmpty()) {
1046             *parameters = p;
1047             return ret;
1048         }
1049     }
1050 
1051     int64_t token = CameraThreadState::clearCallingIdentity();
1052     ret = initializeShimMetadata(cameraId);
1053     CameraThreadState::restoreCallingIdentity(token);
1054     if (!ret.isOk()) {
1055         // Error already logged by callee
1056         return ret;
1057     }
1058 
1059     // Check for parameters again
1060     {
1061         // Scope for service lock
1062         Mutex::Autolock lock(mServiceLock);
1063         auto cameraState = getCameraState(id);
1064         if (cameraState == nullptr) {
1065             ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
1066             return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1067                     "Invalid camera ID: %s", id.string());
1068         }
1069         CameraParameters p = cameraState->getShimParams();
1070         if (!p.isEmpty()) {
1071             *parameters = p;
1072             return ret;
1073         }
1074     }
1075 
1076     ALOGE("%s: Parameters were not initialized, or were empty.  Device may not be present.",
1077             __FUNCTION__);
1078     return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
1079 }
1080 
1081 // Can camera service trust the caller based on the calling UID?
isTrustedCallingUid(uid_t uid)1082 static bool isTrustedCallingUid(uid_t uid) {
1083     switch (uid) {
1084         case AID_MEDIA:        // mediaserver
1085         case AID_CAMERASERVER: // cameraserver
1086         case AID_RADIO:        // telephony
1087             return true;
1088         default:
1089             return false;
1090     }
1091 }
1092 
getUidForPackage(String16 packageName,int userId,uid_t & uid,int err)1093 static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1094     PermissionController pc;
1095     uid = pc.getPackageUid(packageName, 0);
1096     if (uid <= 0) {
1097         ALOGE("Unknown package: '%s'", String8(packageName).string());
1098         dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
1099         return BAD_VALUE;
1100     }
1101 
1102     if (userId < 0) {
1103         ALOGE("Invalid user: %d", userId);
1104         dprintf(err, "Invalid user: %d\n", userId);
1105         return BAD_VALUE;
1106     }
1107 
1108     uid = multiuser_get_uid(userId, uid);
1109     return NO_ERROR;
1110 }
1111 
validateConnectLocked(const String8 & cameraId,const String8 & clientName8,int & clientUid,int & clientPid,int & originalClientPid) const1112 Status CameraService::validateConnectLocked(const String8& cameraId,
1113         const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
1114         /*out*/int& originalClientPid) const {
1115 
1116 #ifdef __BRILLO__
1117     UNUSED(clientName8);
1118     UNUSED(clientUid);
1119     UNUSED(clientPid);
1120     UNUSED(originalClientPid);
1121 #else
1122     Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1123             originalClientPid);
1124     if (!allowed.isOk()) {
1125         return allowed;
1126     }
1127 #endif  // __BRILLO__
1128 
1129     int callingPid = CameraThreadState::getCallingPid();
1130 
1131     if (!mInitialized) {
1132         ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1133                 callingPid);
1134         return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1135                 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
1136     }
1137 
1138     if (getCameraState(cameraId) == nullptr) {
1139         ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1140                 cameraId.string());
1141         return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1142                 "No camera device with ID \"%s\" available", cameraId.string());
1143     }
1144 
1145     status_t err = checkIfDeviceIsUsable(cameraId);
1146     if (err != NO_ERROR) {
1147         switch(err) {
1148             case -ENODEV:
1149             case -EBUSY:
1150                 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1151                         "No camera device with ID \"%s\" currently available", cameraId.string());
1152             default:
1153                 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1154                         "Unknown error connecting to ID \"%s\"", cameraId.string());
1155         }
1156     }
1157     return Status::ok();
1158 }
1159 
validateClientPermissionsLocked(const String8 & cameraId,const String8 & clientName8,int & clientUid,int & clientPid,int & originalClientPid) const1160 Status CameraService::validateClientPermissionsLocked(const String8& cameraId,
1161         const String8& clientName8, int& clientUid, int& clientPid,
1162         /*out*/int& originalClientPid) const {
1163     int callingPid = CameraThreadState::getCallingPid();
1164     int callingUid = CameraThreadState::getCallingUid();
1165 
1166     // Check if we can trust clientUid
1167     if (clientUid == USE_CALLING_UID) {
1168         clientUid = callingUid;
1169     } else if (!isTrustedCallingUid(callingUid)) {
1170         ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1171                 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
1172         return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1173                 "Untrusted caller (calling PID %d, UID %d) trying to "
1174                 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1175                 callingPid, callingUid, cameraId.string(),
1176                 clientName8.string(), clientUid, clientPid);
1177     }
1178 
1179     // Check if we can trust clientPid
1180     if (clientPid == USE_CALLING_PID) {
1181         clientPid = callingPid;
1182     } else if (!isTrustedCallingUid(callingUid)) {
1183         ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1184                 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
1185         return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1186                 "Untrusted caller (calling PID %d, UID %d) trying to "
1187                 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1188                 callingPid, callingUid, cameraId.string(),
1189                 clientName8.string(), clientUid, clientPid);
1190     }
1191 
1192     if (shouldRejectSystemCameraConnection(cameraId)) {
1193         ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1194                 cameraId.c_str());
1195         return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
1196                                 "available", cameraId.string());
1197     }
1198     SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1199     if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1200         ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
1201         return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
1202                 "found while trying to query device kind", cameraId.string());
1203 
1204     }
1205 
1206     // If it's not calling from cameraserver, check the permission if the
1207     // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1208     // android.permission.SYSTEM_CAMERA for system only camera devices).
1209     if (callingPid != getpid() &&
1210                 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
1211                 !checkPermission(sCameraPermission, clientPid, clientUid)) {
1212         ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
1213         return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1214                 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
1215                 clientName8.string(), clientUid, clientPid, cameraId.string());
1216     }
1217 
1218     // Make sure the UID is in an active state to use the camera
1219     if (!mUidPolicy->isUidActive(callingUid, String16(clientName8))) {
1220         int32_t procState = mUidPolicy->getProcState(callingUid);
1221         ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1222             clientPid, clientUid);
1223         return STATUS_ERROR_FMT(ERROR_DISABLED,
1224                 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1225                 "calling UID %d proc state %" PRId32 ")",
1226                 clientName8.string(), clientUid, clientPid, cameraId.string(),
1227                 callingUid, procState);
1228     }
1229 
1230     // If sensor privacy is enabled then prevent access to the camera
1231     if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1232         ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1233         return STATUS_ERROR_FMT(ERROR_DISABLED,
1234                 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
1235                 "is enabled", clientName8.string(), clientUid, clientPid, cameraId.string());
1236     }
1237 
1238     // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1239     // connected to camera service directly.
1240     originalClientPid = clientPid;
1241     clientPid = callingPid;
1242 
1243     userid_t clientUserId = multiuser_get_user_id(clientUid);
1244 
1245     // Only allow clients who are being used by the current foreground device user, unless calling
1246     // from our own process OR the caller is using the cameraserver's HIDL interface.
1247     if (getCurrentServingCall() != BinderCallType::HWBINDER && callingPid != getpid() &&
1248             (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
1249         ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1250                 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
1251                 toString(mAllowedUsers).string());
1252         return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1253                 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
1254                 clientUserId, cameraId.string());
1255     }
1256 
1257     return Status::ok();
1258 }
1259 
checkIfDeviceIsUsable(const String8 & cameraId) const1260 status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
1261     auto cameraState = getCameraState(cameraId);
1262     int callingPid = CameraThreadState::getCallingPid();
1263     if (cameraState == nullptr) {
1264         ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1265                 cameraId.string());
1266         return -ENODEV;
1267     }
1268 
1269     StatusInternal currentStatus = cameraState->getStatus();
1270     if (currentStatus == StatusInternal::NOT_PRESENT) {
1271         ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
1272                 callingPid, cameraId.string());
1273         return -ENODEV;
1274     } else if (currentStatus == StatusInternal::ENUMERATING) {
1275         ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
1276                 callingPid, cameraId.string());
1277         return -EBUSY;
1278     }
1279 
1280     return NO_ERROR;
1281 }
1282 
finishConnectLocked(const sp<BasicClient> & client,const CameraService::DescriptorPtr & desc,int oomScoreOffset)1283 void CameraService::finishConnectLocked(const sp<BasicClient>& client,
1284         const CameraService::DescriptorPtr& desc, int oomScoreOffset) {
1285 
1286     // Make a descriptor for the incoming client
1287     auto clientDescriptor =
1288             CameraService::CameraClientManager::makeClientDescriptor(client, desc,
1289                     oomScoreOffset);
1290     auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1291 
1292     logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
1293             String8(client->getPackageName()));
1294 
1295     if (evicted.size() > 0) {
1296         // This should never happen - clients should already have been removed in disconnect
1297         for (auto& i : evicted) {
1298             ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
1299                     __FUNCTION__, i->getKey().string());
1300         }
1301 
1302         LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1303                 __FUNCTION__);
1304     }
1305 
1306     // And register a death notification for the client callback. Do
1307     // this last to avoid Binder policy where a nested Binder
1308     // transaction might be pre-empted to service the client death
1309     // notification if the client process dies before linkToDeath is
1310     // invoked.
1311     sp<IBinder> remoteCallback = client->getRemote();
1312     if (remoteCallback != nullptr) {
1313         remoteCallback->linkToDeath(this);
1314     }
1315 }
1316 
handleEvictionsLocked(const String8 & cameraId,int clientPid,apiLevel effectiveApiLevel,const sp<IBinder> & remoteCallback,const String8 & packageName,int oomScoreOffset,sp<BasicClient> * client,std::shared_ptr<resource_policy::ClientDescriptor<String8,sp<BasicClient>>> * partial)1317 status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
1318         apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
1319         int oomScoreOffset,
1320         /*out*/
1321         sp<BasicClient>* client,
1322         std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
1323     ATRACE_CALL();
1324     status_t ret = NO_ERROR;
1325     std::vector<DescriptorPtr> evictedClients;
1326     DescriptorPtr clientDescriptor;
1327     {
1328         if (effectiveApiLevel == API_1) {
1329             // If we are using API1, any existing client for this camera ID with the same remote
1330             // should be returned rather than evicted to allow MediaRecorder to work properly.
1331 
1332             auto current = mActiveClientManager.get(cameraId);
1333             if (current != nullptr) {
1334                 auto clientSp = current->getValue();
1335                 if (clientSp.get() != nullptr) { // should never be needed
1336                     if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
1337                         ALOGW("CameraService connect called from same client, but with a different"
1338                                 " API level, evicting prior client...");
1339                     } else if (clientSp->getRemote() == remoteCallback) {
1340                         ALOGI("CameraService::connect X (PID %d) (second call from same"
1341                                 " app binder, returning the same client)", clientPid);
1342                         *client = clientSp;
1343                         return NO_ERROR;
1344                     }
1345                 }
1346             }
1347         }
1348 
1349         // Get current active client PIDs
1350         std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1351         ownerPids.push_back(clientPid);
1352 
1353         std::vector<int> priorityScores(ownerPids.size());
1354         std::vector<int> states(ownerPids.size());
1355 
1356         // Get priority scores of all active PIDs
1357         status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1358                 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1359                 /*out*/&priorityScores[0]);
1360         if (err != OK) {
1361             ALOGE("%s: Priority score query failed: %d",
1362                   __FUNCTION__, err);
1363             return err;
1364         }
1365 
1366         // Update all active clients' priorities
1367         std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
1368         for (size_t i = 0; i < ownerPids.size() - 1; i++) {
1369             pidToPriorityMap.emplace(ownerPids[i],
1370                     resource_policy::ClientPriority(priorityScores[i], states[i],
1371                             /* isVendorClient won't get copied over*/ false,
1372                             /* oomScoreOffset won't get copied over*/ 0));
1373         }
1374         mActiveClientManager.updatePriorities(pidToPriorityMap);
1375 
1376         // Get state for the given cameraId
1377         auto state = getCameraState(cameraId);
1378         if (state == nullptr) {
1379             ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1380                 clientPid, cameraId.string());
1381             // Should never get here because validateConnectLocked should have errored out
1382             return BAD_VALUE;
1383         }
1384 
1385         int32_t actualScore = priorityScores[priorityScores.size() - 1];
1386         int32_t actualState = states[states.size() - 1];
1387 
1388         // Make descriptor for incoming client. We store the oomScoreOffset
1389         // since we might need it later on new handleEvictionsLocked and
1390         // ProcessInfoService would not take that into account.
1391         clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1392                 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1393                 state->getConflicting(), actualScore, clientPid, actualState,
1394                 oomScoreOffset);
1395 
1396         resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1397 
1398         // Find clients that would be evicted
1399         auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1400 
1401         // If the incoming client was 'evicted,' higher priority clients have the camera in the
1402         // background, so we cannot do evictions
1403         if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1404             ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1405                     " priority).", clientPid);
1406 
1407             sp<BasicClient> clientSp = clientDescriptor->getValue();
1408             String8 curTime = getFormattedCurrentTime();
1409             auto incompatibleClients =
1410                     mActiveClientManager.getIncompatibleClients(clientDescriptor);
1411 
1412             String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
1413                     "(PID %d, score %d state %d) due to eviction policy", curTime.string(),
1414                     cameraId.string(), packageName.string(), clientPid,
1415                     clientPriority.getScore(), clientPriority.getState());
1416 
1417             for (auto& i : incompatibleClients) {
1418                 msg.appendFormat("\n   - Blocked by existing device %s client for package %s"
1419                         "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
1420                         i->getKey().string(),
1421                         String8{i->getValue()->getPackageName()}.string(),
1422                         i->getOwnerId(), i->getPriority().getScore(),
1423                         i->getPriority().getState());
1424                 ALOGE("   Conflicts with: Device %s, client package %s (PID %"
1425                         PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(),
1426                         String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
1427                         i->getPriority().getScore(), i->getPriority().getState());
1428             }
1429 
1430             // Log the client's attempt
1431             Mutex::Autolock l(mLogLock);
1432             mEventLog.add(msg);
1433 
1434             auto current = mActiveClientManager.get(cameraId);
1435             if (current != nullptr) {
1436                 return -EBUSY; // CAMERA_IN_USE
1437             } else {
1438                 return -EUSERS; // MAX_CAMERAS_IN_USE
1439             }
1440         }
1441 
1442         for (auto& i : evicted) {
1443             sp<BasicClient> clientSp = i->getValue();
1444             if (clientSp.get() == nullptr) {
1445                 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1446 
1447                 // TODO: Remove this
1448                 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1449                         __FUNCTION__);
1450                 mActiveClientManager.remove(i);
1451                 continue;
1452             }
1453 
1454             ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1455                     i->getKey().string());
1456             evictedClients.push_back(i);
1457 
1458             // Log the clients evicted
1459             logEvent(String8::format("EVICT device %s client held by package %s (PID"
1460                     " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1461                     " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
1462                     i->getKey().string(), String8{clientSp->getPackageName()}.string(),
1463                     i->getOwnerId(), i->getPriority().getScore(),
1464                     i->getPriority().getState(), cameraId.string(),
1465                     packageName.string(), clientPid, clientPriority.getScore(),
1466                     clientPriority.getState()));
1467 
1468             // Notify the client of disconnection
1469             clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
1470                     CaptureResultExtras());
1471         }
1472     }
1473 
1474     // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1475     // other clients from connecting in mServiceLockWrapper if held
1476     mServiceLock.unlock();
1477 
1478     // Clear caller identity temporarily so client disconnect PID checks work correctly
1479     int64_t token = CameraThreadState::clearCallingIdentity();
1480 
1481     // Destroy evicted clients
1482     for (auto& i : evictedClients) {
1483         // Disconnect is blocking, and should only have returned when HAL has cleaned up
1484         i->getValue()->disconnect(); // Clients will remove themselves from the active client list
1485     }
1486 
1487     CameraThreadState::restoreCallingIdentity(token);
1488 
1489     for (const auto& i : evictedClients) {
1490         ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1491                 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1492         ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1493         if (ret == TIMED_OUT) {
1494             ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1495                     "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1496                     mActiveClientManager.toString().string());
1497             return -EBUSY;
1498         }
1499         if (ret != NO_ERROR) {
1500             ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1501                     "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1502                     ret, mActiveClientManager.toString().string());
1503             return ret;
1504         }
1505     }
1506 
1507     evictedClients.clear();
1508 
1509     // Once clients have been disconnected, relock
1510     mServiceLock.lock();
1511 
1512     // Check again if the device was unplugged or something while we weren't holding mServiceLock
1513     if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1514         return ret;
1515     }
1516 
1517     *partial = clientDescriptor;
1518     return NO_ERROR;
1519 }
1520 
connect(const sp<ICameraClient> & cameraClient,int api1CameraId,const String16 & clientPackageName,int clientUid,int clientPid,int targetSdkVersion,sp<ICamera> * device)1521 Status CameraService::connect(
1522         const sp<ICameraClient>& cameraClient,
1523         int api1CameraId,
1524         const String16& clientPackageName,
1525         int clientUid,
1526         int clientPid,
1527         int targetSdkVersion,
1528         /*out*/
1529         sp<ICamera>* device) {
1530 
1531     ATRACE_CALL();
1532     Status ret = Status::ok();
1533 
1534     String8 id = cameraIdIntToStr(api1CameraId);
1535     sp<Client> client = nullptr;
1536     ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId,
1537             clientPackageName, {}, clientUid, clientPid, API_1,
1538             /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion, /*out*/client);
1539 
1540     if(!ret.isOk()) {
1541         logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
1542                 ret.toString8());
1543         return ret;
1544     }
1545 
1546     *device = client;
1547     return ret;
1548 }
1549 
shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,bool isVendorListener,int clientPid,int clientUid)1550 bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
1551         bool isVendorListener, int clientPid, int clientUid) {
1552     // If the client is not a vendor client, don't add listener if
1553     //   a) the camera is a publicly hidden secure camera OR
1554     //   b) the camera is a system only camera and the client doesn't
1555     //      have android.permission.SYSTEM_CAMERA permissions.
1556     if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
1557             (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1558             !hasPermissionsForSystemCamera(clientPid, clientUid)))) {
1559         return true;
1560     }
1561     return false;
1562 }
1563 
shouldRejectSystemCameraConnection(const String8 & cameraId) const1564 bool CameraService::shouldRejectSystemCameraConnection(const String8& cameraId) const {
1565     // Rules for rejection:
1566     // 1) If cameraserver tries to access this camera device, accept the
1567     //    connection.
1568     // 2) The camera device is a publicly hidden secure camera device AND some
1569     //    component is trying to access it on a non-hwbinder thread (generally a non HAL client),
1570     //    reject it.
1571     // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
1572     //    and the serving thread is a non hwbinder thread, the client must have
1573     //    android.permission.SYSTEM_CAMERA permissions to connect.
1574 
1575     int cPid = CameraThreadState::getCallingPid();
1576     int cUid = CameraThreadState::getCallingUid();
1577     SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
1578     if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
1579         // This isn't a known camera ID, so it's not a system camera
1580         ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
1581         return false;
1582     }
1583 
1584     // (1) Cameraserver trying to connect, accept.
1585     if (CameraThreadState::getCallingPid() == getpid()) {
1586         return false;
1587     }
1588     // (2)
1589     if (getCurrentServingCall() != BinderCallType::HWBINDER &&
1590             systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
1591         ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
1592         return true;
1593     }
1594     // (3) Here we only check for permissions if it is a system only camera device. This is since
1595     //     getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
1596     //     characteristics) even if clients don't have android.permission.CAMERA. We do not want the
1597     //     same behavior for system camera devices.
1598     if (getCurrentServingCall() != BinderCallType::HWBINDER &&
1599             systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1600             !hasPermissionsForSystemCamera(cPid, cUid)) {
1601         ALOGW("Rejecting access to system only camera %s, inadequete permissions",
1602                 cameraId.c_str());
1603         return true;
1604     }
1605 
1606     return false;
1607 }
1608 
connectDevice(const sp<hardware::camera2::ICameraDeviceCallbacks> & cameraCb,const String16 & cameraId,const String16 & clientPackageName,const std::optional<String16> & clientFeatureId,int clientUid,int oomScoreOffset,int targetSdkVersion,sp<hardware::camera2::ICameraDeviceUser> * device)1609 Status CameraService::connectDevice(
1610         const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
1611         const String16& cameraId,
1612         const String16& clientPackageName,
1613         const std::optional<String16>& clientFeatureId,
1614         int clientUid, int oomScoreOffset, int targetSdkVersion,
1615         /*out*/
1616         sp<hardware::camera2::ICameraDeviceUser>* device) {
1617 
1618     ATRACE_CALL();
1619     Status ret = Status::ok();
1620     String8 id = String8(cameraId);
1621     sp<CameraDeviceClient> client = nullptr;
1622     String16 clientPackageNameAdj = clientPackageName;
1623     int callingPid = CameraThreadState::getCallingPid();
1624 
1625     if (getCurrentServingCall() == BinderCallType::HWBINDER) {
1626         std::string vendorClient =
1627                 StringPrintf("vendor.client.pid<%d>", CameraThreadState::getCallingPid());
1628         clientPackageNameAdj = String16(vendorClient.c_str());
1629     }
1630 
1631     if (oomScoreOffset < 0) {
1632         String8 msg =
1633                 String8::format("Cannot increase the priority of a client %s pid %d for "
1634                         "camera id %s", String8(clientPackageNameAdj).string(), callingPid,
1635                         id.string());
1636         ALOGE("%s: %s", __FUNCTION__, msg.string());
1637         return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
1638     }
1639 
1640     // enforce system camera permissions
1641     if (oomScoreOffset > 0 &&
1642             !hasPermissionsForSystemCamera(callingPid, CameraThreadState::getCallingUid())) {
1643         String8 msg =
1644                 String8::format("Cannot change the priority of a client %s pid %d for "
1645                         "camera id %s without SYSTEM_CAMERA permissions",
1646                         String8(clientPackageNameAdj).string(), callingPid, id.string());
1647         ALOGE("%s: %s", __FUNCTION__, msg.string());
1648         return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.string());
1649     }
1650 
1651     ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
1652             /*api1CameraId*/-1, clientPackageNameAdj, clientFeatureId,
1653             clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, oomScoreOffset,
1654             targetSdkVersion, /*out*/client);
1655 
1656     if(!ret.isOk()) {
1657         logRejected(id, callingPid, String8(clientPackageNameAdj), ret.toString8());
1658         return ret;
1659     }
1660 
1661     *device = client;
1662     Mutex::Autolock lock(mServiceLock);
1663 
1664     // Clear the previous cached logs and reposition the
1665     // file offset to beginning of the file to log new data.
1666     // If either truncate or lseek fails, close the previous file and create a new one.
1667     if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
1668         ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
1669         // Close the previous memfd.
1670         close(mMemFd);
1671         // If failure to wipe the data, then create a new file and
1672         // assign the new value to mMemFd.
1673         mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
1674         if (mMemFd == -1) {
1675             ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
1676         }
1677     }
1678     return ret;
1679 }
1680 
1681 template<class CALLBACK, class CLIENT>
connectHelper(const sp<CALLBACK> & cameraCb,const String8 & cameraId,int api1CameraId,const String16 & clientPackageName,const std::optional<String16> & clientFeatureId,int clientUid,int clientPid,apiLevel effectiveApiLevel,bool shimUpdateOnly,int oomScoreOffset,int targetSdkVersion,sp<CLIENT> & device)1682 Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
1683         int api1CameraId, const String16& clientPackageName,
1684         const std::optional<String16>& clientFeatureId, int clientUid, int clientPid,
1685         apiLevel effectiveApiLevel, bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
1686         /*out*/sp<CLIENT>& device) {
1687     binder::Status ret = binder::Status::ok();
1688 
1689     String8 clientName8(clientPackageName);
1690 
1691     int originalClientPid = 0;
1692 
1693     ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
1694             "Camera API version %d", clientPid, clientName8.string(), cameraId.string(),
1695             static_cast<int>(effectiveApiLevel));
1696 
1697     nsecs_t openTimeNs = systemTime();
1698 
1699     sp<CLIENT> client = nullptr;
1700     int facing = -1;
1701     int orientation = 0;
1702     bool isNdk = (clientPackageName.size() == 0);
1703     {
1704         // Acquire mServiceLock and prevent other clients from connecting
1705         std::unique_ptr<AutoConditionLock> lock =
1706                 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1707 
1708         if (lock == nullptr) {
1709             ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
1710                     , clientPid);
1711             return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1712                     "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
1713                     cameraId.string(), clientName8.string(), clientPid);
1714         }
1715 
1716         // Enforce client permissions and do basic validity checks
1717         if(!(ret = validateConnectLocked(cameraId, clientName8,
1718                 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
1719             return ret;
1720         }
1721 
1722         // Check the shim parameters after acquiring lock, if they have already been updated and
1723         // we were doing a shim update, return immediately
1724         if (shimUpdateOnly) {
1725             auto cameraState = getCameraState(cameraId);
1726             if (cameraState != nullptr) {
1727                 if (!cameraState->getShimParams().isEmpty()) return ret;
1728             }
1729         }
1730 
1731         status_t err;
1732 
1733         sp<BasicClient> clientTmp = nullptr;
1734         std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
1735         if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
1736                 IInterface::asBinder(cameraCb), clientName8, oomScoreOffset, /*out*/&clientTmp,
1737                 /*out*/&partial)) != NO_ERROR) {
1738             switch (err) {
1739                 case -ENODEV:
1740                     return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1741                             "No camera device with ID \"%s\" currently available",
1742                             cameraId.string());
1743                 case -EBUSY:
1744                     return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1745                             "Higher-priority client using camera, ID \"%s\" currently unavailable",
1746                             cameraId.string());
1747                 case -EUSERS:
1748                     return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1749                             "Too many cameras already open, cannot open camera \"%s\"",
1750                             cameraId.string());
1751                 default:
1752                     return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1753                             "Unexpected error %s (%d) opening camera \"%s\"",
1754                             strerror(-err), err, cameraId.string());
1755             }
1756         }
1757 
1758         if (clientTmp.get() != nullptr) {
1759             // Handle special case for API1 MediaRecorder where the existing client is returned
1760             device = static_cast<CLIENT*>(clientTmp.get());
1761             return ret;
1762         }
1763 
1764         // give flashlight a chance to close devices if necessary.
1765         mFlashlight->prepareDeviceOpen(cameraId);
1766 
1767         int deviceVersion = getDeviceVersion(cameraId, /*out*/&facing, /*out*/&orientation);
1768         if (facing == -1) {
1769             ALOGE("%s: Unable to get camera device \"%s\"  facing", __FUNCTION__, cameraId.string());
1770             return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1771                     "Unable to get camera device \"%s\" facing", cameraId.string());
1772         }
1773 
1774         sp<BasicClient> tmp = nullptr;
1775         bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
1776                 mPerfClassPrimaryCameraIds, cameraId.string(), targetSdkVersion);
1777         if(!(ret = makeClient(this, cameraCb, clientPackageName, clientFeatureId,
1778                 cameraId, api1CameraId, facing, orientation,
1779                 clientPid, clientUid, getpid(),
1780                 deviceVersion, effectiveApiLevel, overrideForPerfClass,
1781                 /*out*/&tmp)).isOk()) {
1782             return ret;
1783         }
1784         client = static_cast<CLIENT*>(tmp.get());
1785 
1786         LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
1787                 __FUNCTION__);
1788 
1789         err = client->initialize(mCameraProviderManager, mMonitorTags);
1790         if (err != OK) {
1791             ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
1792             // Errors could be from the HAL module open call or from AppOpsManager
1793             switch(err) {
1794                 case BAD_VALUE:
1795                     return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1796                             "Illegal argument to HAL module for camera \"%s\"", cameraId.string());
1797                 case -EBUSY:
1798                     return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1799                             "Camera \"%s\" is already open", cameraId.string());
1800                 case -EUSERS:
1801                     return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1802                             "Too many cameras already open, cannot open camera \"%s\"",
1803                             cameraId.string());
1804                 case PERMISSION_DENIED:
1805                     return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1806                             "No permission to open camera \"%s\"", cameraId.string());
1807                 case -EACCES:
1808                     return STATUS_ERROR_FMT(ERROR_DISABLED,
1809                             "Camera \"%s\" disabled by policy", cameraId.string());
1810                 case -ENODEV:
1811                 default:
1812                     return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1813                             "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
1814                             strerror(-err), err);
1815             }
1816         }
1817 
1818         // Update shim paremeters for legacy clients
1819         if (effectiveApiLevel == API_1) {
1820             // Assume we have always received a Client subclass for API1
1821             sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
1822             String8 rawParams = shimClient->getParameters();
1823             CameraParameters params(rawParams);
1824 
1825             auto cameraState = getCameraState(cameraId);
1826             if (cameraState != nullptr) {
1827                 cameraState->setShimParams(params);
1828             } else {
1829                 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
1830                         __FUNCTION__, cameraId.string());
1831             }
1832         }
1833 
1834         // Set rotate-and-crop override behavior
1835         if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
1836             client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
1837         } else if (CameraServiceProxyWrapper::isRotateAndCropOverrideNeeded(clientPackageName,
1838                     orientation, facing)) {
1839             client->setRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_90);
1840         }
1841 
1842         // Set camera muting behavior
1843         bool isCameraPrivacyEnabled =
1844                 mSensorPrivacyPolicy->isCameraPrivacyEnabled(multiuser_get_user_id(clientUid));
1845         if (client->supportsCameraMute()) {
1846             client->setCameraMute(
1847                     mOverrideCameraMuteMode || isCameraPrivacyEnabled);
1848         } else if (isCameraPrivacyEnabled) {
1849             // no camera mute supported, but privacy is on! => disconnect
1850             ALOGI("Camera mute not supported for package: %s, camera id: %s",
1851                     String8(client->getPackageName()).string(), cameraId.string());
1852             // Do not hold mServiceLock while disconnecting clients, but
1853             // retain the condition blocking other clients from connecting
1854             // in mServiceLockWrapper if held.
1855             mServiceLock.unlock();
1856             // Clear caller identity temporarily so client disconnect PID
1857             // checks work correctly
1858             int64_t token = CameraThreadState::clearCallingIdentity();
1859             // Note AppOp to trigger the "Unblock" dialog
1860             client->noteAppOp();
1861             client->disconnect();
1862             CameraThreadState::restoreCallingIdentity(token);
1863             // Reacquire mServiceLock
1864             mServiceLock.lock();
1865 
1866             return STATUS_ERROR_FMT(ERROR_DISABLED,
1867                     "Camera \"%s\" disabled due to camera mute", cameraId.string());
1868         }
1869 
1870         if (shimUpdateOnly) {
1871             // If only updating legacy shim parameters, immediately disconnect client
1872             mServiceLock.unlock();
1873             client->disconnect();
1874             mServiceLock.lock();
1875         } else {
1876             // Otherwise, add client to active clients list
1877             finishConnectLocked(client, partial, oomScoreOffset);
1878         }
1879 
1880         client->setImageDumpMask(mImageDumpMask);
1881     } // lock is destroyed, allow further connect calls
1882 
1883     // Important: release the mutex here so the client can call back into the service from its
1884     // destructor (can be at the end of the call)
1885     device = client;
1886 
1887     int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
1888     CameraServiceProxyWrapper::logOpen(cameraId, facing, clientPackageName,
1889             effectiveApiLevel, isNdk, openLatencyMs);
1890 
1891     return ret;
1892 }
1893 
addOfflineClient(String8 cameraId,sp<BasicClient> offlineClient)1894 status_t CameraService::addOfflineClient(String8 cameraId, sp<BasicClient> offlineClient) {
1895     if (offlineClient.get() == nullptr) {
1896         return BAD_VALUE;
1897     }
1898 
1899     {
1900         // Acquire mServiceLock and prevent other clients from connecting
1901         std::unique_ptr<AutoConditionLock> lock =
1902                 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1903 
1904         if (lock == nullptr) {
1905             ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
1906                     , __FUNCTION__, offlineClient->getClientPid());
1907             return TIMED_OUT;
1908         }
1909 
1910         auto onlineClientDesc = mActiveClientManager.get(cameraId);
1911         if (onlineClientDesc.get() == nullptr) {
1912             ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
1913                     cameraId.c_str());
1914             return BAD_VALUE;
1915         }
1916 
1917         // Offline clients do not evict or conflict with other online devices. Resource sharing
1918         // conflicts are handled by the camera provider which will either succeed or fail before
1919         // reaching this method.
1920         const auto& onlinePriority = onlineClientDesc->getPriority();
1921         auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
1922                 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
1923                 /*conflictingKeys*/ std::set<String8>(), onlinePriority.getScore(),
1924                 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
1925                 /*ommScoreOffset*/ 0);
1926 
1927         // Allow only one offline device per camera
1928         auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
1929         if (!incompatibleClients.empty()) {
1930             ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
1931             return BAD_VALUE;
1932         }
1933 
1934         auto err = offlineClient->initialize(mCameraProviderManager, mMonitorTags);
1935         if (err != OK) {
1936             ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
1937             return err;
1938         }
1939 
1940         auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
1941         if (evicted.size() > 0) {
1942             for (auto& i : evicted) {
1943                 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
1944                         __FUNCTION__, i->getKey().string());
1945             }
1946 
1947             LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
1948                     "properly", __FUNCTION__);
1949 
1950             return BAD_VALUE;
1951         }
1952 
1953         logConnectedOffline(offlineClientDesc->getKey(),
1954                 static_cast<int>(offlineClientDesc->getOwnerId()),
1955                 String8(offlineClient->getPackageName()));
1956 
1957         sp<IBinder> remoteCallback = offlineClient->getRemote();
1958         if (remoteCallback != nullptr) {
1959             remoteCallback->linkToDeath(this);
1960         }
1961     } // lock is destroyed, allow further connect calls
1962 
1963     return OK;
1964 }
1965 
setTorchMode(const String16 & cameraId,bool enabled,const sp<IBinder> & clientBinder)1966 Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
1967         const sp<IBinder>& clientBinder) {
1968     Mutex::Autolock lock(mServiceLock);
1969 
1970     ATRACE_CALL();
1971     if (enabled && clientBinder == nullptr) {
1972         ALOGE("%s: torch client binder is NULL", __FUNCTION__);
1973         return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1974                 "Torch client Binder is null");
1975     }
1976 
1977     String8 id = String8(cameraId.string());
1978     int uid = CameraThreadState::getCallingUid();
1979 
1980     if (shouldRejectSystemCameraConnection(id)) {
1981         return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
1982                 " for system only device %s: ", id.string());
1983     }
1984     // verify id is valid.
1985     auto state = getCameraState(id);
1986     if (state == nullptr) {
1987         ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
1988         return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1989                 "Camera ID \"%s\" is a not valid camera ID", id.string());
1990     }
1991 
1992     StatusInternal cameraStatus = state->getStatus();
1993     if (cameraStatus != StatusInternal::PRESENT &&
1994             cameraStatus != StatusInternal::NOT_AVAILABLE) {
1995         ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus);
1996         return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1997                 "Camera ID \"%s\" is a not valid camera ID", id.string());
1998     }
1999 
2000     {
2001         Mutex::Autolock al(mTorchStatusMutex);
2002         TorchModeStatus status;
2003         status_t err = getTorchStatusLocked(id, &status);
2004         if (err != OK) {
2005             if (err == NAME_NOT_FOUND) {
2006                 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2007                         "Camera \"%s\" does not have a flash unit", id.string());
2008             }
2009             ALOGE("%s: getting current torch status failed for camera %s",
2010                     __FUNCTION__, id.string());
2011             return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2012                     "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
2013                     strerror(-err), err);
2014         }
2015 
2016         if (status == TorchModeStatus::NOT_AVAILABLE) {
2017             if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
2018                 ALOGE("%s: torch mode of camera %s is not available because "
2019                         "camera is in use", __FUNCTION__, id.string());
2020                 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2021                         "Torch for camera \"%s\" is not available due to an existing camera user",
2022                         id.string());
2023             } else {
2024                 ALOGE("%s: torch mode of camera %s is not available due to "
2025                         "insufficient resources", __FUNCTION__, id.string());
2026                 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2027                         "Torch for camera \"%s\" is not available due to insufficient resources",
2028                         id.string());
2029             }
2030         }
2031     }
2032 
2033     {
2034         // Update UID map - this is used in the torch status changed callbacks, so must be done
2035         // before setTorchMode
2036         Mutex::Autolock al(mTorchUidMapMutex);
2037         if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
2038             mTorchUidMap[id].first = uid;
2039             mTorchUidMap[id].second = uid;
2040         } else {
2041             // Set the pending UID
2042             mTorchUidMap[id].first = uid;
2043         }
2044     }
2045 
2046     status_t err = mFlashlight->setTorchMode(id, enabled);
2047 
2048     if (err != OK) {
2049         int32_t errorCode;
2050         String8 msg;
2051         switch (err) {
2052             case -ENOSYS:
2053                 msg = String8::format("Camera \"%s\" has no flashlight",
2054                     id.string());
2055                 errorCode = ERROR_ILLEGAL_ARGUMENT;
2056                 break;
2057             default:
2058                 msg = String8::format(
2059                     "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
2060                     id.string(), enabled, strerror(-err), err);
2061                 errorCode = ERROR_INVALID_OPERATION;
2062         }
2063         ALOGE("%s: %s", __FUNCTION__, msg.string());
2064         logServiceError(msg,errorCode);
2065         return STATUS_ERROR(errorCode, msg.string());
2066     }
2067 
2068     {
2069         // update the link to client's death
2070         Mutex::Autolock al(mTorchClientMapMutex);
2071         ssize_t index = mTorchClientMap.indexOfKey(id);
2072         if (enabled) {
2073             if (index == NAME_NOT_FOUND) {
2074                 mTorchClientMap.add(id, clientBinder);
2075             } else {
2076                 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
2077                 mTorchClientMap.replaceValueAt(index, clientBinder);
2078             }
2079             clientBinder->linkToDeath(this);
2080         } else if (index != NAME_NOT_FOUND) {
2081             mTorchClientMap.valueAt(index)->unlinkToDeath(this);
2082         }
2083     }
2084 
2085     int clientPid = CameraThreadState::getCallingPid();
2086     const char *id_cstr = id.c_str();
2087     const char *torchState = enabled ? "on" : "off";
2088     ALOGI("Torch for camera id %s turned %s for client PID %d", id_cstr, torchState, clientPid);
2089     logTorchEvent(id_cstr, torchState , clientPid);
2090     return Status::ok();
2091 }
2092 
notifySystemEvent(int32_t eventId,const std::vector<int32_t> & args)2093 Status CameraService::notifySystemEvent(int32_t eventId,
2094         const std::vector<int32_t>& args) {
2095     const int pid = CameraThreadState::getCallingPid();
2096     const int selfPid = getpid();
2097 
2098     // Permission checks
2099     if (pid != selfPid) {
2100         // Ensure we're being called by system_server, or similar process with
2101         // permissions to notify the camera service about system events
2102         if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
2103             const int uid = CameraThreadState::getCallingUid();
2104             ALOGE("Permission Denial: cannot send updates to camera service about system"
2105                     " events from pid=%d, uid=%d", pid, uid);
2106             return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2107                     "No permission to send updates to camera service about system events"
2108                     " from pid=%d, uid=%d", pid, uid);
2109         }
2110     }
2111 
2112     ATRACE_CALL();
2113 
2114     switch(eventId) {
2115         case ICameraService::EVENT_USER_SWITCHED: {
2116             // Try to register for UID and sensor privacy policy updates, in case we're recovering
2117             // from a system server crash
2118             mUidPolicy->registerSelf();
2119             mSensorPrivacyPolicy->registerSelf();
2120             doUserSwitch(/*newUserIds*/ args);
2121             break;
2122         }
2123         case ICameraService::EVENT_NONE:
2124         default: {
2125             ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
2126                     eventId);
2127             break;
2128         }
2129     }
2130     return Status::ok();
2131 }
2132 
notifyMonitoredUids()2133 void CameraService::notifyMonitoredUids() {
2134     Mutex::Autolock lock(mStatusListenerLock);
2135 
2136     for (const auto& it : mListenerList) {
2137         auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
2138         if (!ret.isOk()) {
2139             ALOGE("%s: Failed to trigger permission callback: %d", __FUNCTION__,
2140                     ret.exceptionCode());
2141         }
2142     }
2143 }
2144 
notifyDeviceStateChange(int64_t newState)2145 Status CameraService::notifyDeviceStateChange(int64_t newState) {
2146     const int pid = CameraThreadState::getCallingPid();
2147     const int selfPid = getpid();
2148 
2149     // Permission checks
2150     if (pid != selfPid) {
2151         // Ensure we're being called by system_server, or similar process with
2152         // permissions to notify the camera service about system events
2153         if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
2154             const int uid = CameraThreadState::getCallingUid();
2155             ALOGE("Permission Denial: cannot send updates to camera service about device"
2156                     " state changes from pid=%d, uid=%d", pid, uid);
2157             return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2158                     "No permission to send updates to camera service about device state"
2159                     " changes from pid=%d, uid=%d", pid, uid);
2160         }
2161     }
2162 
2163     ATRACE_CALL();
2164 
2165     using hardware::camera::provider::V2_5::DeviceState;
2166     hardware::hidl_bitfield<DeviceState> newDeviceState{};
2167     if (newState & ICameraService::DEVICE_STATE_BACK_COVERED) {
2168         newDeviceState |= DeviceState::BACK_COVERED;
2169     }
2170     if (newState & ICameraService::DEVICE_STATE_FRONT_COVERED) {
2171         newDeviceState |= DeviceState::FRONT_COVERED;
2172     }
2173     if (newState & ICameraService::DEVICE_STATE_FOLDED) {
2174         newDeviceState |= DeviceState::FOLDED;
2175     }
2176     // Only map vendor bits directly
2177     uint64_t vendorBits = static_cast<uint64_t>(newState) & 0xFFFFFFFF00000000l;
2178     newDeviceState |= vendorBits;
2179 
2180     ALOGV("%s: New device state 0x%" PRIx64, __FUNCTION__, newDeviceState);
2181     Mutex::Autolock l(mServiceLock);
2182     mCameraProviderManager->notifyDeviceStateChange(newDeviceState);
2183 
2184     return Status::ok();
2185 }
2186 
notifyDisplayConfigurationChange()2187 Status CameraService::notifyDisplayConfigurationChange() {
2188     ATRACE_CALL();
2189     const int callingPid = CameraThreadState::getCallingPid();
2190     const int selfPid = getpid();
2191 
2192     // Permission checks
2193     if (callingPid != selfPid) {
2194         // Ensure we're being called by system_server, or similar process with
2195         // permissions to notify the camera service about system events
2196         if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
2197             const int uid = CameraThreadState::getCallingUid();
2198             ALOGE("Permission Denial: cannot send updates to camera service about orientation"
2199                     " changes from pid=%d, uid=%d", callingPid, uid);
2200             return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2201                     "No permission to send updates to camera service about orientation"
2202                     " changes from pid=%d, uid=%d", callingPid, uid);
2203         }
2204     }
2205 
2206     Mutex::Autolock lock(mServiceLock);
2207 
2208     // Don't do anything if rotate-and-crop override via cmd is active
2209     if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
2210 
2211     const auto clients = mActiveClientManager.getAll();
2212     for (auto& current : clients) {
2213         if (current != nullptr) {
2214             const auto basicClient = current->getValue();
2215             if (basicClient.get() != nullptr) {
2216                 if (CameraServiceProxyWrapper::isRotateAndCropOverrideNeeded(
2217                             basicClient->getPackageName(), basicClient->getCameraOrientation(),
2218                             basicClient->getCameraFacing())) {
2219                     basicClient->setRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_90);
2220                 } else {
2221                     basicClient->setRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE);
2222                 }
2223             }
2224         }
2225     }
2226 
2227     return Status::ok();
2228 }
2229 
getConcurrentCameraIds(std::vector<ConcurrentCameraIdCombination> * concurrentCameraIds)2230 Status CameraService::getConcurrentCameraIds(
2231         std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
2232     ATRACE_CALL();
2233     if (!concurrentCameraIds) {
2234         ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
2235         return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
2236     }
2237 
2238     if (!mInitialized) {
2239         ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2240         logServiceError(String8::format("Camera subsystem is not available"),ERROR_DISCONNECTED);
2241         return STATUS_ERROR(ERROR_DISCONNECTED,
2242                 "Camera subsystem is not available");
2243     }
2244     // First call into the provider and get the set of concurrent camera
2245     // combinations
2246     std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
2247             mCameraProviderManager->getConcurrentCameraIds();
2248     for (auto &combination : concurrentCameraCombinations) {
2249         std::vector<std::string> validCombination;
2250         for (auto &cameraId : combination) {
2251             // if the camera state is not present, skip
2252             String8 cameraIdStr(cameraId.c_str());
2253             auto state = getCameraState(cameraIdStr);
2254             if (state == nullptr) {
2255                 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
2256                 continue;
2257             }
2258             StatusInternal status = state->getStatus();
2259             if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
2260                 continue;
2261             }
2262             if (shouldRejectSystemCameraConnection(cameraIdStr)) {
2263                 continue;
2264             }
2265             validCombination.push_back(cameraId);
2266         }
2267         if (validCombination.size() != 0) {
2268             concurrentCameraIds->push_back(std::move(validCombination));
2269         }
2270     }
2271     return Status::ok();
2272 }
2273 
isConcurrentSessionConfigurationSupported(const std::vector<CameraIdAndSessionConfiguration> & cameraIdsAndSessionConfigurations,int targetSdkVersion,bool * isSupported)2274 Status CameraService::isConcurrentSessionConfigurationSupported(
2275         const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
2276         int targetSdkVersion, /*out*/bool* isSupported) {
2277     if (!isSupported) {
2278         ALOGE("%s: isSupported is NULL", __FUNCTION__);
2279         return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
2280     }
2281 
2282     if (!mInitialized) {
2283         ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2284         return STATUS_ERROR(ERROR_DISCONNECTED,
2285                 "Camera subsystem is not available");
2286     }
2287 
2288     // Check for camera permissions
2289     int callingPid = CameraThreadState::getCallingPid();
2290     int callingUid = CameraThreadState::getCallingUid();
2291     if ((callingPid != getpid()) && !checkPermission(sCameraPermission, callingPid, callingUid)) {
2292         ALOGE("%s: pid %d doesn't have camera permissions", __FUNCTION__, callingPid);
2293         return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2294                 "android.permission.CAMERA needed to call"
2295                 "isConcurrentSessionConfigurationSupported");
2296     }
2297 
2298     status_t res =
2299             mCameraProviderManager->isConcurrentSessionConfigurationSupported(
2300                     cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
2301                     targetSdkVersion, isSupported);
2302     if (res != OK) {
2303         logServiceError(String8::format("Unable to query session configuration support"),
2304             ERROR_INVALID_OPERATION);
2305         return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
2306                 "support %s (%d)", strerror(-res), res);
2307     }
2308     return Status::ok();
2309 }
2310 
addListener(const sp<ICameraServiceListener> & listener,std::vector<hardware::CameraStatus> * cameraStatuses)2311 Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
2312         /*out*/
2313         std::vector<hardware::CameraStatus> *cameraStatuses) {
2314     return addListenerHelper(listener, cameraStatuses);
2315 }
2316 
addListenerTest(const sp<hardware::ICameraServiceListener> & listener,std::vector<hardware::CameraStatus> * cameraStatuses)2317 binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
2318             std::vector<hardware::CameraStatus>* cameraStatuses) {
2319     return addListenerHelper(listener, cameraStatuses, false, true);
2320 }
2321 
addListenerHelper(const sp<ICameraServiceListener> & listener,std::vector<hardware::CameraStatus> * cameraStatuses,bool isVendorListener,bool isProcessLocalTest)2322 Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
2323         /*out*/
2324         std::vector<hardware::CameraStatus> *cameraStatuses,
2325         bool isVendorListener, bool isProcessLocalTest) {
2326 
2327     ATRACE_CALL();
2328 
2329     ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
2330 
2331     if (listener == nullptr) {
2332         ALOGE("%s: Listener must not be null", __FUNCTION__);
2333         return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
2334     }
2335 
2336     auto clientUid = CameraThreadState::getCallingUid();
2337     auto clientPid = CameraThreadState::getCallingPid();
2338     bool openCloseCallbackAllowed = checkPermission(sCameraOpenCloseListenerPermission,
2339             clientPid, clientUid);
2340 
2341     Mutex::Autolock lock(mServiceLock);
2342 
2343     {
2344         Mutex::Autolock lock(mStatusListenerLock);
2345         for (const auto &it : mListenerList) {
2346             if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
2347                 ALOGW("%s: Tried to add listener %p which was already subscribed",
2348                       __FUNCTION__, listener.get());
2349                 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
2350             }
2351         }
2352 
2353         sp<ServiceListener> serviceListener =
2354                 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
2355                         openCloseCallbackAllowed);
2356         auto ret = serviceListener->initialize(isProcessLocalTest);
2357         if (ret != NO_ERROR) {
2358             String8 msg = String8::format("Failed to initialize service listener: %s (%d)",
2359                     strerror(-ret), ret);
2360             logServiceError(msg,ERROR_ILLEGAL_ARGUMENT);
2361             ALOGE("%s: %s", __FUNCTION__, msg.string());
2362             return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
2363         }
2364         // The listener still needs to be added to the list of listeners, regardless of what
2365         // permissions the listener process has / whether it is a vendor listener. Since it might be
2366         // eligible to listen to other camera ids.
2367         mListenerList.emplace_back(serviceListener);
2368         mUidPolicy->registerMonitorUid(clientUid);
2369     }
2370 
2371     /* Collect current devices and status */
2372     {
2373         Mutex::Autolock lock(mCameraStatesLock);
2374         for (auto& i : mCameraStates) {
2375             cameraStatuses->emplace_back(i.first,
2376                     mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds());
2377         }
2378     }
2379     // Remove the camera statuses that should be hidden from the client, we do
2380     // this after collecting the states in order to avoid holding
2381     // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
2382     // the same time.
2383     cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
2384                 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
2385                     SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
2386                     if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
2387                         ALOGE("%s: Invalid camera id %s, skipping status update",
2388                                 __FUNCTION__, s.cameraId.c_str());
2389                         return true;
2390                     }
2391                     return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
2392                             clientUid);}), cameraStatuses->end());
2393 
2394     //cameraStatuses will have non-eligible camera ids removed.
2395     std::set<String16> idsChosenForCallback;
2396     for (const auto &s : *cameraStatuses) {
2397         idsChosenForCallback.insert(String16(s.cameraId));
2398     }
2399 
2400     /*
2401      * Immediately signal current torch status to this listener only
2402      * This may be a subset of all the devices, so don't include it in the response directly
2403      */
2404     {
2405         Mutex::Autolock al(mTorchStatusMutex);
2406         for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
2407             String16 id = String16(mTorchStatusMap.keyAt(i).string());
2408             // The camera id is visible to the client. Fine to send torch
2409             // callback.
2410             if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
2411                 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
2412             }
2413         }
2414     }
2415 
2416     return Status::ok();
2417 }
2418 
removeListener(const sp<ICameraServiceListener> & listener)2419 Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
2420     ATRACE_CALL();
2421 
2422     ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
2423 
2424     if (listener == 0) {
2425         ALOGE("%s: Listener must not be null", __FUNCTION__);
2426         return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
2427     }
2428 
2429     Mutex::Autolock lock(mServiceLock);
2430 
2431     {
2432         Mutex::Autolock lock(mStatusListenerLock);
2433         for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
2434             if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
2435                 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid());
2436                 IInterface::asBinder(listener)->unlinkToDeath(*it);
2437                 mListenerList.erase(it);
2438                 return Status::ok();
2439             }
2440         }
2441     }
2442 
2443     ALOGW("%s: Tried to remove a listener %p which was not subscribed",
2444           __FUNCTION__, listener.get());
2445 
2446     return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
2447 }
2448 
getLegacyParameters(int cameraId,String16 * parameters)2449 Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
2450 
2451     ATRACE_CALL();
2452     ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
2453 
2454     if (parameters == NULL) {
2455         ALOGE("%s: parameters must not be null", __FUNCTION__);
2456         return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
2457     }
2458 
2459     Status ret = Status::ok();
2460 
2461     CameraParameters shimParams;
2462     if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
2463         // Error logged by caller
2464         return ret;
2465     }
2466 
2467     String8 shimParamsString8 = shimParams.flatten();
2468     String16 shimParamsString16 = String16(shimParamsString8);
2469 
2470     *parameters = shimParamsString16;
2471 
2472     return ret;
2473 }
2474 
supportsCameraApi(const String16 & cameraId,int apiVersion,bool * isSupported)2475 Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
2476         /*out*/ bool *isSupported) {
2477     ATRACE_CALL();
2478 
2479     const String8 id = String8(cameraId);
2480 
2481     ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
2482 
2483     switch (apiVersion) {
2484         case API_VERSION_1:
2485         case API_VERSION_2:
2486             break;
2487         default:
2488             String8 msg = String8::format("Unknown API version %d", apiVersion);
2489             ALOGE("%s: %s", __FUNCTION__, msg.string());
2490             return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
2491     }
2492 
2493     int deviceVersion = getDeviceVersion(id);
2494     switch (deviceVersion) {
2495         case CAMERA_DEVICE_API_VERSION_1_0:
2496         case CAMERA_DEVICE_API_VERSION_3_0:
2497         case CAMERA_DEVICE_API_VERSION_3_1:
2498             if (apiVersion == API_VERSION_2) {
2499                 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without shim",
2500                         __FUNCTION__, id.string(), deviceVersion);
2501                 *isSupported = false;
2502             } else { // if (apiVersion == API_VERSION_1) {
2503                 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always supported",
2504                         __FUNCTION__, id.string());
2505                 *isSupported = true;
2506             }
2507             break;
2508         case CAMERA_DEVICE_API_VERSION_3_2:
2509         case CAMERA_DEVICE_API_VERSION_3_3:
2510         case CAMERA_DEVICE_API_VERSION_3_4:
2511         case CAMERA_DEVICE_API_VERSION_3_5:
2512         case CAMERA_DEVICE_API_VERSION_3_6:
2513         case CAMERA_DEVICE_API_VERSION_3_7:
2514             ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
2515                     __FUNCTION__, id.string());
2516             *isSupported = true;
2517             break;
2518         case -1: {
2519             String8 msg = String8::format("Unknown camera ID %s", id.string());
2520             ALOGE("%s: %s", __FUNCTION__, msg.string());
2521             return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
2522         }
2523         default: {
2524             String8 msg = String8::format("Unknown device version %x for device %s",
2525                     deviceVersion, id.string());
2526             ALOGE("%s: %s", __FUNCTION__, msg.string());
2527             return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
2528         }
2529     }
2530 
2531     return Status::ok();
2532 }
2533 
isHiddenPhysicalCamera(const String16 & cameraId,bool * isSupported)2534 Status CameraService::isHiddenPhysicalCamera(const String16& cameraId,
2535         /*out*/ bool *isSupported) {
2536     ATRACE_CALL();
2537 
2538     const String8 id = String8(cameraId);
2539 
2540     ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
2541     *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(id.string());
2542 
2543     return Status::ok();
2544 }
2545 
injectCamera(const String16 & packageName,const String16 & internalCamId,const String16 & externalCamId,const sp<ICameraInjectionCallback> & callback,sp<hardware::camera2::ICameraInjectionSession> * cameraInjectionSession)2546 Status CameraService::injectCamera(
2547         const String16& packageName, const String16& internalCamId,
2548         const String16& externalCamId,
2549         const sp<ICameraInjectionCallback>& callback,
2550         /*out*/
2551         sp<hardware::camera2::ICameraInjectionSession>* cameraInjectionSession) {
2552     ATRACE_CALL();
2553 
2554     if (!checkCallingPermission(sCameraInjectExternalCameraPermission)) {
2555         const int pid = CameraThreadState::getCallingPid();
2556         const int uid = CameraThreadState::getCallingUid();
2557         ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
2558         return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2559                         "Permission Denial: no permission to inject camera");
2560     }
2561 
2562     ALOGV(
2563         "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
2564         "%s",
2565         __FUNCTION__, String8(packageName).string(),
2566         String8(internalCamId).string(), String8(externalCamId).string());
2567 
2568     binder::Status ret = binder::Status::ok();
2569     // TODO: Implement the injection camera function.
2570     // ret = internalInjectCamera(...);
2571     // if(!ret.isOk()) {
2572     //     mInjectionStatusListener->notifyInjectionError(...);
2573     //     return ret;
2574     // }
2575 
2576     mInjectionStatusListener->addListener(callback);
2577     *cameraInjectionSession = new CameraInjectionSession(this);
2578 
2579     return ret;
2580 }
2581 
removeByClient(const BasicClient * client)2582 void CameraService::removeByClient(const BasicClient* client) {
2583     Mutex::Autolock lock(mServiceLock);
2584     for (auto& i : mActiveClientManager.getAll()) {
2585         auto clientSp = i->getValue();
2586         if (clientSp.get() == client) {
2587             mActiveClientManager.remove(i);
2588         }
2589     }
2590     updateAudioRestrictionLocked();
2591 }
2592 
evictClientIdByRemote(const wp<IBinder> & remote)2593 bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
2594     bool ret = false;
2595     {
2596         // Acquire mServiceLock and prevent other clients from connecting
2597         std::unique_ptr<AutoConditionLock> lock =
2598                 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
2599 
2600 
2601         std::vector<sp<BasicClient>> evicted;
2602         for (auto& i : mActiveClientManager.getAll()) {
2603             auto clientSp = i->getValue();
2604             if (clientSp.get() == nullptr) {
2605                 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2606                 mActiveClientManager.remove(i);
2607                 continue;
2608             }
2609             if (remote == clientSp->getRemote()) {
2610                 mActiveClientManager.remove(i);
2611                 evicted.push_back(clientSp);
2612 
2613                 // Notify the client of disconnection
2614                 clientSp->notifyError(
2615                         hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
2616                         CaptureResultExtras());
2617             }
2618         }
2619 
2620         // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2621         // other clients from connecting in mServiceLockWrapper if held
2622         mServiceLock.unlock();
2623 
2624         // Do not clear caller identity, remote caller should be client proccess
2625 
2626         for (auto& i : evicted) {
2627             if (i.get() != nullptr) {
2628                 i->disconnect();
2629                 ret = true;
2630             }
2631         }
2632 
2633         // Reacquire mServiceLock
2634         mServiceLock.lock();
2635 
2636     } // lock is destroyed, allow further connect calls
2637 
2638     return ret;
2639 }
2640 
getCameraState(const String8 & cameraId) const2641 std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
2642         const String8& cameraId) const {
2643     std::shared_ptr<CameraState> state;
2644     {
2645         Mutex::Autolock lock(mCameraStatesLock);
2646         auto iter = mCameraStates.find(cameraId);
2647         if (iter != mCameraStates.end()) {
2648             state = iter->second;
2649         }
2650     }
2651     return state;
2652 }
2653 
removeClientLocked(const String8 & cameraId)2654 sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
2655     // Remove from active clients list
2656     auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
2657     if (clientDescriptorPtr == nullptr) {
2658         ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
2659                 cameraId.string());
2660         return sp<BasicClient>{nullptr};
2661     }
2662 
2663     return clientDescriptorPtr->getValue();
2664 }
2665 
doUserSwitch(const std::vector<int32_t> & newUserIds)2666 void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
2667     // Acquire mServiceLock and prevent other clients from connecting
2668     std::unique_ptr<AutoConditionLock> lock =
2669             AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
2670 
2671     std::set<userid_t> newAllowedUsers;
2672     for (size_t i = 0; i < newUserIds.size(); i++) {
2673         if (newUserIds[i] < 0) {
2674             ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
2675                     __FUNCTION__, newUserIds[i]);
2676             return;
2677         }
2678         newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
2679     }
2680 
2681 
2682     if (newAllowedUsers == mAllowedUsers) {
2683         ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
2684         return;
2685     }
2686 
2687     logUserSwitch(mAllowedUsers, newAllowedUsers);
2688 
2689     mAllowedUsers = std::move(newAllowedUsers);
2690 
2691     // Current user has switched, evict all current clients.
2692     std::vector<sp<BasicClient>> evicted;
2693     for (auto& i : mActiveClientManager.getAll()) {
2694         auto clientSp = i->getValue();
2695 
2696         if (clientSp.get() == nullptr) {
2697             ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2698             continue;
2699         }
2700 
2701         // Don't evict clients that are still allowed.
2702         uid_t clientUid = clientSp->getClientUid();
2703         userid_t clientUserId = multiuser_get_user_id(clientUid);
2704         if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
2705             continue;
2706         }
2707 
2708         evicted.push_back(clientSp);
2709 
2710         String8 curTime = getFormattedCurrentTime();
2711 
2712         ALOGE("Evicting conflicting client for camera ID %s due to user change",
2713                 i->getKey().string());
2714 
2715         // Log the clients evicted
2716         logEvent(String8::format("EVICT device %s client held by package %s (PID %"
2717                 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n   - Evicted due"
2718                 " to user switch.", i->getKey().string(),
2719                 String8{clientSp->getPackageName()}.string(),
2720                 i->getOwnerId(), i->getPriority().getScore(),
2721                 i->getPriority().getState()));
2722 
2723     }
2724 
2725     // Do not hold mServiceLock while disconnecting clients, but retain the condition
2726     // blocking other clients from connecting in mServiceLockWrapper if held.
2727     mServiceLock.unlock();
2728 
2729     // Clear caller identity temporarily so client disconnect PID checks work correctly
2730     int64_t token = CameraThreadState::clearCallingIdentity();
2731 
2732     for (auto& i : evicted) {
2733         i->disconnect();
2734     }
2735 
2736     CameraThreadState::restoreCallingIdentity(token);
2737 
2738     // Reacquire mServiceLock
2739     mServiceLock.lock();
2740 }
2741 
logEvent(const char * event)2742 void CameraService::logEvent(const char* event) {
2743     String8 curTime = getFormattedCurrentTime();
2744     Mutex::Autolock l(mLogLock);
2745     String8 msg = String8::format("%s : %s", curTime.string(), event);
2746     // For service error events, print the msg only once.
2747     if(!msg.contains("SERVICE ERROR")) {
2748         mEventLog.add(msg);
2749     } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
2750         // Error event not added to the dumpsys log before
2751         mEventLog.add(msg);
2752         sServiceErrorEventSet.insert(msg);
2753     }
2754 }
2755 
logDisconnected(const char * cameraId,int clientPid,const char * clientPackage)2756 void CameraService::logDisconnected(const char* cameraId, int clientPid,
2757         const char* clientPackage) {
2758     // Log the clients evicted
2759     logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
2760             clientPackage, clientPid));
2761 }
2762 
logDisconnectedOffline(const char * cameraId,int clientPid,const char * clientPackage)2763 void CameraService::logDisconnectedOffline(const char* cameraId, int clientPid,
2764         const char* clientPackage) {
2765     // Log the clients evicted
2766     logEvent(String8::format("DISCONNECT offline device %s client for package %s (PID %d)",
2767                 cameraId, clientPackage, clientPid));
2768 }
2769 
logConnected(const char * cameraId,int clientPid,const char * clientPackage)2770 void CameraService::logConnected(const char* cameraId, int clientPid,
2771         const char* clientPackage) {
2772     // Log the clients evicted
2773     logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
2774             clientPackage, clientPid));
2775 }
2776 
logConnectedOffline(const char * cameraId,int clientPid,const char * clientPackage)2777 void CameraService::logConnectedOffline(const char* cameraId, int clientPid,
2778         const char* clientPackage) {
2779     // Log the clients evicted
2780     logEvent(String8::format("CONNECT offline device %s client for package %s (PID %d)", cameraId,
2781             clientPackage, clientPid));
2782 }
2783 
logRejected(const char * cameraId,int clientPid,const char * clientPackage,const char * reason)2784 void CameraService::logRejected(const char* cameraId, int clientPid,
2785         const char* clientPackage, const char* reason) {
2786     // Log the client rejected
2787     logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
2788             cameraId, clientPackage, clientPid, reason));
2789 }
2790 
logTorchEvent(const char * cameraId,const char * torchState,int clientPid)2791 void CameraService::logTorchEvent(const char* cameraId, const char *torchState, int clientPid) {
2792     // Log torch event
2793     logEvent(String8::format("Torch for camera id %s turned %s for client PID %d", cameraId,
2794             torchState, clientPid));
2795 }
2796 
logUserSwitch(const std::set<userid_t> & oldUserIds,const std::set<userid_t> & newUserIds)2797 void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
2798         const std::set<userid_t>& newUserIds) {
2799     String8 newUsers = toString(newUserIds);
2800     String8 oldUsers = toString(oldUserIds);
2801     if (oldUsers.size() == 0) {
2802         oldUsers = "<None>";
2803     }
2804     // Log the new and old users
2805     logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
2806             oldUsers.string(), newUsers.string()));
2807 }
2808 
logDeviceRemoved(const char * cameraId,const char * reason)2809 void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
2810     // Log the device removal
2811     logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
2812 }
2813 
logDeviceAdded(const char * cameraId,const char * reason)2814 void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
2815     // Log the device removal
2816     logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
2817 }
2818 
logClientDied(int clientPid,const char * reason)2819 void CameraService::logClientDied(int clientPid, const char* reason) {
2820     // Log the device removal
2821     logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
2822 }
2823 
logServiceError(const char * msg,int errorCode)2824 void CameraService::logServiceError(const char* msg, int errorCode) {
2825     String8 curTime = getFormattedCurrentTime();
2826     logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
2827 }
2828 
onTransact(uint32_t code,const Parcel & data,Parcel * reply,uint32_t flags)2829 status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
2830         uint32_t flags) {
2831 
2832     // Permission checks
2833     switch (code) {
2834         case SHELL_COMMAND_TRANSACTION: {
2835             int in = data.readFileDescriptor();
2836             int out = data.readFileDescriptor();
2837             int err = data.readFileDescriptor();
2838             int argc = data.readInt32();
2839             Vector<String16> args;
2840             for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
2841                args.add(data.readString16());
2842             }
2843             sp<IBinder> unusedCallback;
2844             sp<IResultReceiver> resultReceiver;
2845             status_t status;
2846             if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
2847                 return status;
2848             }
2849             if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
2850                 return status;
2851             }
2852             status = shellCommand(in, out, err, args);
2853             if (resultReceiver != nullptr) {
2854                 resultReceiver->send(status);
2855             }
2856             return NO_ERROR;
2857         }
2858     }
2859 
2860     return BnCameraService::onTransact(code, data, reply, flags);
2861 }
2862 
2863 // We share the media players for shutter and recording sound for all clients.
2864 // A reference count is kept to determine when we will actually release the
2865 // media players.
2866 
newMediaPlayer(const char * file)2867 sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
2868     sp<MediaPlayer> mp = new MediaPlayer();
2869     status_t error;
2870     if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
2871         mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
2872         error = mp->prepare();
2873     }
2874     if (error != NO_ERROR) {
2875         ALOGE("Failed to load CameraService sounds: %s", file);
2876         mp->disconnect();
2877         mp.clear();
2878         return nullptr;
2879     }
2880     return mp;
2881 }
2882 
increaseSoundRef()2883 void CameraService::increaseSoundRef() {
2884     Mutex::Autolock lock(mSoundLock);
2885     mSoundRef++;
2886 }
2887 
loadSoundLocked(sound_kind kind)2888 void CameraService::loadSoundLocked(sound_kind kind) {
2889     ATRACE_CALL();
2890 
2891     LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
2892     if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
2893         mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
2894         if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
2895             mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
2896         }
2897     } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] ==  NULL) {
2898         mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
2899         if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
2900             mSoundPlayer[SOUND_RECORDING_START] =
2901                 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
2902         }
2903     } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
2904         mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
2905         if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
2906             mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
2907         }
2908     }
2909 }
2910 
decreaseSoundRef()2911 void CameraService::decreaseSoundRef() {
2912     Mutex::Autolock lock(mSoundLock);
2913     LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
2914     if (--mSoundRef) return;
2915 
2916     for (int i = 0; i < NUM_SOUNDS; i++) {
2917         if (mSoundPlayer[i] != 0) {
2918             mSoundPlayer[i]->disconnect();
2919             mSoundPlayer[i].clear();
2920         }
2921     }
2922 }
2923 
playSound(sound_kind kind)2924 void CameraService::playSound(sound_kind kind) {
2925     ATRACE_CALL();
2926 
2927     LOG1("playSound(%d)", kind);
2928     if (kind < 0 || kind >= NUM_SOUNDS) {
2929         ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
2930         return;
2931     }
2932 
2933     Mutex::Autolock lock(mSoundLock);
2934     loadSoundLocked(kind);
2935     sp<MediaPlayer> player = mSoundPlayer[kind];
2936     if (player != 0) {
2937         player->seekTo(0);
2938         player->start();
2939     }
2940 }
2941 
2942 // ----------------------------------------------------------------------------
2943 
Client(const sp<CameraService> & cameraService,const sp<ICameraClient> & cameraClient,const String16 & clientPackageName,const std::optional<String16> & clientFeatureId,const String8 & cameraIdStr,int api1CameraId,int cameraFacing,int sensorOrientation,int clientPid,uid_t clientUid,int servicePid)2944 CameraService::Client::Client(const sp<CameraService>& cameraService,
2945         const sp<ICameraClient>& cameraClient,
2946         const String16& clientPackageName,
2947         const std::optional<String16>& clientFeatureId,
2948         const String8& cameraIdStr,
2949         int api1CameraId, int cameraFacing, int sensorOrientation,
2950         int clientPid, uid_t clientUid,
2951         int servicePid) :
2952         CameraService::BasicClient(cameraService,
2953                 IInterface::asBinder(cameraClient),
2954                 clientPackageName, clientFeatureId,
2955                 cameraIdStr, cameraFacing, sensorOrientation,
2956                 clientPid, clientUid,
2957                 servicePid),
2958         mCameraId(api1CameraId)
2959 {
2960     int callingPid = CameraThreadState::getCallingPid();
2961     LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
2962 
2963     mRemoteCallback = cameraClient;
2964 
2965     cameraService->increaseSoundRef();
2966 
2967     LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
2968 }
2969 
2970 // tear down the client
~Client()2971 CameraService::Client::~Client() {
2972     ALOGV("~Client");
2973     mDestructionStarted = true;
2974 
2975     sCameraService->decreaseSoundRef();
2976     // unconditionally disconnect. function is idempotent
2977     Client::disconnect();
2978 }
2979 
2980 sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
2981 
BasicClient(const sp<CameraService> & cameraService,const sp<IBinder> & remoteCallback,const String16 & clientPackageName,const std::optional<String16> & clientFeatureId,const String8 & cameraIdStr,int cameraFacing,int sensorOrientation,int clientPid,uid_t clientUid,int servicePid)2982 CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
2983         const sp<IBinder>& remoteCallback,
2984         const String16& clientPackageName, const std::optional<String16>& clientFeatureId,
2985         const String8& cameraIdStr, int cameraFacing, int sensorOrientation,
2986         int clientPid, uid_t clientUid,
2987         int servicePid):
2988         mDestructionStarted(false),
2989         mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
2990         mClientPackageName(clientPackageName), mClientFeatureId(clientFeatureId),
2991         mClientPid(clientPid), mClientUid(clientUid),
2992         mServicePid(servicePid),
2993         mDisconnected(false), mUidIsTrusted(false),
2994         mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
2995         mRemoteBinder(remoteCallback),
2996         mOpsActive(false),
2997         mOpsStreaming(false)
2998 {
2999     if (sCameraService == nullptr) {
3000         sCameraService = cameraService;
3001     }
3002 
3003     // In some cases the calling code has no access to the package it runs under.
3004     // For example, NDK camera API.
3005     // In this case we will get the packages for the calling UID and pick the first one
3006     // for attributing the app op. This will work correctly for runtime permissions
3007     // as for legacy apps we will toggle the app op for all packages in the UID.
3008     // The caveat is that the operation may be attributed to the wrong package and
3009     // stats based on app ops may be slightly off.
3010     if (mClientPackageName.size() <= 0) {
3011         sp<IServiceManager> sm = defaultServiceManager();
3012         sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
3013         if (binder == 0) {
3014             ALOGE("Cannot get permission service");
3015             // Leave mClientPackageName unchanged (empty) and the further interaction
3016             // with camera will fail in BasicClient::startCameraOps
3017             return;
3018         }
3019 
3020         sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
3021         Vector<String16> packages;
3022 
3023         permCtrl->getPackagesForUid(mClientUid, packages);
3024 
3025         if (packages.isEmpty()) {
3026             ALOGE("No packages for calling UID");
3027             // Leave mClientPackageName unchanged (empty) and the further interaction
3028             // with camera will fail in BasicClient::startCameraOps
3029             return;
3030         }
3031         mClientPackageName = packages[0];
3032     }
3033     if (getCurrentServingCall() != BinderCallType::HWBINDER) {
3034         mAppOpsManager = std::make_unique<AppOpsManager>();
3035     }
3036 
3037     mUidIsTrusted = isTrustedCallingUid(mClientUid);
3038 }
3039 
~BasicClient()3040 CameraService::BasicClient::~BasicClient() {
3041     ALOGV("~BasicClient");
3042     mDestructionStarted = true;
3043 }
3044 
disconnect()3045 binder::Status CameraService::BasicClient::disconnect() {
3046     binder::Status res = Status::ok();
3047     if (mDisconnected) {
3048         return res;
3049     }
3050     mDisconnected = true;
3051 
3052     sCameraService->removeByClient(this);
3053     sCameraService->logDisconnected(mCameraIdStr, mClientPid, String8(mClientPackageName));
3054     sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
3055             mCameraIdStr.c_str());
3056 
3057     sp<IBinder> remote = getRemote();
3058     if (remote != nullptr) {
3059         remote->unlinkToDeath(sCameraService);
3060     }
3061 
3062     finishCameraOps();
3063     // Notify flashlight that a camera device is closed.
3064     sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
3065     ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
3066             mClientPid);
3067 
3068     // client shouldn't be able to call into us anymore
3069     mClientPid = 0;
3070 
3071     return res;
3072 }
3073 
dump(int,const Vector<String16> &)3074 status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
3075     // No dumping of clients directly over Binder,
3076     // must go through CameraService::dump
3077     android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
3078             CameraThreadState::getCallingUid(), NULL, 0);
3079     return OK;
3080 }
3081 
getPackageName() const3082 String16 CameraService::BasicClient::getPackageName() const {
3083     return mClientPackageName;
3084 }
3085 
getCameraFacing() const3086 int CameraService::BasicClient::getCameraFacing() const {
3087     return mCameraFacing;
3088 }
3089 
getCameraOrientation() const3090 int CameraService::BasicClient::getCameraOrientation() const {
3091     return mOrientation;
3092 }
3093 
getClientPid() const3094 int CameraService::BasicClient::getClientPid() const {
3095     return mClientPid;
3096 }
3097 
getClientUid() const3098 uid_t CameraService::BasicClient::getClientUid() const {
3099     return mClientUid;
3100 }
3101 
canCastToApiClient(apiLevel level) const3102 bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
3103     // Defaults to API2.
3104     return level == API_2;
3105 }
3106 
setAudioRestriction(int32_t mode)3107 status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
3108     {
3109         Mutex::Autolock l(mAudioRestrictionLock);
3110         mAudioRestriction = mode;
3111     }
3112     sCameraService->updateAudioRestriction();
3113     return OK;
3114 }
3115 
getServiceAudioRestriction() const3116 int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
3117     return sCameraService->updateAudioRestriction();
3118 }
3119 
getAudioRestriction() const3120 int32_t CameraService::BasicClient::getAudioRestriction() const {
3121     Mutex::Autolock l(mAudioRestrictionLock);
3122     return mAudioRestriction;
3123 }
3124 
isValidAudioRestriction(int32_t mode)3125 bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
3126     switch (mode) {
3127         case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
3128         case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
3129         case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
3130             return true;
3131         default:
3132             return false;
3133     }
3134 }
3135 
handleAppOpMode(int32_t mode)3136 status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
3137     if (mode == AppOpsManager::MODE_ERRORED) {
3138         ALOGI("Camera %s: Access for \"%s\" has been revoked",
3139                 mCameraIdStr.string(), String8(mClientPackageName).string());
3140         return PERMISSION_DENIED;
3141     } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
3142         // If the calling Uid is trusted (a native service), the AppOpsManager could
3143         // return MODE_IGNORED. Do not treat such case as error.
3144         bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
3145                 mClientPackageName);
3146         bool isCameraPrivacyEnabled =
3147                 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled(
3148                     multiuser_get_user_id(mClientUid));
3149         if (!isUidActive || !isCameraPrivacyEnabled) {
3150             ALOGI("Camera %s: Access for \"%s\" has been restricted",
3151                     mCameraIdStr.string(), String8(mClientPackageName).string());
3152             // Return the same error as for device policy manager rejection
3153             return -EACCES;
3154         }
3155     }
3156     return OK;
3157 }
3158 
startCameraOps()3159 status_t CameraService::BasicClient::startCameraOps() {
3160     ATRACE_CALL();
3161 
3162     {
3163         ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
3164               __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
3165     }
3166     if (mAppOpsManager != nullptr) {
3167         // Notify app ops that the camera is not available
3168         mOpsCallback = new OpsCallback(this);
3169         mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
3170                 mClientPackageName, mOpsCallback);
3171 
3172         // Just check for camera acccess here on open - delay startOp until
3173         // camera frames start streaming in startCameraStreamingOps
3174         int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
3175                 mClientPackageName);
3176         status_t res = handleAppOpMode(mode);
3177         if (res != OK) {
3178             return res;
3179         }
3180     }
3181 
3182     mOpsActive = true;
3183 
3184     // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
3185     sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
3186 
3187     sCameraService->mUidPolicy->registerMonitorUid(mClientUid);
3188 
3189     // Notify listeners of camera open/close status
3190     sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
3191 
3192     return OK;
3193 }
3194 
startCameraStreamingOps()3195 status_t CameraService::BasicClient::startCameraStreamingOps() {
3196     ATRACE_CALL();
3197 
3198     if (!mOpsActive) {
3199         ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
3200         return INVALID_OPERATION;
3201     }
3202     if (mOpsStreaming) {
3203         ALOGV("%s: Streaming already active!", __FUNCTION__);
3204         return OK;
3205     }
3206 
3207     ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
3208             __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
3209 
3210     if (mAppOpsManager != nullptr) {
3211         int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
3212                 mClientPackageName, /*startIfModeDefault*/ false, mClientFeatureId,
3213                 String16("start camera ") + String16(mCameraIdStr));
3214         status_t res = handleAppOpMode(mode);
3215         if (res != OK) {
3216             return res;
3217         }
3218     }
3219 
3220     mOpsStreaming = true;
3221 
3222     return OK;
3223 }
3224 
noteAppOp()3225 status_t CameraService::BasicClient::noteAppOp() {
3226     ATRACE_CALL();
3227 
3228     ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d",
3229             __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
3230 
3231     // noteAppOp is only used for when camera mute is not supported, in order
3232     // to trigger the sensor privacy "Unblock" dialog
3233     if (mAppOpsManager != nullptr) {
3234         int32_t mode = mAppOpsManager->noteOp(AppOpsManager::OP_CAMERA, mClientUid,
3235                 mClientPackageName, mClientFeatureId,
3236                 String16("start camera ") + String16(mCameraIdStr));
3237         status_t res = handleAppOpMode(mode);
3238         if (res != OK) {
3239             return res;
3240         }
3241     }
3242 
3243     return OK;
3244 }
3245 
finishCameraStreamingOps()3246 status_t CameraService::BasicClient::finishCameraStreamingOps() {
3247     ATRACE_CALL();
3248 
3249     if (!mOpsActive) {
3250         ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
3251         return INVALID_OPERATION;
3252     }
3253     if (!mOpsStreaming) {
3254         ALOGV("%s: Streaming not active!", __FUNCTION__);
3255         return OK;
3256     }
3257 
3258     if (mAppOpsManager != nullptr) {
3259         mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
3260                 mClientPackageName, mClientFeatureId);
3261         mOpsStreaming = false;
3262     }
3263 
3264     return OK;
3265 }
3266 
finishCameraOps()3267 status_t CameraService::BasicClient::finishCameraOps() {
3268     ATRACE_CALL();
3269 
3270     if (mOpsStreaming) {
3271         // Make sure we've notified everyone about camera stopping
3272         finishCameraStreamingOps();
3273     }
3274 
3275     // Check if startCameraOps succeeded, and if so, finish the camera op
3276     if (mOpsActive) {
3277         mOpsActive = false;
3278 
3279         // This function is called when a client disconnects. This should
3280         // release the camera, but actually only if it was in a proper
3281         // functional state, i.e. with status NOT_AVAILABLE
3282         std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
3283                 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
3284 
3285         // Transition to PRESENT if the camera is not in either of the rejected states
3286         sCameraService->updateStatus(StatusInternal::PRESENT,
3287                 mCameraIdStr, rejected);
3288     }
3289     // Always stop watching, even if no camera op is active
3290     if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
3291         mAppOpsManager->stopWatchingMode(mOpsCallback);
3292     }
3293     mOpsCallback.clear();
3294 
3295     sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid);
3296 
3297     // Notify listeners of camera open/close status
3298     sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
3299 
3300     return OK;
3301 }
3302 
opChanged(int32_t op,const String16 &)3303 void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
3304     ATRACE_CALL();
3305     if (mAppOpsManager == nullptr) {
3306         return;
3307     }
3308     // TODO : add offline camera session case
3309     if (op != AppOpsManager::OP_CAMERA) {
3310         ALOGW("Unexpected app ops notification received: %d", op);
3311         return;
3312     }
3313 
3314     int32_t res;
3315     res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
3316             mClientUid, mClientPackageName);
3317     ALOGV("checkOp returns: %d, %s ", res,
3318             res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
3319             res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
3320             res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
3321             "UNKNOWN");
3322 
3323     if (res == AppOpsManager::MODE_ERRORED) {
3324         ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
3325               String8(mClientPackageName).string());
3326         block();
3327     } else if (res == AppOpsManager::MODE_IGNORED) {
3328         bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
3329         bool isCameraPrivacyEnabled =
3330                 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled(
3331                         multiuser_get_user_id(mClientUid));
3332         ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d",
3333                 mCameraIdStr.string(), String8(mClientPackageName).string(),
3334                 mUidIsTrusted, isUidActive);
3335         // If the calling Uid is trusted (a native service), or the client Uid is active (WAR for
3336         // b/175320666), the AppOpsManager could return MODE_IGNORED. Do not treat such cases as
3337         // error.
3338         if (!mUidIsTrusted) {
3339             if (isUidActive && isCameraPrivacyEnabled && supportsCameraMute()) {
3340                 setCameraMute(true);
3341             } else if (!isUidActive
3342                 || (isCameraPrivacyEnabled && !supportsCameraMute())) {
3343                 block();
3344             }
3345         }
3346     } else if (res == AppOpsManager::MODE_ALLOWED) {
3347         setCameraMute(sCameraService->mOverrideCameraMuteMode);
3348     }
3349 }
3350 
block()3351 void CameraService::BasicClient::block() {
3352     ATRACE_CALL();
3353 
3354     // Reset the client PID to allow server-initiated disconnect,
3355     // and to prevent further calls by client.
3356     mClientPid = CameraThreadState::getCallingPid();
3357     CaptureResultExtras resultExtras; // a dummy result (invalid)
3358     notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
3359     disconnect();
3360 }
3361 
3362 // ----------------------------------------------------------------------------
3363 
notifyError(int32_t errorCode,const CaptureResultExtras & resultExtras)3364 void CameraService::Client::notifyError(int32_t errorCode,
3365         const CaptureResultExtras& resultExtras) {
3366     (void) resultExtras;
3367     if (mRemoteCallback != NULL) {
3368         int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
3369         if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
3370             api1ErrorCode = CAMERA_ERROR_DISABLED;
3371         }
3372         mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
3373     } else {
3374         ALOGE("mRemoteCallback is NULL!!");
3375     }
3376 }
3377 
3378 // NOTE: function is idempotent
disconnect()3379 binder::Status CameraService::Client::disconnect() {
3380     ALOGV("Client::disconnect");
3381     return BasicClient::disconnect();
3382 }
3383 
canCastToApiClient(apiLevel level) const3384 bool CameraService::Client::canCastToApiClient(apiLevel level) const {
3385     return level == API_1;
3386 }
3387 
OpsCallback(wp<BasicClient> client)3388 CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
3389         mClient(client) {
3390 }
3391 
opChanged(int32_t op,const String16 & packageName)3392 void CameraService::Client::OpsCallback::opChanged(int32_t op,
3393         const String16& packageName) {
3394     sp<BasicClient> client = mClient.promote();
3395     if (client != NULL) {
3396         client->opChanged(op, packageName);
3397     }
3398 }
3399 
3400 // ----------------------------------------------------------------------------
3401 //                  UidPolicy
3402 // ----------------------------------------------------------------------------
3403 
registerSelf()3404 void CameraService::UidPolicy::registerSelf() {
3405     Mutex::Autolock _l(mUidLock);
3406 
3407     if (mRegistered) return;
3408     status_t res = mAm.linkToDeath(this);
3409     mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
3410             | ActivityManager::UID_OBSERVER_IDLE
3411             | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE,
3412             ActivityManager::PROCESS_STATE_UNKNOWN,
3413             String16("cameraserver"));
3414     if (res == OK) {
3415         mRegistered = true;
3416         ALOGV("UidPolicy: Registered with ActivityManager");
3417     }
3418 }
3419 
unregisterSelf()3420 void CameraService::UidPolicy::unregisterSelf() {
3421     Mutex::Autolock _l(mUidLock);
3422 
3423     mAm.unregisterUidObserver(this);
3424     mAm.unlinkToDeath(this);
3425     mRegistered = false;
3426     mActiveUids.clear();
3427     ALOGV("UidPolicy: Unregistered with ActivityManager");
3428 }
3429 
onUidGone(uid_t uid,bool disabled)3430 void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
3431     onUidIdle(uid, disabled);
3432 }
3433 
onUidActive(uid_t uid)3434 void CameraService::UidPolicy::onUidActive(uid_t uid) {
3435     Mutex::Autolock _l(mUidLock);
3436     mActiveUids.insert(uid);
3437 }
3438 
onUidIdle(uid_t uid,bool)3439 void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
3440     bool deleted = false;
3441     {
3442         Mutex::Autolock _l(mUidLock);
3443         if (mActiveUids.erase(uid) > 0) {
3444             deleted = true;
3445         }
3446     }
3447     if (deleted) {
3448         sp<CameraService> service = mService.promote();
3449         if (service != nullptr) {
3450             service->blockClientsForUid(uid);
3451         }
3452     }
3453 }
3454 
onUidStateChanged(uid_t uid,int32_t procState,int64_t procStateSeq __unused,int32_t capability __unused)3455 void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
3456         int64_t procStateSeq __unused, int32_t capability __unused) {
3457     bool procStateChange = false;
3458     {
3459         Mutex::Autolock _l(mUidLock);
3460         if ((mMonitoredUids.find(uid) != mMonitoredUids.end()) &&
3461                 (mMonitoredUids[uid].first != procState)) {
3462             mMonitoredUids[uid].first = procState;
3463             procStateChange = true;
3464         }
3465     }
3466 
3467     if (procStateChange) {
3468         sp<CameraService> service = mService.promote();
3469         if (service != nullptr) {
3470             service->notifyMonitoredUids();
3471         }
3472     }
3473 }
3474 
registerMonitorUid(uid_t uid)3475 void CameraService::UidPolicy::registerMonitorUid(uid_t uid) {
3476     Mutex::Autolock _l(mUidLock);
3477     auto it = mMonitoredUids.find(uid);
3478     if (it != mMonitoredUids.end()) {
3479         it->second.second++;
3480     } else {
3481         mMonitoredUids.emplace(
3482                 std::pair<uid_t, std::pair<int32_t, size_t>> (uid,
3483                     std::pair<int32_t, size_t> (ActivityManager::PROCESS_STATE_NONEXISTENT, 1)));
3484     }
3485 }
3486 
unregisterMonitorUid(uid_t uid)3487 void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid) {
3488     Mutex::Autolock _l(mUidLock);
3489     auto it = mMonitoredUids.find(uid);
3490     if (it != mMonitoredUids.end()) {
3491         it->second.second--;
3492         if (it->second.second == 0) {
3493             mMonitoredUids.erase(it);
3494         }
3495     } else {
3496         ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
3497     }
3498 }
3499 
isUidActive(uid_t uid,String16 callingPackage)3500 bool CameraService::UidPolicy::isUidActive(uid_t uid, String16 callingPackage) {
3501     Mutex::Autolock _l(mUidLock);
3502     return isUidActiveLocked(uid, callingPackage);
3503 }
3504 
3505 static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
3506 static const int64_t kPollUidActiveTimeoutMillis = 50;
3507 
isUidActiveLocked(uid_t uid,String16 callingPackage)3508 bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
3509     // Non-app UIDs are considered always active
3510     // If activity manager is unreachable, assume everything is active
3511     if (uid < FIRST_APPLICATION_UID || !mRegistered) {
3512         return true;
3513     }
3514     auto it = mOverrideUids.find(uid);
3515     if (it != mOverrideUids.end()) {
3516         return it->second;
3517     }
3518     bool active = mActiveUids.find(uid) != mActiveUids.end();
3519     if (!active) {
3520         // We want active UIDs to always access camera with their first attempt since
3521         // there is no guarantee the app is robustly written and would retry getting
3522         // the camera on failure. The inverse case is not a problem as we would take
3523         // camera away soon once we get the callback that the uid is no longer active.
3524         ActivityManager am;
3525         // Okay to access with a lock held as UID changes are dispatched without
3526         // a lock and we are a higher level component.
3527         int64_t startTimeMillis = 0;
3528         do {
3529             // TODO: Fix this b/109950150!
3530             // Okay this is a hack. There is a race between the UID turning active and
3531             // activity being resumed. The proper fix is very risky, so we temporary add
3532             // some polling which should happen pretty rarely anyway as the race is hard
3533             // to hit.
3534             active = mActiveUids.find(uid) != mActiveUids.end();
3535             if (!active) active = am.isUidActive(uid, callingPackage);
3536             if (active) {
3537                 break;
3538             }
3539             if (startTimeMillis <= 0) {
3540                 startTimeMillis = uptimeMillis();
3541             }
3542             int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
3543             int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
3544             if (remainingTimeMillis <= 0) {
3545                 break;
3546             }
3547             remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
3548 
3549             mUidLock.unlock();
3550             usleep(remainingTimeMillis * 1000);
3551             mUidLock.lock();
3552         } while (true);
3553 
3554         if (active) {
3555             // Now that we found out the UID is actually active, cache that
3556             mActiveUids.insert(uid);
3557         }
3558     }
3559     return active;
3560 }
3561 
getProcState(uid_t uid)3562 int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
3563     Mutex::Autolock _l(mUidLock);
3564     return getProcStateLocked(uid);
3565 }
3566 
getProcStateLocked(uid_t uid)3567 int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
3568     int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
3569     if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
3570         procState = mMonitoredUids[uid].first;
3571     }
3572     return procState;
3573 }
3574 
addOverrideUid(uid_t uid,String16 callingPackage,bool active)3575 void CameraService::UidPolicy::UidPolicy::addOverrideUid(uid_t uid,
3576         String16 callingPackage, bool active) {
3577     updateOverrideUid(uid, callingPackage, active, true);
3578 }
3579 
removeOverrideUid(uid_t uid,String16 callingPackage)3580 void CameraService::UidPolicy::removeOverrideUid(uid_t uid, String16 callingPackage) {
3581     updateOverrideUid(uid, callingPackage, false, false);
3582 }
3583 
binderDied(const wp<IBinder> &)3584 void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
3585     Mutex::Autolock _l(mUidLock);
3586     ALOGV("UidPolicy: ActivityManager has died");
3587     mRegistered = false;
3588     mActiveUids.clear();
3589 }
3590 
updateOverrideUid(uid_t uid,String16 callingPackage,bool active,bool insert)3591 void CameraService::UidPolicy::updateOverrideUid(uid_t uid, String16 callingPackage,
3592         bool active, bool insert) {
3593     bool wasActive = false;
3594     bool isActive = false;
3595     {
3596         Mutex::Autolock _l(mUidLock);
3597         wasActive = isUidActiveLocked(uid, callingPackage);
3598         mOverrideUids.erase(uid);
3599         if (insert) {
3600             mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
3601         }
3602         isActive = isUidActiveLocked(uid, callingPackage);
3603     }
3604     if (wasActive != isActive && !isActive) {
3605         sp<CameraService> service = mService.promote();
3606         if (service != nullptr) {
3607             service->blockClientsForUid(uid);
3608         }
3609     }
3610 }
3611 
3612 // ----------------------------------------------------------------------------
3613 //                  SensorPrivacyPolicy
3614 // ----------------------------------------------------------------------------
registerSelf()3615 void CameraService::SensorPrivacyPolicy::registerSelf() {
3616     Mutex::Autolock _l(mSensorPrivacyLock);
3617     if (mRegistered) {
3618         return;
3619     }
3620     hasCameraPrivacyFeature(); // Called so the result is cached
3621     mSpm.addSensorPrivacyListener(this);
3622     mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
3623     status_t res = mSpm.linkToDeath(this);
3624     if (res == OK) {
3625         mRegistered = true;
3626         ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
3627     }
3628 }
3629 
unregisterSelf()3630 void CameraService::SensorPrivacyPolicy::unregisterSelf() {
3631     Mutex::Autolock _l(mSensorPrivacyLock);
3632     mSpm.removeSensorPrivacyListener(this);
3633     mSpm.unlinkToDeath(this);
3634     mRegistered = false;
3635     ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
3636 }
3637 
isSensorPrivacyEnabled()3638 bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
3639     Mutex::Autolock _l(mSensorPrivacyLock);
3640     return mSensorPrivacyEnabled;
3641 }
3642 
isCameraPrivacyEnabled(userid_t userId)3643 bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled(userid_t userId) {
3644     if (!hasCameraPrivacyFeature()) {
3645         return false;
3646     }
3647     return mSpm.isIndividualSensorPrivacyEnabled(userId,
3648         SensorPrivacyManager::INDIVIDUAL_SENSOR_CAMERA);
3649 }
3650 
onSensorPrivacyChanged(bool enabled)3651 binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
3652     {
3653         Mutex::Autolock _l(mSensorPrivacyLock);
3654         mSensorPrivacyEnabled = enabled;
3655     }
3656     // if sensor privacy is enabled then block all clients from accessing the camera
3657     if (enabled) {
3658         sp<CameraService> service = mService.promote();
3659         if (service != nullptr) {
3660             service->blockAllClients();
3661         }
3662     }
3663     return binder::Status::ok();
3664 }
3665 
binderDied(const wp<IBinder> &)3666 void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
3667     Mutex::Autolock _l(mSensorPrivacyLock);
3668     ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
3669     mRegistered = false;
3670 }
3671 
hasCameraPrivacyFeature()3672 bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
3673     return mSpm.supportsSensorToggle(SensorPrivacyManager::INDIVIDUAL_SENSOR_CAMERA);
3674 }
3675 
3676 // ----------------------------------------------------------------------------
3677 //                  CameraState
3678 // ----------------------------------------------------------------------------
3679 
CameraState(const String8 & id,int cost,const std::set<String8> & conflicting,SystemCameraKind systemCameraKind)3680 CameraService::CameraState::CameraState(const String8& id, int cost,
3681         const std::set<String8>& conflicting, SystemCameraKind systemCameraKind) : mId(id),
3682         mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
3683         mSystemCameraKind(systemCameraKind) {}
3684 
~CameraState()3685 CameraService::CameraState::~CameraState() {}
3686 
getStatus() const3687 CameraService::StatusInternal CameraService::CameraState::getStatus() const {
3688     Mutex::Autolock lock(mStatusLock);
3689     return mStatus;
3690 }
3691 
getUnavailablePhysicalIds() const3692 std::vector<String8> CameraService::CameraState::getUnavailablePhysicalIds() const {
3693     Mutex::Autolock lock(mStatusLock);
3694     std::vector<String8> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
3695     return res;
3696 }
3697 
getShimParams() const3698 CameraParameters CameraService::CameraState::getShimParams() const {
3699     return mShimParams;
3700 }
3701 
setShimParams(const CameraParameters & params)3702 void CameraService::CameraState::setShimParams(const CameraParameters& params) {
3703     mShimParams = params;
3704 }
3705 
getCost() const3706 int CameraService::CameraState::getCost() const {
3707     return mCost;
3708 }
3709 
getConflicting() const3710 std::set<String8> CameraService::CameraState::getConflicting() const {
3711     return mConflicting;
3712 }
3713 
getId() const3714 String8 CameraService::CameraState::getId() const {
3715     return mId;
3716 }
3717 
getSystemCameraKind() const3718 SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
3719     return mSystemCameraKind;
3720 }
3721 
addUnavailablePhysicalId(const String8 & physicalId)3722 bool CameraService::CameraState::addUnavailablePhysicalId(const String8& physicalId) {
3723     Mutex::Autolock lock(mStatusLock);
3724     auto result = mUnavailablePhysicalIds.insert(physicalId);
3725     return result.second;
3726 }
3727 
removeUnavailablePhysicalId(const String8 & physicalId)3728 bool CameraService::CameraState::removeUnavailablePhysicalId(const String8& physicalId) {
3729     Mutex::Autolock lock(mStatusLock);
3730     auto count = mUnavailablePhysicalIds.erase(physicalId);
3731     return count > 0;
3732 }
3733 
3734 // ----------------------------------------------------------------------------
3735 //                  ClientEventListener
3736 // ----------------------------------------------------------------------------
3737 
onClientAdded(const resource_policy::ClientDescriptor<String8,sp<CameraService::BasicClient>> & descriptor)3738 void CameraService::ClientEventListener::onClientAdded(
3739         const resource_policy::ClientDescriptor<String8,
3740         sp<CameraService::BasicClient>>& descriptor) {
3741     const auto& basicClient = descriptor.getValue();
3742     if (basicClient.get() != nullptr) {
3743         BatteryNotifier& notifier(BatteryNotifier::getInstance());
3744         notifier.noteStartCamera(descriptor.getKey(),
3745                 static_cast<int>(basicClient->getClientUid()));
3746     }
3747 }
3748 
onClientRemoved(const resource_policy::ClientDescriptor<String8,sp<CameraService::BasicClient>> & descriptor)3749 void CameraService::ClientEventListener::onClientRemoved(
3750         const resource_policy::ClientDescriptor<String8,
3751         sp<CameraService::BasicClient>>& descriptor) {
3752     const auto& basicClient = descriptor.getValue();
3753     if (basicClient.get() != nullptr) {
3754         BatteryNotifier& notifier(BatteryNotifier::getInstance());
3755         notifier.noteStopCamera(descriptor.getKey(),
3756                 static_cast<int>(basicClient->getClientUid()));
3757     }
3758 }
3759 
3760 
3761 // ----------------------------------------------------------------------------
3762 //                  CameraClientManager
3763 // ----------------------------------------------------------------------------
3764 
CameraClientManager()3765 CameraService::CameraClientManager::CameraClientManager() {
3766     setListener(std::make_shared<ClientEventListener>());
3767 }
3768 
~CameraClientManager()3769 CameraService::CameraClientManager::~CameraClientManager() {}
3770 
getCameraClient(const String8 & id) const3771 sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
3772         const String8& id) const {
3773     auto descriptor = get(id);
3774     if (descriptor == nullptr) {
3775         return sp<BasicClient>{nullptr};
3776     }
3777     return descriptor->getValue();
3778 }
3779 
toString() const3780 String8 CameraService::CameraClientManager::toString() const {
3781     auto all = getAll();
3782     String8 ret("[");
3783     bool hasAny = false;
3784     for (auto& i : all) {
3785         hasAny = true;
3786         String8 key = i->getKey();
3787         int32_t cost = i->getCost();
3788         int32_t pid = i->getOwnerId();
3789         int32_t score = i->getPriority().getScore();
3790         int32_t state = i->getPriority().getState();
3791         auto conflicting = i->getConflicting();
3792         auto clientSp = i->getValue();
3793         String8 packageName;
3794         userid_t clientUserId = 0;
3795         if (clientSp.get() != nullptr) {
3796             packageName = String8{clientSp->getPackageName()};
3797             uid_t clientUid = clientSp->getClientUid();
3798             clientUserId = multiuser_get_user_id(clientUid);
3799         }
3800         ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
3801                 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
3802 
3803         if (clientSp.get() != nullptr) {
3804             ret.appendFormat("User Id: %d, ", clientUserId);
3805         }
3806         if (packageName.size() != 0) {
3807             ret.appendFormat("Client Package Name: %s", packageName.string());
3808         }
3809 
3810         ret.append(", Conflicting Client Devices: {");
3811         for (auto& j : conflicting) {
3812             ret.appendFormat("%s, ", j.string());
3813         }
3814         ret.append("})");
3815     }
3816     if (hasAny) ret.append("\n");
3817     ret.append("]\n");
3818     return ret;
3819 }
3820 
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)3821 CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3822         const String8& key, const sp<BasicClient>& value, int32_t cost,
3823         const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
3824         int32_t state, int32_t oomScoreOffset) {
3825 
3826     bool isVendorClient = getCurrentServingCall() == BinderCallType::HWBINDER;
3827     int32_t score_adj = isVendorClient ? kVendorClientScore : score;
3828     int32_t state_adj = isVendorClient ? kVendorClientState: state;
3829 
3830     return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
3831             key, value, cost, conflictingKeys, score_adj, ownerId, state_adj, isVendorClient,
3832             oomScoreOffset);
3833 }
3834 
makeClientDescriptor(const sp<BasicClient> & value,const CameraService::DescriptorPtr & partial,int32_t oomScoreOffset)3835 CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3836         const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
3837         int32_t oomScoreOffset) {
3838     return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
3839             partial->getConflicting(), partial->getPriority().getScore(),
3840             partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset);
3841 }
3842 
3843 // ----------------------------------------------------------------------------
3844 //                  InjectionStatusListener
3845 // ----------------------------------------------------------------------------
3846 
addListener(const sp<ICameraInjectionCallback> & callback)3847 void CameraService::InjectionStatusListener::addListener(
3848         const sp<ICameraInjectionCallback>& callback) {
3849     Mutex::Autolock lock(mListenerLock);
3850     if (mCameraInjectionCallback) return;
3851     status_t res = IInterface::asBinder(callback)->linkToDeath(this);
3852     if (res == OK) {
3853         mCameraInjectionCallback = callback;
3854     }
3855 }
3856 
removeListener()3857 void CameraService::InjectionStatusListener::removeListener() {
3858     Mutex::Autolock lock(mListenerLock);
3859     if (mCameraInjectionCallback == nullptr) {
3860         ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
3861         return;
3862     }
3863     IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
3864     mCameraInjectionCallback = nullptr;
3865 }
3866 
notifyInjectionError(int errorCode)3867 void CameraService::InjectionStatusListener::notifyInjectionError(
3868         int errorCode) {
3869     Mutex::Autolock lock(mListenerLock);
3870     if (mCameraInjectionCallback == nullptr) {
3871         ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
3872         return;
3873     }
3874     mCameraInjectionCallback->onInjectionError(errorCode);
3875 }
3876 
binderDied(const wp<IBinder> &)3877 void CameraService::InjectionStatusListener::binderDied(
3878         const wp<IBinder>& /*who*/) {
3879     Mutex::Autolock lock(mListenerLock);
3880     ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
3881     auto parent = mParent.promote();
3882     if (parent != nullptr) {
3883         parent->stopInjectionImpl();
3884     }
3885 }
3886 
3887 // ----------------------------------------------------------------------------
3888 //                  CameraInjectionSession
3889 // ----------------------------------------------------------------------------
3890 
stopInjection()3891 binder::Status CameraService::CameraInjectionSession::stopInjection() {
3892     Mutex::Autolock lock(mInjectionSessionLock);
3893     auto parent = mParent.promote();
3894     if (parent == nullptr) {
3895         ALOGE("CameraInjectionSession: Parent is gone");
3896         return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
3897                 "Camera service encountered error");
3898     }
3899     parent->stopInjectionImpl();
3900     return binder::Status::ok();
3901 }
3902 
3903 // ----------------------------------------------------------------------------
3904 
3905 static const int kDumpLockRetries = 50;
3906 static const int kDumpLockSleep = 60000;
3907 
tryLock(Mutex & mutex)3908 static bool tryLock(Mutex& mutex)
3909 {
3910     bool locked = false;
3911     for (int i = 0; i < kDumpLockRetries; ++i) {
3912         if (mutex.tryLock() == NO_ERROR) {
3913             locked = true;
3914             break;
3915         }
3916         usleep(kDumpLockSleep);
3917     }
3918     return locked;
3919 }
3920 
cacheDump()3921 void CameraService::cacheDump() {
3922     if (mMemFd != -1) {
3923         const Vector<String16> args;
3924         ATRACE_CALL();
3925         // Acquiring service lock here will avoid the deadlock since
3926         // cacheDump will not be called during the second disconnect.
3927         Mutex::Autolock lock(mServiceLock);
3928 
3929         Mutex::Autolock l(mCameraStatesLock);
3930         // Start collecting the info for open sessions and store it in temp file.
3931         for (const auto& state : mCameraStates) {
3932             String8 cameraId = state.first;
3933             auto clientDescriptor = mActiveClientManager.get(cameraId);
3934             if (clientDescriptor != nullptr) {
3935                 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.string());
3936                 // Log the current open session info before device is disconnected.
3937                 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
3938             }
3939         }
3940     }
3941 }
3942 
dump(int fd,const Vector<String16> & args)3943 status_t CameraService::dump(int fd, const Vector<String16>& args) {
3944     ATRACE_CALL();
3945 
3946     if (checkCallingPermission(sDumpPermission) == false) {
3947         dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
3948                 CameraThreadState::getCallingPid(),
3949                 CameraThreadState::getCallingUid());
3950         return NO_ERROR;
3951     }
3952     bool locked = tryLock(mServiceLock);
3953     // failed to lock - CameraService is probably deadlocked
3954     if (!locked) {
3955         dprintf(fd, "!! CameraService may be deadlocked !!\n");
3956     }
3957 
3958     if (!mInitialized) {
3959         dprintf(fd, "!! No camera HAL available !!\n");
3960 
3961         // Dump event log for error information
3962         dumpEventLog(fd);
3963 
3964         if (locked) mServiceLock.unlock();
3965         return NO_ERROR;
3966     }
3967     dprintf(fd, "\n== Service global info: ==\n\n");
3968     dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
3969     dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
3970     dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
3971             mNormalDeviceIdsWithoutSystemCamera.size());
3972     for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
3973         dprintf(fd, "    Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
3974     }
3975     String8 activeClientString = mActiveClientManager.toString();
3976     dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
3977     dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
3978 
3979     dumpEventLog(fd);
3980 
3981     bool stateLocked = tryLock(mCameraStatesLock);
3982     if (!stateLocked) {
3983         dprintf(fd, "CameraStates in use, may be deadlocked\n");
3984     }
3985 
3986     int argSize = args.size();
3987     for (int i = 0; i < argSize; i++) {
3988         if (args[i] == TagMonitor::kMonitorOption) {
3989             if (i + 1 < argSize) {
3990                 mMonitorTags = String8(args[i + 1]);
3991             }
3992             break;
3993         }
3994     }
3995 
3996     for (auto& state : mCameraStates) {
3997         String8 cameraId = state.first;
3998 
3999         dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
4000 
4001         CameraParameters p = state.second->getShimParams();
4002         if (!p.isEmpty()) {
4003             dprintf(fd, "  Camera1 API shim is using parameters:\n        ");
4004             p.dump(fd, args);
4005         }
4006 
4007         auto clientDescriptor = mActiveClientManager.get(cameraId);
4008         if (clientDescriptor != nullptr) {
4009             // log the current open session info
4010             dumpOpenSessionClientLogs(fd, args, cameraId);
4011         } else {
4012             dumpClosedSessionClientLogs(fd, cameraId);
4013         }
4014 
4015     }
4016 
4017     if (stateLocked) mCameraStatesLock.unlock();
4018 
4019     if (locked) mServiceLock.unlock();
4020 
4021     mCameraProviderManager->dump(fd, args);
4022 
4023     dprintf(fd, "\n== Vendor tags: ==\n\n");
4024 
4025     sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
4026     if (desc == NULL) {
4027         sp<VendorTagDescriptorCache> cache =
4028                 VendorTagDescriptorCache::getGlobalVendorTagCache();
4029         if (cache == NULL) {
4030             dprintf(fd, "No vendor tags.\n");
4031         } else {
4032             cache->dump(fd, /*verbosity*/2, /*indentation*/2);
4033         }
4034     } else {
4035         desc->dump(fd, /*verbosity*/2, /*indentation*/2);
4036     }
4037 
4038     // Dump camera traces if there were any
4039     dprintf(fd, "\n");
4040     camera3::CameraTraces::dump(fd, args);
4041 
4042     // Process dump arguments, if any
4043     int n = args.size();
4044     String16 verboseOption("-v");
4045     String16 unreachableOption("--unreachable");
4046     for (int i = 0; i < n; i++) {
4047         if (args[i] == verboseOption) {
4048             // change logging level
4049             if (i + 1 >= n) continue;
4050             String8 levelStr(args[i+1]);
4051             int level = atoi(levelStr.string());
4052             dprintf(fd, "\nSetting log level to %d.\n", level);
4053             setLogLevel(level);
4054         } else if (args[i] == unreachableOption) {
4055             // Dump memory analysis
4056             // TODO - should limit be an argument parameter?
4057             UnreachableMemoryInfo info;
4058             bool success = GetUnreachableMemory(info, /*limit*/ 10000);
4059             if (!success) {
4060                 dprintf(fd, "\n== Unable to dump unreachable memory. "
4061                         "Try disabling SELinux enforcement. ==\n");
4062             } else {
4063                 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
4064                 std::string s = info.ToString(/*log_contents*/ true);
4065                 write(fd, s.c_str(), s.size());
4066             }
4067         }
4068     }
4069 
4070     bool serviceLocked = tryLock(mServiceLock);
4071 
4072     // Dump info from previous open sessions.
4073     // Reposition the offset to beginning of the file before reading
4074 
4075     if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
4076         dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
4077         ssize_t size_read;
4078         char buf[4096];
4079         while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
4080             // Read data from file to a small buffer and write it to fd.
4081             write(fd, buf, size_read);
4082             if (size_read == -1) {
4083                 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
4084                 break;
4085             }
4086         }
4087         dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
4088     } else {
4089         ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
4090     }
4091 
4092     if (serviceLocked) mServiceLock.unlock();
4093     return NO_ERROR;
4094 }
4095 
dumpOpenSessionClientLogs(int fd,const Vector<String16> & args,const String8 & cameraId)4096 void CameraService::dumpOpenSessionClientLogs(int fd,
4097         const Vector<String16>& args, const String8& cameraId) {
4098     auto clientDescriptor = mActiveClientManager.get(cameraId);
4099     dprintf(fd, "  Device %s is open. Client instance dump:\n",
4100         cameraId.string());
4101     dprintf(fd, "    Client priority score: %d state: %d\n",
4102         clientDescriptor->getPriority().getScore(),
4103         clientDescriptor->getPriority().getState());
4104     dprintf(fd, "    Client PID: %d\n", clientDescriptor->getOwnerId());
4105 
4106     auto client = clientDescriptor->getValue();
4107     dprintf(fd, "    Client package: %s\n",
4108         String8(client->getPackageName()).string());
4109 
4110     client->dumpClient(fd, args);
4111 }
4112 
dumpClosedSessionClientLogs(int fd,const String8 & cameraId)4113 void CameraService::dumpClosedSessionClientLogs(int fd, const String8& cameraId) {
4114     dprintf(fd, "  Device %s is closed, no client instance\n",
4115                     cameraId.string());
4116 }
4117 
dumpEventLog(int fd)4118 void CameraService::dumpEventLog(int fd) {
4119     dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
4120 
4121     Mutex::Autolock l(mLogLock);
4122     for (const auto& msg : mEventLog) {
4123         dprintf(fd, "  %s\n", msg.string());
4124     }
4125 
4126     if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
4127         dprintf(fd, "  ...\n");
4128     } else if (mEventLog.size() == 0) {
4129         dprintf(fd, "  [no events yet]\n");
4130     }
4131     dprintf(fd, "\n");
4132 }
4133 
handleTorchClientBinderDied(const wp<IBinder> & who)4134 void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
4135     Mutex::Autolock al(mTorchClientMapMutex);
4136     for (size_t i = 0; i < mTorchClientMap.size(); i++) {
4137         if (mTorchClientMap[i] == who) {
4138             // turn off the torch mode that was turned on by dead client
4139             String8 cameraId = mTorchClientMap.keyAt(i);
4140             status_t res = mFlashlight->setTorchMode(cameraId, false);
4141             if (res) {
4142                 ALOGE("%s: torch client died but couldn't turn off torch: "
4143                     "%s (%d)", __FUNCTION__, strerror(-res), res);
4144                 return;
4145             }
4146             mTorchClientMap.removeItemsAt(i);
4147             break;
4148         }
4149     }
4150 }
4151 
binderDied(const wp<IBinder> & who)4152 /*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
4153 
4154     /**
4155       * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
4156       * binder driver
4157       */
4158     // PID here is approximate and can be wrong.
4159     logClientDied(CameraThreadState::getCallingPid(), String8("Binder died unexpectedly"));
4160 
4161     // check torch client
4162     handleTorchClientBinderDied(who);
4163 
4164     // check camera device client
4165     if(!evictClientIdByRemote(who)) {
4166         ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
4167         return;
4168     }
4169 
4170     ALOGE("%s: Java client's binder died, removing it from the list of active clients",
4171             __FUNCTION__);
4172 }
4173 
updateStatus(StatusInternal status,const String8 & cameraId)4174 void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
4175     updateStatus(status, cameraId, {});
4176 }
4177 
updateStatus(StatusInternal status,const String8 & cameraId,std::initializer_list<StatusInternal> rejectSourceStates)4178 void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
4179         std::initializer_list<StatusInternal> rejectSourceStates) {
4180     // Do not lock mServiceLock here or can get into a deadlock from
4181     // connect() -> disconnect -> updateStatus
4182 
4183     auto state = getCameraState(cameraId);
4184 
4185     if (state == nullptr) {
4186         ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
4187                 cameraId.string());
4188         return;
4189     }
4190 
4191     // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
4192     SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
4193     if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
4194         ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
4195         return;
4196     }
4197 
4198     // Collect the logical cameras without holding mStatusLock in updateStatus
4199     // as that can lead to a deadlock(b/162192331).
4200     auto logicalCameraIds = getLogicalCameras(cameraId);
4201     // Update the status for this camera state, then send the onStatusChangedCallbacks to each
4202     // of the listeners with both the mStatusLock and mStatusListenerLock held
4203     state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
4204                         &logicalCameraIds]
4205             (const String8& cameraId, StatusInternal status) {
4206 
4207             if (status != StatusInternal::ENUMERATING) {
4208                 // Update torch status if it has a flash unit.
4209                 Mutex::Autolock al(mTorchStatusMutex);
4210                 TorchModeStatus torchStatus;
4211                 if (getTorchStatusLocked(cameraId, &torchStatus) !=
4212                         NAME_NOT_FOUND) {
4213                     TorchModeStatus newTorchStatus =
4214                             status == StatusInternal::PRESENT ?
4215                             TorchModeStatus::AVAILABLE_OFF :
4216                             TorchModeStatus::NOT_AVAILABLE;
4217                     if (torchStatus != newTorchStatus) {
4218                         onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
4219                     }
4220                 }
4221             }
4222 
4223             Mutex::Autolock lock(mStatusListenerLock);
4224             notifyPhysicalCameraStatusLocked(mapToInterface(status), String16(cameraId),
4225                     logicalCameraIds, deviceKind);
4226 
4227             for (auto& listener : mListenerList) {
4228                 bool isVendorListener = listener->isVendorListener();
4229                 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
4230                         listener->getListenerPid(), listener->getListenerUid()) ||
4231                         isVendorListener) {
4232                     ALOGV("Skipping discovery callback for system-only camera device %s",
4233                             cameraId.c_str());
4234                     continue;
4235                 }
4236                 listener->getListener()->onStatusChanged(mapToInterface(status),
4237                         String16(cameraId));
4238             }
4239         });
4240 }
4241 
updateOpenCloseStatus(const String8 & cameraId,bool open,const String16 & clientPackageName)4242 void CameraService::updateOpenCloseStatus(const String8& cameraId, bool open,
4243         const String16& clientPackageName) {
4244     Mutex::Autolock lock(mStatusListenerLock);
4245 
4246     for (const auto& it : mListenerList) {
4247         if (!it->isOpenCloseCallbackAllowed()) {
4248             continue;
4249         }
4250 
4251         binder::Status ret;
4252         String16 cameraId64(cameraId);
4253         if (open) {
4254             ret = it->getListener()->onCameraOpened(cameraId64, clientPackageName);
4255         } else {
4256             ret = it->getListener()->onCameraClosed(cameraId64);
4257         }
4258         if (!ret.isOk()) {
4259             ALOGE("%s: Failed to trigger onCameraOpened/onCameraClosed callback: %d", __FUNCTION__,
4260                     ret.exceptionCode());
4261         }
4262     }
4263 }
4264 
4265 template<class Func>
updateStatus(StatusInternal status,const String8 & cameraId,std::initializer_list<StatusInternal> rejectSourceStates,Func onStatusUpdatedLocked)4266 void CameraService::CameraState::updateStatus(StatusInternal status,
4267         const String8& cameraId,
4268         std::initializer_list<StatusInternal> rejectSourceStates,
4269         Func onStatusUpdatedLocked) {
4270     Mutex::Autolock lock(mStatusLock);
4271     StatusInternal oldStatus = mStatus;
4272     mStatus = status;
4273 
4274     if (oldStatus == status) {
4275         return;
4276     }
4277 
4278     ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
4279             cameraId.string(), oldStatus, status);
4280 
4281     if (oldStatus == StatusInternal::NOT_PRESENT &&
4282             (status != StatusInternal::PRESENT &&
4283              status != StatusInternal::ENUMERATING)) {
4284 
4285         ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
4286                 __FUNCTION__);
4287         mStatus = oldStatus;
4288         return;
4289     }
4290 
4291     /**
4292      * Sometimes we want to conditionally do a transition.
4293      * For example if a client disconnects, we want to go to PRESENT
4294      * only if we weren't already in NOT_PRESENT or ENUMERATING.
4295      */
4296     for (auto& rejectStatus : rejectSourceStates) {
4297         if (oldStatus == rejectStatus) {
4298             ALOGV("%s: Rejecting status transition for Camera ID %s,  since the source "
4299                     "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
4300             mStatus = oldStatus;
4301             return;
4302         }
4303     }
4304 
4305     onStatusUpdatedLocked(cameraId, status);
4306 }
4307 
getTorchStatusLocked(const String8 & cameraId,TorchModeStatus * status) const4308 status_t CameraService::getTorchStatusLocked(
4309         const String8& cameraId,
4310         TorchModeStatus *status) const {
4311     if (!status) {
4312         return BAD_VALUE;
4313     }
4314     ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
4315     if (index == NAME_NOT_FOUND) {
4316         // invalid camera ID or the camera doesn't have a flash unit
4317         return NAME_NOT_FOUND;
4318     }
4319 
4320     *status = mTorchStatusMap.valueAt(index);
4321     return OK;
4322 }
4323 
setTorchStatusLocked(const String8 & cameraId,TorchModeStatus status)4324 status_t CameraService::setTorchStatusLocked(const String8& cameraId,
4325         TorchModeStatus status) {
4326     ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
4327     if (index == NAME_NOT_FOUND) {
4328         return BAD_VALUE;
4329     }
4330     mTorchStatusMap.editValueAt(index) = status;
4331 
4332     return OK;
4333 }
4334 
getLogicalCameras(const String8 & physicalCameraId)4335 std::list<String16> CameraService::getLogicalCameras(
4336         const String8& physicalCameraId) {
4337     std::list<String16> retList;
4338     Mutex::Autolock lock(mCameraStatesLock);
4339     for (const auto& state : mCameraStates) {
4340         std::vector<std::string> physicalCameraIds;
4341         if (!mCameraProviderManager->isLogicalCamera(state.first.c_str(), &physicalCameraIds)) {
4342             // This is not a logical multi-camera.
4343             continue;
4344         }
4345         if (std::find(physicalCameraIds.begin(), physicalCameraIds.end(), physicalCameraId.c_str())
4346                 == physicalCameraIds.end()) {
4347             // cameraId is not a physical camera of this logical multi-camera.
4348             continue;
4349         }
4350 
4351         retList.emplace_back(String16(state.first));
4352     }
4353     return retList;
4354 }
4355 
notifyPhysicalCameraStatusLocked(int32_t status,const String16 & physicalCameraId,const std::list<String16> & logicalCameraIds,SystemCameraKind deviceKind)4356 void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
4357         const String16& physicalCameraId, const std::list<String16>& logicalCameraIds,
4358         SystemCameraKind deviceKind) {
4359     // mStatusListenerLock is expected to be locked
4360     for (const auto& logicalCameraId : logicalCameraIds) {
4361         for (auto& listener : mListenerList) {
4362             // Note: we check only the deviceKind of the physical camera id
4363             // since, logical camera ids and their physical camera ids are
4364             // guaranteed to have the same system camera kind.
4365             if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
4366                     listener->getListenerPid(), listener->getListenerUid())) {
4367                 ALOGV("Skipping discovery callback for system-only camera device %s",
4368                         String8(physicalCameraId).c_str());
4369                 continue;
4370             }
4371             listener->getListener()->onPhysicalCameraStatusChanged(status,
4372                     logicalCameraId, physicalCameraId);
4373         }
4374     }
4375 }
4376 
4377 
blockClientsForUid(uid_t uid)4378 void CameraService::blockClientsForUid(uid_t uid) {
4379     const auto clients = mActiveClientManager.getAll();
4380     for (auto& current : clients) {
4381         if (current != nullptr) {
4382             const auto basicClient = current->getValue();
4383             if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
4384                 basicClient->block();
4385             }
4386         }
4387     }
4388 }
4389 
blockAllClients()4390 void CameraService::blockAllClients() {
4391     const auto clients = mActiveClientManager.getAll();
4392     for (auto& current : clients) {
4393         if (current != nullptr) {
4394             const auto basicClient = current->getValue();
4395             if (basicClient.get() != nullptr) {
4396                 basicClient->block();
4397             }
4398         }
4399     }
4400 }
4401 
4402 // NOTE: This is a remote API - make sure all args are validated
shellCommand(int in,int out,int err,const Vector<String16> & args)4403 status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
4404     if (!checkCallingPermission(sManageCameraPermission, nullptr, nullptr)) {
4405         return PERMISSION_DENIED;
4406     }
4407     if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
4408         return BAD_VALUE;
4409     }
4410     if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
4411         return handleSetUidState(args, err);
4412     } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
4413         return handleResetUidState(args, err);
4414     } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
4415         return handleGetUidState(args, out, err);
4416     } else if (args.size() >= 2 && args[0] == String16("set-rotate-and-crop")) {
4417         return handleSetRotateAndCrop(args);
4418     } else if (args.size() >= 1 && args[0] == String16("get-rotate-and-crop")) {
4419         return handleGetRotateAndCrop(out);
4420     } else if (args.size() >= 2 && args[0] == String16("set-image-dump-mask")) {
4421         return handleSetImageDumpMask(args);
4422     } else if (args.size() >= 1 && args[0] == String16("get-image-dump-mask")) {
4423         return handleGetImageDumpMask(out);
4424     } else if (args.size() >= 2 && args[0] == String16("set-camera-mute")) {
4425         return handleSetCameraMute(args);
4426     } else if (args.size() == 1 && args[0] == String16("help")) {
4427         printHelp(out);
4428         return NO_ERROR;
4429     }
4430     printHelp(err);
4431     return BAD_VALUE;
4432 }
4433 
handleSetUidState(const Vector<String16> & args,int err)4434 status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
4435     String16 packageName = args[1];
4436 
4437     bool active = false;
4438     if (args[2] == String16("active")) {
4439         active = true;
4440     } else if ((args[2] != String16("idle"))) {
4441         ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
4442         return BAD_VALUE;
4443     }
4444 
4445     int userId = 0;
4446     if (args.size() >= 5 && args[3] == String16("--user")) {
4447         userId = atoi(String8(args[4]));
4448     }
4449 
4450     uid_t uid;
4451     if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
4452         return BAD_VALUE;
4453     }
4454 
4455     mUidPolicy->addOverrideUid(uid, packageName, active);
4456     return NO_ERROR;
4457 }
4458 
handleResetUidState(const Vector<String16> & args,int err)4459 status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
4460     String16 packageName = args[1];
4461 
4462     int userId = 0;
4463     if (args.size() >= 4 && args[2] == String16("--user")) {
4464         userId = atoi(String8(args[3]));
4465     }
4466 
4467     uid_t uid;
4468     if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
4469         return BAD_VALUE;
4470     }
4471 
4472     mUidPolicy->removeOverrideUid(uid, packageName);
4473     return NO_ERROR;
4474 }
4475 
handleGetUidState(const Vector<String16> & args,int out,int err)4476 status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
4477     String16 packageName = args[1];
4478 
4479     int userId = 0;
4480     if (args.size() >= 4 && args[2] == String16("--user")) {
4481         userId = atoi(String8(args[3]));
4482     }
4483 
4484     uid_t uid;
4485     if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
4486         return BAD_VALUE;
4487     }
4488 
4489     if (mUidPolicy->isUidActive(uid, packageName)) {
4490         return dprintf(out, "active\n");
4491     } else {
4492         return dprintf(out, "idle\n");
4493     }
4494 }
4495 
handleSetRotateAndCrop(const Vector<String16> & args)4496 status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
4497     int rotateValue = atoi(String8(args[1]));
4498     if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
4499             rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
4500     Mutex::Autolock lock(mServiceLock);
4501 
4502     mOverrideRotateAndCropMode = rotateValue;
4503 
4504     if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
4505 
4506     const auto clients = mActiveClientManager.getAll();
4507     for (auto& current : clients) {
4508         if (current != nullptr) {
4509             const auto basicClient = current->getValue();
4510             if (basicClient.get() != nullptr) {
4511                 basicClient->setRotateAndCropOverride(rotateValue);
4512             }
4513         }
4514     }
4515 
4516     return OK;
4517 }
4518 
handleGetRotateAndCrop(int out)4519 status_t CameraService::handleGetRotateAndCrop(int out) {
4520     Mutex::Autolock lock(mServiceLock);
4521 
4522     return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
4523 }
4524 
handleSetImageDumpMask(const Vector<String16> & args)4525 status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
4526     char *endPtr;
4527     errno = 0;
4528     String8 maskString8 = String8(args[1]);
4529     long maskValue = strtol(maskString8.c_str(), &endPtr, 10);
4530 
4531     if (errno != 0) return BAD_VALUE;
4532     if (endPtr != maskString8.c_str() + maskString8.size()) return BAD_VALUE;
4533     if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
4534 
4535     Mutex::Autolock lock(mServiceLock);
4536 
4537     mImageDumpMask = maskValue;
4538 
4539     return OK;
4540 }
4541 
handleGetImageDumpMask(int out)4542 status_t CameraService::handleGetImageDumpMask(int out) {
4543     Mutex::Autolock lock(mServiceLock);
4544 
4545     return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
4546 }
4547 
handleSetCameraMute(const Vector<String16> & args)4548 status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
4549     int muteValue = strtol(String8(args[1]), nullptr, 10);
4550     if (errno != 0) return BAD_VALUE;
4551 
4552     if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
4553     Mutex::Autolock lock(mServiceLock);
4554 
4555     mOverrideCameraMuteMode = (muteValue == 1);
4556 
4557     const auto clients = mActiveClientManager.getAll();
4558     for (auto& current : clients) {
4559         if (current != nullptr) {
4560             const auto basicClient = current->getValue();
4561             if (basicClient.get() != nullptr) {
4562                 if (basicClient->supportsCameraMute()) {
4563                     basicClient->setCameraMute(mOverrideCameraMuteMode);
4564                 }
4565             }
4566         }
4567     }
4568 
4569     return OK;
4570 }
4571 
printHelp(int out)4572 status_t CameraService::printHelp(int out) {
4573     return dprintf(out, "Camera service commands:\n"
4574         "  get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
4575         "  set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
4576         "  reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
4577         "  set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
4578         "      Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
4579         "  get-rotate-and-crop returns the current override rotate-and-crop value\n"
4580         "  set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
4581         "      Valid values 0=OFF, 1=ON for JPEG\n"
4582         "  get-image-dump-mask returns the current image-dump-mask value\n"
4583         "  set-camera-mute <0/1> enable or disable camera muting\n"
4584         "  help print this message\n");
4585 }
4586 
updateAudioRestriction()4587 int32_t CameraService::updateAudioRestriction() {
4588     Mutex::Autolock lock(mServiceLock);
4589     return updateAudioRestrictionLocked();
4590 }
4591 
updateAudioRestrictionLocked()4592 int32_t CameraService::updateAudioRestrictionLocked() {
4593     int32_t mode = 0;
4594     // iterate through all active client
4595     for (const auto& i : mActiveClientManager.getAll()) {
4596         const auto clientSp = i->getValue();
4597         mode |= clientSp->getAudioRestriction();
4598     }
4599 
4600     bool modeChanged = (mAudioRestriction != mode);
4601     mAudioRestriction = mode;
4602     if (modeChanged) {
4603         mAppOps.setCameraAudioRestriction(mode);
4604     }
4605     return mode;
4606 }
4607 
stopInjectionImpl()4608 void CameraService::stopInjectionImpl() {
4609     mInjectionStatusListener->removeListener();
4610 
4611     // TODO: Implement the stop injection function.
4612 }
4613 
4614 }; // namespace android
4615