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