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