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 <binder/AppOpsManager.h>
37 #include <binder/IPCThreadState.h>
38 #include <binder/IServiceManager.h>
39 #include <binder/MemoryBase.h>
40 #include <binder/MemoryHeapBase.h>
41 #include <binder/ProcessInfoService.h>
42 #include <cutils/atomic.h>
43 #include <cutils/properties.h>
44 #include <gui/Surface.h>
45 #include <hardware/hardware.h>
46 #include <memunreachable/memunreachable.h>
47 #include <media/AudioSystem.h>
48 #include <media/IMediaHTTPService.h>
49 #include <media/mediaplayer.h>
50 #include <mediautils/BatteryNotifier.h>
51 #include <utils/Errors.h>
52 #include <utils/Log.h>
53 #include <utils/String16.h>
54 #include <utils/Trace.h>
55 #include <private/android_filesystem_config.h>
56 #include <system/camera_vendor_tags.h>
57 #include <system/camera_metadata.h>
58
59 #include <system/camera.h>
60
61 #include "CameraService.h"
62 #include "api1/CameraClient.h"
63 #include "api1/Camera2Client.h"
64 #include "api2/CameraDeviceClient.h"
65 #include "utils/CameraTraces.h"
66
67 namespace {
68 const char* kPermissionServiceName = "permission";
69 }; // namespace anonymous
70
71 namespace android {
72
73 using binder::Status;
74 using hardware::ICamera;
75 using hardware::ICameraClient;
76 using hardware::ICameraServiceProxy;
77 using hardware::ICameraServiceListener;
78 using hardware::camera::common::V1_0::CameraDeviceStatus;
79 using hardware::camera::common::V1_0::TorchModeStatus;
80
81 // ----------------------------------------------------------------------------
82 // Logging support -- this is for debugging only
83 // Use "adb shell dumpsys media.camera -v 1" to change it.
84 volatile int32_t gLogLevel = 0;
85
86 #define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
87 #define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
88
setLogLevel(int level)89 static void setLogLevel(int level) {
90 android_atomic_write(level, &gLogLevel);
91 }
92
93 // Convenience methods for constructing binder::Status objects for error returns
94
95 #define STATUS_ERROR(errorCode, errorString) \
96 binder::Status::fromServiceSpecificError(errorCode, \
97 String8::format("%s:%d: %s", __FUNCTION__, __LINE__, errorString))
98
99 #define STATUS_ERROR_FMT(errorCode, errorString, ...) \
100 binder::Status::fromServiceSpecificError(errorCode, \
101 String8::format("%s:%d: " errorString, __FUNCTION__, __LINE__, \
102 __VA_ARGS__))
103
104 // ----------------------------------------------------------------------------
105
106 extern "C" {
camera_device_status_change(const struct camera_module_callbacks * callbacks,int camera_id,int new_status)107 static void camera_device_status_change(
108 const struct camera_module_callbacks* callbacks,
109 int camera_id,
110 int new_status) {
111 sp<CameraService> cs = const_cast<CameraService*>(
112 static_cast<const CameraService*>(callbacks));
113 String8 id = String8::format("%d", camera_id);
114
115 CameraDeviceStatus newStatus{CameraDeviceStatus::NOT_PRESENT};
116 switch (new_status) {
117 case CAMERA_DEVICE_STATUS_NOT_PRESENT:
118 newStatus = CameraDeviceStatus::NOT_PRESENT;
119 break;
120 case CAMERA_DEVICE_STATUS_PRESENT:
121 newStatus = CameraDeviceStatus::PRESENT;
122 break;
123 case CAMERA_DEVICE_STATUS_ENUMERATING:
124 newStatus = CameraDeviceStatus::ENUMERATING;
125 break;
126 default:
127 ALOGW("Unknown device status change to %d", new_status);
128 break;
129 }
130 cs->onDeviceStatusChanged(id, newStatus);
131 }
132
torch_mode_status_change(const struct camera_module_callbacks * callbacks,const char * camera_id,int new_status)133 static void torch_mode_status_change(
134 const struct camera_module_callbacks* callbacks,
135 const char* camera_id,
136 int new_status) {
137 if (!callbacks || !camera_id) {
138 ALOGE("%s invalid parameters. callbacks %p, camera_id %p", __FUNCTION__,
139 callbacks, camera_id);
140 }
141 sp<CameraService> cs = const_cast<CameraService*>(
142 static_cast<const CameraService*>(callbacks));
143
144 TorchModeStatus status;
145 switch (new_status) {
146 case TORCH_MODE_STATUS_NOT_AVAILABLE:
147 status = TorchModeStatus::NOT_AVAILABLE;
148 break;
149 case TORCH_MODE_STATUS_AVAILABLE_OFF:
150 status = TorchModeStatus::AVAILABLE_OFF;
151 break;
152 case TORCH_MODE_STATUS_AVAILABLE_ON:
153 status = TorchModeStatus::AVAILABLE_ON;
154 break;
155 default:
156 ALOGE("Unknown torch status %d", new_status);
157 return;
158 }
159
160 cs->onTorchStatusChanged(
161 String8(camera_id),
162 status);
163 }
164 } // extern "C"
165
166 // ----------------------------------------------------------------------------
167
CameraService()168 CameraService::CameraService() :
169 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
170 mNumberOfCameras(0), mNumberOfNormalCameras(0),
171 mSoundRef(0), mInitialized(false) {
172 ALOGI("CameraService started (pid=%d)", getpid());
173
174 this->camera_device_status_change = android::camera_device_status_change;
175 this->torch_mode_status_change = android::torch_mode_status_change;
176
177 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
178 }
179
onFirstRef()180 void CameraService::onFirstRef()
181 {
182 ALOGI("CameraService process starting");
183
184 BnCameraService::onFirstRef();
185
186 // Update battery life tracking if service is restarting
187 BatteryNotifier& notifier(BatteryNotifier::getInstance());
188 notifier.noteResetCamera();
189 notifier.noteResetFlashlight();
190
191 status_t res = INVALID_OPERATION;
192
193 res = enumerateProviders();
194 if (res == OK) {
195 mInitialized = true;
196 }
197
198 CameraService::pingCameraServiceProxy();
199 }
200
enumerateProviders()201 status_t CameraService::enumerateProviders() {
202 status_t res;
203 Mutex::Autolock l(mServiceLock);
204
205 if (nullptr == mCameraProviderManager.get()) {
206 mCameraProviderManager = new CameraProviderManager();
207 res = mCameraProviderManager->initialize(this);
208 if (res != OK) {
209 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
210 __FUNCTION__, strerror(-res), res);
211 return res;
212 }
213 }
214
215 mNumberOfCameras = mCameraProviderManager->getCameraCount();
216 mNumberOfNormalCameras =
217 mCameraProviderManager->getAPI1CompatibleCameraCount();
218
219 // Setup vendor tags before we call get_camera_info the first time
220 // because HAL might need to setup static vendor keys in get_camera_info
221 // TODO: maybe put this into CameraProviderManager::initialize()?
222 mCameraProviderManager->setUpVendorTags();
223
224 if (nullptr == mFlashlight.get()) {
225 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
226 }
227
228 res = mFlashlight->findFlashUnits();
229 if (res != OK) {
230 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
231 }
232
233 for (auto& cameraId : mCameraProviderManager->getCameraDeviceIds()) {
234 String8 id8 = String8(cameraId.c_str());
235 bool cameraFound = false;
236 {
237
238 Mutex::Autolock lock(mCameraStatesLock);
239 auto iter = mCameraStates.find(id8);
240 if (iter != mCameraStates.end()) {
241 cameraFound = true;
242 }
243 }
244
245 if (!cameraFound) {
246 hardware::camera::common::V1_0::CameraResourceCost cost;
247 res = mCameraProviderManager->getResourceCost(cameraId, &cost);
248 if (res != OK) {
249 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
250 continue;
251 }
252 std::set<String8> conflicting;
253 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
254 conflicting.emplace(String8(cost.conflictingDevices[i].c_str()));
255 }
256
257 {
258 Mutex::Autolock lock(mCameraStatesLock);
259 mCameraStates.emplace(id8,
260 std::make_shared<CameraState>(id8, cost.resourceCost, conflicting));
261 }
262 }
263
264 onDeviceStatusChanged(id8, CameraDeviceStatus::PRESENT);
265
266 if (mFlashlight->hasFlashUnit(id8)) {
267 mTorchStatusMap.add(id8, TorchModeStatus::AVAILABLE_OFF);
268 }
269 }
270
271 return OK;
272 }
273
getCameraServiceProxy()274 sp<ICameraServiceProxy> CameraService::getCameraServiceProxy() {
275 sp<ICameraServiceProxy> proxyBinder = nullptr;
276 #ifndef __BRILLO__
277 sp<IServiceManager> sm = defaultServiceManager();
278 // Use checkService because cameraserver normally starts before the
279 // system server and the proxy service. So the long timeout that getService
280 // has before giving up is inappropriate.
281 sp<IBinder> binder = sm->checkService(String16("media.camera.proxy"));
282 if (binder != nullptr) {
283 proxyBinder = interface_cast<ICameraServiceProxy>(binder);
284 }
285 #endif
286 return proxyBinder;
287 }
288
pingCameraServiceProxy()289 void CameraService::pingCameraServiceProxy() {
290 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
291 if (proxyBinder == nullptr) return;
292 proxyBinder->pingForUserUpdate();
293 }
294
~CameraService()295 CameraService::~CameraService() {
296 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
297 }
298
onNewProviderRegistered()299 void CameraService::onNewProviderRegistered() {
300 enumerateProviders();
301 }
302
onDeviceStatusChanged(const String8 & id,CameraDeviceStatus newHalStatus)303 void CameraService::onDeviceStatusChanged(const String8& id,
304 CameraDeviceStatus newHalStatus) {
305 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
306 id.string(), newHalStatus);
307
308 StatusInternal newStatus = mapToInternal(newHalStatus);
309
310 std::shared_ptr<CameraState> state = getCameraState(id);
311
312 if (state == nullptr) {
313 if (newStatus == StatusInternal::PRESENT) {
314 ALOGW("%s: Unknown camera ID %s, probably newly registered?",
315 __FUNCTION__, id.string());
316 } else {
317 ALOGE("%s: Bad camera ID %s", __FUNCTION__, id.string());
318 }
319 return;
320 }
321
322 StatusInternal oldStatus = state->getStatus();
323
324 if (oldStatus == newStatus) {
325 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
326 return;
327 }
328
329 if (newStatus == StatusInternal::NOT_PRESENT) {
330 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
331 newStatus));
332 sp<BasicClient> clientToDisconnect;
333 {
334 // Don't do this in updateStatus to avoid deadlock over mServiceLock
335 Mutex::Autolock lock(mServiceLock);
336
337 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
338 // to this device until the status changes
339 updateStatus(StatusInternal::NOT_PRESENT, id);
340
341 // Remove cached shim parameters
342 state->setShimParams(CameraParameters());
343
344 // Remove the client from the list of active clients, if there is one
345 clientToDisconnect = removeClientLocked(id);
346 }
347
348 // Disconnect client
349 if (clientToDisconnect.get() != nullptr) {
350 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
351 __FUNCTION__, id.string());
352 // Notify the client of disconnection
353 clientToDisconnect->notifyError(
354 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
355 CaptureResultExtras{});
356 // Ensure not in binder RPC so client disconnect PID checks work correctly
357 LOG_ALWAYS_FATAL_IF(getCallingPid() != getpid(),
358 "onDeviceStatusChanged must be called from the camera service process!");
359 clientToDisconnect->disconnect();
360 }
361
362 } else {
363 if (oldStatus == StatusInternal::NOT_PRESENT) {
364 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
365 newStatus));
366 }
367 updateStatus(newStatus, id);
368 }
369
370 }
371
onTorchStatusChanged(const String8 & cameraId,TorchModeStatus newStatus)372 void CameraService::onTorchStatusChanged(const String8& cameraId,
373 TorchModeStatus newStatus) {
374 Mutex::Autolock al(mTorchStatusMutex);
375 onTorchStatusChangedLocked(cameraId, newStatus);
376 }
377
onTorchStatusChangedLocked(const String8 & cameraId,TorchModeStatus newStatus)378 void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
379 TorchModeStatus newStatus) {
380 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
381 __FUNCTION__, cameraId.string(), newStatus);
382
383 TorchModeStatus status;
384 status_t res = getTorchStatusLocked(cameraId, &status);
385 if (res) {
386 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
387 __FUNCTION__, cameraId.string(), strerror(-res), res);
388 return;
389 }
390 if (status == newStatus) {
391 return;
392 }
393
394 res = setTorchStatusLocked(cameraId, newStatus);
395 if (res) {
396 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
397 (uint32_t)newStatus, strerror(-res), res);
398 return;
399 }
400
401 {
402 // Update battery life logging for flashlight
403 Mutex::Autolock al(mTorchUidMapMutex);
404 auto iter = mTorchUidMap.find(cameraId);
405 if (iter != mTorchUidMap.end()) {
406 int oldUid = iter->second.second;
407 int newUid = iter->second.first;
408 BatteryNotifier& notifier(BatteryNotifier::getInstance());
409 if (oldUid != newUid) {
410 // If the UID has changed, log the status and update current UID in mTorchUidMap
411 if (status == TorchModeStatus::AVAILABLE_ON) {
412 notifier.noteFlashlightOff(cameraId, oldUid);
413 }
414 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
415 notifier.noteFlashlightOn(cameraId, newUid);
416 }
417 iter->second.second = newUid;
418 } else {
419 // If the UID has not changed, log the status
420 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
421 notifier.noteFlashlightOn(cameraId, oldUid);
422 } else {
423 notifier.noteFlashlightOff(cameraId, oldUid);
424 }
425 }
426 }
427 }
428
429 {
430 Mutex::Autolock lock(mStatusListenerLock);
431 for (auto& i : mListenerList) {
432 i->onTorchStatusChanged(mapToInterface(newStatus), String16{cameraId});
433 }
434 }
435 }
436
getNumberOfCameras(int32_t type,int32_t * numCameras)437 Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
438 ATRACE_CALL();
439 Mutex::Autolock l(mServiceLock);
440 switch (type) {
441 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
442 *numCameras = mNumberOfNormalCameras;
443 break;
444 case CAMERA_TYPE_ALL:
445 *numCameras = mNumberOfCameras;
446 break;
447 default:
448 ALOGW("%s: Unknown camera type %d",
449 __FUNCTION__, type);
450 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
451 "Unknown camera type %d", type);
452 }
453 return Status::ok();
454 }
455
getCameraInfo(int cameraId,CameraInfo * cameraInfo)456 Status CameraService::getCameraInfo(int cameraId,
457 CameraInfo* cameraInfo) {
458 ATRACE_CALL();
459 Mutex::Autolock l(mServiceLock);
460
461 if (!mInitialized) {
462 return STATUS_ERROR(ERROR_DISCONNECTED,
463 "Camera subsystem is not available");
464 }
465
466 if (cameraId < 0 || cameraId >= mNumberOfCameras) {
467 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
468 "CameraId is not valid");
469 }
470
471 Status ret = Status::ok();
472 status_t err = mCameraProviderManager->getCameraInfo(std::to_string(cameraId), cameraInfo);
473 if (err != OK) {
474 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
475 "Error retrieving camera info from device %d: %s (%d)", cameraId,
476 strerror(-err), err);
477 }
478
479 return ret;
480 }
481
cameraIdToInt(const String8 & cameraId)482 int CameraService::cameraIdToInt(const String8& cameraId) {
483 int id;
484 bool success = base::ParseInt(cameraId.string(), &id, 0);
485 if (!success) {
486 return -1;
487 }
488 return id;
489 }
490
getCameraCharacteristics(const String16 & cameraId,CameraMetadata * cameraInfo)491 Status CameraService::getCameraCharacteristics(const String16& cameraId,
492 CameraMetadata* cameraInfo) {
493 ATRACE_CALL();
494 if (!cameraInfo) {
495 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
496 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
497 }
498
499 if (!mInitialized) {
500 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
501 return STATUS_ERROR(ERROR_DISCONNECTED,
502 "Camera subsystem is not available");;
503 }
504
505 Status ret{};
506
507 status_t res = mCameraProviderManager->getCameraCharacteristics(
508 String8(cameraId).string(), cameraInfo);
509 if (res != OK) {
510 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
511 "characteristics for device %s: %s (%d)", String8(cameraId).string(),
512 strerror(-res), res);
513 }
514
515 return ret;
516 }
517
getCallingPid()518 int CameraService::getCallingPid() {
519 return IPCThreadState::self()->getCallingPid();
520 }
521
getCallingUid()522 int CameraService::getCallingUid() {
523 return IPCThreadState::self()->getCallingUid();
524 }
525
getFormattedCurrentTime()526 String8 CameraService::getFormattedCurrentTime() {
527 time_t now = time(nullptr);
528 char formattedTime[64];
529 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
530 return String8(formattedTime);
531 }
532
getCameraVendorTagDescriptor(hardware::camera2::params::VendorTagDescriptor * desc)533 Status CameraService::getCameraVendorTagDescriptor(
534 /*out*/
535 hardware::camera2::params::VendorTagDescriptor* desc) {
536 ATRACE_CALL();
537 if (!mInitialized) {
538 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
539 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
540 }
541 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
542 if (globalDescriptor != nullptr) {
543 *desc = *(globalDescriptor.get());
544 }
545 return Status::ok();
546 }
547
getCameraVendorTagCache(hardware::camera2::params::VendorTagDescriptorCache * cache)548 Status CameraService::getCameraVendorTagCache(
549 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
550 ATRACE_CALL();
551 if (!mInitialized) {
552 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
553 return STATUS_ERROR(ERROR_DISCONNECTED,
554 "Camera subsystem not available");
555 }
556 sp<VendorTagDescriptorCache> globalCache =
557 VendorTagDescriptorCache::getGlobalVendorTagCache();
558 if (globalCache != nullptr) {
559 *cache = *(globalCache.get());
560 }
561 return Status::ok();
562 }
563
getDeviceVersion(const String8 & cameraId,int * facing)564 int CameraService::getDeviceVersion(const String8& cameraId, int* facing) {
565 ATRACE_CALL();
566
567 int deviceVersion = 0;
568
569 status_t res;
570 hardware::hidl_version maxVersion{0,0};
571 res = mCameraProviderManager->getHighestSupportedVersion(cameraId.string(),
572 &maxVersion);
573 if (res != OK) return -1;
574 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
575
576 hardware::CameraInfo info;
577 if (facing) {
578 res = mCameraProviderManager->getCameraInfo(cameraId.string(), &info);
579 if (res != OK) return -1;
580 *facing = info.facing;
581 }
582
583 return deviceVersion;
584 }
585
filterGetInfoErrorCode(status_t err)586 Status CameraService::filterGetInfoErrorCode(status_t err) {
587 switch(err) {
588 case NO_ERROR:
589 return Status::ok();
590 case BAD_VALUE:
591 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
592 "CameraId is not valid for HAL module");
593 case NO_INIT:
594 return STATUS_ERROR(ERROR_DISCONNECTED,
595 "Camera device not available");
596 default:
597 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
598 "Camera HAL encountered error %d: %s",
599 err, strerror(-err));
600 }
601 }
602
makeClient(const sp<CameraService> & cameraService,const sp<IInterface> & cameraCb,const String16 & packageName,const String8 & cameraId,int facing,int clientPid,uid_t clientUid,int servicePid,bool legacyMode,int halVersion,int deviceVersion,apiLevel effectiveApiLevel,sp<BasicClient> * client)603 Status CameraService::makeClient(const sp<CameraService>& cameraService,
604 const sp<IInterface>& cameraCb, const String16& packageName, const String8& cameraId,
605 int facing, int clientPid, uid_t clientUid, int servicePid, bool legacyMode,
606 int halVersion, int deviceVersion, apiLevel effectiveApiLevel,
607 /*out*/sp<BasicClient>* client) {
608
609 if (halVersion < 0 || halVersion == deviceVersion) {
610 // Default path: HAL version is unspecified by caller, create CameraClient
611 // based on device version reported by the HAL.
612 switch(deviceVersion) {
613 case CAMERA_DEVICE_API_VERSION_1_0:
614 if (effectiveApiLevel == API_1) { // Camera1 API route
615 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
616 *client = new CameraClient(cameraService, tmp, packageName, cameraIdToInt(cameraId),
617 facing, clientPid, clientUid, getpid(), legacyMode);
618 } else { // Camera2 API route
619 ALOGW("Camera using old HAL version: %d", deviceVersion);
620 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
621 "Camera device \"%s\" HAL version %d does not support camera2 API",
622 cameraId.string(), deviceVersion);
623 }
624 break;
625 case CAMERA_DEVICE_API_VERSION_3_0:
626 case CAMERA_DEVICE_API_VERSION_3_1:
627 case CAMERA_DEVICE_API_VERSION_3_2:
628 case CAMERA_DEVICE_API_VERSION_3_3:
629 case CAMERA_DEVICE_API_VERSION_3_4:
630 if (effectiveApiLevel == API_1) { // Camera1 API route
631 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
632 *client = new Camera2Client(cameraService, tmp, packageName, cameraIdToInt(cameraId),
633 facing, clientPid, clientUid, servicePid, legacyMode);
634 } else { // Camera2 API route
635 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
636 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
637 *client = new CameraDeviceClient(cameraService, tmp, packageName, cameraId,
638 facing, clientPid, clientUid, servicePid);
639 }
640 break;
641 default:
642 // Should not be reachable
643 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
644 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
645 "Camera device \"%s\" has unknown HAL version %d",
646 cameraId.string(), deviceVersion);
647 }
648 } else {
649 // A particular HAL version is requested by caller. Create CameraClient
650 // based on the requested HAL version.
651 if (deviceVersion > CAMERA_DEVICE_API_VERSION_1_0 &&
652 halVersion == CAMERA_DEVICE_API_VERSION_1_0) {
653 // Only support higher HAL version device opened as HAL1.0 device.
654 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
655 *client = new CameraClient(cameraService, tmp, packageName, cameraIdToInt(cameraId),
656 facing, clientPid, clientUid, servicePid, legacyMode);
657 } else {
658 // Other combinations (e.g. HAL3.x open as HAL2.x) are not supported yet.
659 ALOGE("Invalid camera HAL version %x: HAL %x device can only be"
660 " opened as HAL %x device", halVersion, deviceVersion,
661 CAMERA_DEVICE_API_VERSION_1_0);
662 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
663 "Camera device \"%s\" (HAL version %d) cannot be opened as HAL version %d",
664 cameraId.string(), deviceVersion, halVersion);
665 }
666 }
667 return Status::ok();
668 }
669
toString(std::set<userid_t> intSet)670 String8 CameraService::toString(std::set<userid_t> intSet) {
671 String8 s("");
672 bool first = true;
673 for (userid_t i : intSet) {
674 if (first) {
675 s.appendFormat("%d", i);
676 first = false;
677 } else {
678 s.appendFormat(", %d", i);
679 }
680 }
681 return s;
682 }
683
mapToInterface(TorchModeStatus status)684 int32_t CameraService::mapToInterface(TorchModeStatus status) {
685 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
686 switch (status) {
687 case TorchModeStatus::NOT_AVAILABLE:
688 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
689 break;
690 case TorchModeStatus::AVAILABLE_OFF:
691 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
692 break;
693 case TorchModeStatus::AVAILABLE_ON:
694 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
695 break;
696 default:
697 ALOGW("Unknown new flash status: %d", status);
698 }
699 return serviceStatus;
700 }
701
mapToInternal(CameraDeviceStatus status)702 CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
703 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
704 switch (status) {
705 case CameraDeviceStatus::NOT_PRESENT:
706 serviceStatus = StatusInternal::NOT_PRESENT;
707 break;
708 case CameraDeviceStatus::PRESENT:
709 serviceStatus = StatusInternal::PRESENT;
710 break;
711 case CameraDeviceStatus::ENUMERATING:
712 serviceStatus = StatusInternal::ENUMERATING;
713 break;
714 default:
715 ALOGW("Unknown new HAL device status: %d", status);
716 }
717 return serviceStatus;
718 }
719
mapToInterface(StatusInternal status)720 int32_t CameraService::mapToInterface(StatusInternal status) {
721 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
722 switch (status) {
723 case StatusInternal::NOT_PRESENT:
724 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
725 break;
726 case StatusInternal::PRESENT:
727 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
728 break;
729 case StatusInternal::ENUMERATING:
730 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
731 break;
732 case StatusInternal::NOT_AVAILABLE:
733 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
734 break;
735 case StatusInternal::UNKNOWN:
736 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
737 break;
738 default:
739 ALOGW("Unknown new internal device status: %d", status);
740 }
741 return serviceStatus;
742 }
743
initializeShimMetadata(int cameraId)744 Status CameraService::initializeShimMetadata(int cameraId) {
745 int uid = getCallingUid();
746
747 String16 internalPackageName("cameraserver");
748 String8 id = String8::format("%d", cameraId);
749 Status ret = Status::ok();
750 sp<Client> tmp = nullptr;
751 if (!(ret = connectHelper<ICameraClient,Client>(
752 sp<ICameraClient>{nullptr}, id, static_cast<int>(CAMERA_HAL_API_VERSION_UNSPECIFIED),
753 internalPackageName, uid, USE_CALLING_PID,
754 API_1, /*legacyMode*/ false, /*shimUpdateOnly*/ true,
755 /*out*/ tmp)
756 ).isOk()) {
757 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
758 }
759 return ret;
760 }
761
getLegacyParametersLazy(int cameraId,CameraParameters * parameters)762 Status CameraService::getLegacyParametersLazy(int cameraId,
763 /*out*/
764 CameraParameters* parameters) {
765
766 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
767
768 Status ret = Status::ok();
769
770 if (parameters == NULL) {
771 ALOGE("%s: parameters must not be null", __FUNCTION__);
772 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
773 }
774
775 String8 id = String8::format("%d", cameraId);
776
777 // Check if we already have parameters
778 {
779 // Scope for service lock
780 Mutex::Autolock lock(mServiceLock);
781 auto cameraState = getCameraState(id);
782 if (cameraState == nullptr) {
783 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
784 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
785 "Invalid camera ID: %s", id.string());
786 }
787 CameraParameters p = cameraState->getShimParams();
788 if (!p.isEmpty()) {
789 *parameters = p;
790 return ret;
791 }
792 }
793
794 int64_t token = IPCThreadState::self()->clearCallingIdentity();
795 ret = initializeShimMetadata(cameraId);
796 IPCThreadState::self()->restoreCallingIdentity(token);
797 if (!ret.isOk()) {
798 // Error already logged by callee
799 return ret;
800 }
801
802 // Check for parameters again
803 {
804 // Scope for service lock
805 Mutex::Autolock lock(mServiceLock);
806 auto cameraState = getCameraState(id);
807 if (cameraState == nullptr) {
808 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
809 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
810 "Invalid camera ID: %s", id.string());
811 }
812 CameraParameters p = cameraState->getShimParams();
813 if (!p.isEmpty()) {
814 *parameters = p;
815 return ret;
816 }
817 }
818
819 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
820 __FUNCTION__);
821 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
822 }
823
824 // Can camera service trust the caller based on the calling UID?
isTrustedCallingUid(uid_t uid)825 static bool isTrustedCallingUid(uid_t uid) {
826 switch (uid) {
827 case AID_MEDIA: // mediaserver
828 case AID_CAMERASERVER: // cameraserver
829 case AID_RADIO: // telephony
830 return true;
831 default:
832 return false;
833 }
834 }
835
validateConnectLocked(const String8 & cameraId,const String8 & clientName8,int & clientUid,int & clientPid,int & originalClientPid) const836 Status CameraService::validateConnectLocked(const String8& cameraId,
837 const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
838 /*out*/int& originalClientPid) const {
839
840 #ifdef __BRILLO__
841 UNUSED(clientName8);
842 UNUSED(clientUid);
843 UNUSED(clientPid);
844 UNUSED(originalClientPid);
845 #else
846 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
847 originalClientPid);
848 if (!allowed.isOk()) {
849 return allowed;
850 }
851 #endif // __BRILLO__
852
853 int callingPid = getCallingPid();
854
855 if (!mInitialized) {
856 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
857 callingPid);
858 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
859 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
860 }
861
862 if (getCameraState(cameraId) == nullptr) {
863 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
864 cameraId.string());
865 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
866 "No camera device with ID \"%s\" available", cameraId.string());
867 }
868
869 status_t err = checkIfDeviceIsUsable(cameraId);
870 if (err != NO_ERROR) {
871 switch(err) {
872 case -ENODEV:
873 case -EBUSY:
874 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
875 "No camera device with ID \"%s\" currently available", cameraId.string());
876 default:
877 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
878 "Unknown error connecting to ID \"%s\"", cameraId.string());
879 }
880 }
881 return Status::ok();
882 }
883
validateClientPermissionsLocked(const String8 & cameraId,const String8 & clientName8,int & clientUid,int & clientPid,int & originalClientPid) const884 Status CameraService::validateClientPermissionsLocked(const String8& cameraId,
885 const String8& clientName8, int& clientUid, int& clientPid,
886 /*out*/int& originalClientPid) const {
887 int callingPid = getCallingPid();
888 int callingUid = getCallingUid();
889
890 // Check if we can trust clientUid
891 if (clientUid == USE_CALLING_UID) {
892 clientUid = callingUid;
893 } else if (!isTrustedCallingUid(callingUid)) {
894 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
895 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
896 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
897 "Untrusted caller (calling PID %d, UID %d) trying to "
898 "forward camera access to camera %s for client %s (PID %d, UID %d)",
899 callingPid, callingUid, cameraId.string(),
900 clientName8.string(), clientUid, clientPid);
901 }
902
903 // Check if we can trust clientPid
904 if (clientPid == USE_CALLING_PID) {
905 clientPid = callingPid;
906 } else if (!isTrustedCallingUid(callingUid)) {
907 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
908 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
909 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
910 "Untrusted caller (calling PID %d, UID %d) trying to "
911 "forward camera access to camera %s for client %s (PID %d, UID %d)",
912 callingPid, callingUid, cameraId.string(),
913 clientName8.string(), clientUid, clientPid);
914 }
915
916 // If it's not calling from cameraserver, check the permission.
917 if (callingPid != getpid() &&
918 !checkPermission(String16("android.permission.CAMERA"), clientPid, clientUid)) {
919 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
920 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
921 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
922 clientName8.string(), clientUid, clientPid, cameraId.string());
923 }
924
925 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
926 // connected to camera service directly.
927 originalClientPid = clientPid;
928 clientPid = callingPid;
929
930 userid_t clientUserId = multiuser_get_user_id(clientUid);
931
932 // Only allow clients who are being used by the current foreground device user, unless calling
933 // from our own process.
934 if (callingPid != getpid() && (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
935 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
936 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
937 toString(mAllowedUsers).string());
938 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
939 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
940 clientUserId, cameraId.string());
941 }
942
943 return Status::ok();
944 }
945
checkIfDeviceIsUsable(const String8 & cameraId) const946 status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
947 auto cameraState = getCameraState(cameraId);
948 int callingPid = getCallingPid();
949 if (cameraState == nullptr) {
950 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
951 cameraId.string());
952 return -ENODEV;
953 }
954
955 StatusInternal currentStatus = cameraState->getStatus();
956 if (currentStatus == StatusInternal::NOT_PRESENT) {
957 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
958 callingPid, cameraId.string());
959 return -ENODEV;
960 } else if (currentStatus == StatusInternal::ENUMERATING) {
961 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
962 callingPid, cameraId.string());
963 return -EBUSY;
964 }
965
966 return NO_ERROR;
967 }
968
finishConnectLocked(const sp<BasicClient> & client,const CameraService::DescriptorPtr & desc)969 void CameraService::finishConnectLocked(const sp<BasicClient>& client,
970 const CameraService::DescriptorPtr& desc) {
971
972 // Make a descriptor for the incoming client
973 auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
974 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
975
976 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
977 String8(client->getPackageName()));
978
979 if (evicted.size() > 0) {
980 // This should never happen - clients should already have been removed in disconnect
981 for (auto& i : evicted) {
982 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
983 __FUNCTION__, i->getKey().string());
984 }
985
986 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
987 __FUNCTION__);
988 }
989
990 // And register a death notification for the client callback. Do
991 // this last to avoid Binder policy where a nested Binder
992 // transaction might be pre-empted to service the client death
993 // notification if the client process dies before linkToDeath is
994 // invoked.
995 sp<IBinder> remoteCallback = client->getRemote();
996 if (remoteCallback != nullptr) {
997 remoteCallback->linkToDeath(this);
998 }
999 }
1000
handleEvictionsLocked(const String8 & cameraId,int clientPid,apiLevel effectiveApiLevel,const sp<IBinder> & remoteCallback,const String8 & packageName,sp<BasicClient> * client,std::shared_ptr<resource_policy::ClientDescriptor<String8,sp<BasicClient>>> * partial)1001 status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
1002 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
1003 /*out*/
1004 sp<BasicClient>* client,
1005 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
1006 ATRACE_CALL();
1007 status_t ret = NO_ERROR;
1008 std::vector<DescriptorPtr> evictedClients;
1009 DescriptorPtr clientDescriptor;
1010 {
1011 if (effectiveApiLevel == API_1) {
1012 // If we are using API1, any existing client for this camera ID with the same remote
1013 // should be returned rather than evicted to allow MediaRecorder to work properly.
1014
1015 auto current = mActiveClientManager.get(cameraId);
1016 if (current != nullptr) {
1017 auto clientSp = current->getValue();
1018 if (clientSp.get() != nullptr) { // should never be needed
1019 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
1020 ALOGW("CameraService connect called from same client, but with a different"
1021 " API level, evicting prior client...");
1022 } else if (clientSp->getRemote() == remoteCallback) {
1023 ALOGI("CameraService::connect X (PID %d) (second call from same"
1024 " app binder, returning the same client)", clientPid);
1025 *client = clientSp;
1026 return NO_ERROR;
1027 }
1028 }
1029 }
1030 }
1031
1032 // Get current active client PIDs
1033 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1034 ownerPids.push_back(clientPid);
1035
1036 std::vector<int> priorityScores(ownerPids.size());
1037 std::vector<int> states(ownerPids.size());
1038
1039 // Get priority scores of all active PIDs
1040 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1041 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1042 /*out*/&priorityScores[0]);
1043 if (err != OK) {
1044 ALOGE("%s: Priority score query failed: %d",
1045 __FUNCTION__, err);
1046 return err;
1047 }
1048
1049 // Update all active clients' priorities
1050 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
1051 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
1052 pidToPriorityMap.emplace(ownerPids[i],
1053 resource_policy::ClientPriority(priorityScores[i], states[i]));
1054 }
1055 mActiveClientManager.updatePriorities(pidToPriorityMap);
1056
1057 // Get state for the given cameraId
1058 auto state = getCameraState(cameraId);
1059 if (state == nullptr) {
1060 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1061 clientPid, cameraId.string());
1062 // Should never get here because validateConnectLocked should have errored out
1063 return BAD_VALUE;
1064 }
1065
1066 // Make descriptor for incoming client
1067 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1068 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1069 state->getConflicting(),
1070 priorityScores[priorityScores.size() - 1],
1071 clientPid,
1072 states[states.size() - 1]);
1073
1074 // Find clients that would be evicted
1075 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1076
1077 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1078 // background, so we cannot do evictions
1079 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1080 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1081 " priority).", clientPid);
1082
1083 sp<BasicClient> clientSp = clientDescriptor->getValue();
1084 String8 curTime = getFormattedCurrentTime();
1085 auto incompatibleClients =
1086 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1087
1088 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
1089 "(PID %d, score %d state %d) due to eviction policy", curTime.string(),
1090 cameraId.string(), packageName.string(), clientPid,
1091 priorityScores[priorityScores.size() - 1],
1092 states[states.size() - 1]);
1093
1094 for (auto& i : incompatibleClients) {
1095 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
1096 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
1097 i->getKey().string(),
1098 String8{i->getValue()->getPackageName()}.string(),
1099 i->getOwnerId(), i->getPriority().getScore(),
1100 i->getPriority().getState());
1101 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
1102 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(),
1103 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
1104 i->getPriority().getScore(), i->getPriority().getState());
1105 }
1106
1107 // Log the client's attempt
1108 Mutex::Autolock l(mLogLock);
1109 mEventLog.add(msg);
1110
1111 return -EBUSY;
1112 }
1113
1114 for (auto& i : evicted) {
1115 sp<BasicClient> clientSp = i->getValue();
1116 if (clientSp.get() == nullptr) {
1117 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1118
1119 // TODO: Remove this
1120 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1121 __FUNCTION__);
1122 mActiveClientManager.remove(i);
1123 continue;
1124 }
1125
1126 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1127 i->getKey().string());
1128 evictedClients.push_back(i);
1129
1130 // Log the clients evicted
1131 logEvent(String8::format("EVICT device %s client held by package %s (PID"
1132 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1133 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
1134 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
1135 i->getOwnerId(), i->getPriority().getScore(),
1136 i->getPriority().getState(), cameraId.string(),
1137 packageName.string(), clientPid,
1138 priorityScores[priorityScores.size() - 1],
1139 states[states.size() - 1]));
1140
1141 // Notify the client of disconnection
1142 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
1143 CaptureResultExtras());
1144 }
1145 }
1146
1147 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1148 // other clients from connecting in mServiceLockWrapper if held
1149 mServiceLock.unlock();
1150
1151 // Clear caller identity temporarily so client disconnect PID checks work correctly
1152 int64_t token = IPCThreadState::self()->clearCallingIdentity();
1153
1154 // Destroy evicted clients
1155 for (auto& i : evictedClients) {
1156 // Disconnect is blocking, and should only have returned when HAL has cleaned up
1157 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
1158 }
1159
1160 IPCThreadState::self()->restoreCallingIdentity(token);
1161
1162 for (const auto& i : evictedClients) {
1163 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1164 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1165 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1166 if (ret == TIMED_OUT) {
1167 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1168 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1169 mActiveClientManager.toString().string());
1170 return -EBUSY;
1171 }
1172 if (ret != NO_ERROR) {
1173 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1174 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1175 ret, mActiveClientManager.toString().string());
1176 return ret;
1177 }
1178 }
1179
1180 evictedClients.clear();
1181
1182 // Once clients have been disconnected, relock
1183 mServiceLock.lock();
1184
1185 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1186 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1187 return ret;
1188 }
1189
1190 *partial = clientDescriptor;
1191 return NO_ERROR;
1192 }
1193
connect(const sp<ICameraClient> & cameraClient,int cameraId,const String16 & clientPackageName,int clientUid,int clientPid,sp<ICamera> * device)1194 Status CameraService::connect(
1195 const sp<ICameraClient>& cameraClient,
1196 int cameraId,
1197 const String16& clientPackageName,
1198 int clientUid,
1199 int clientPid,
1200 /*out*/
1201 sp<ICamera>* device) {
1202
1203 ATRACE_CALL();
1204 Status ret = Status::ok();
1205 String8 id = String8::format("%d", cameraId);
1206 sp<Client> client = nullptr;
1207 ret = connectHelper<ICameraClient,Client>(cameraClient, id,
1208 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, clientUid, clientPid, API_1,
1209 /*legacyMode*/ false, /*shimUpdateOnly*/ false,
1210 /*out*/client);
1211
1212 if(!ret.isOk()) {
1213 logRejected(id, getCallingPid(), String8(clientPackageName),
1214 ret.toString8());
1215 return ret;
1216 }
1217
1218 *device = client;
1219 return ret;
1220 }
1221
connectLegacy(const sp<ICameraClient> & cameraClient,int cameraId,int halVersion,const String16 & clientPackageName,int clientUid,sp<ICamera> * device)1222 Status CameraService::connectLegacy(
1223 const sp<ICameraClient>& cameraClient,
1224 int cameraId, int halVersion,
1225 const String16& clientPackageName,
1226 int clientUid,
1227 /*out*/
1228 sp<ICamera>* device) {
1229
1230 ATRACE_CALL();
1231 String8 id = String8::format("%d", cameraId);
1232
1233 Status ret = Status::ok();
1234 sp<Client> client = nullptr;
1235 ret = connectHelper<ICameraClient,Client>(cameraClient, id, halVersion,
1236 clientPackageName, clientUid, USE_CALLING_PID, API_1,
1237 /*legacyMode*/ true, /*shimUpdateOnly*/ false,
1238 /*out*/client);
1239
1240 if(!ret.isOk()) {
1241 logRejected(id, getCallingPid(), String8(clientPackageName),
1242 ret.toString8());
1243 return ret;
1244 }
1245
1246 *device = client;
1247 return ret;
1248 }
1249
connectDevice(const sp<hardware::camera2::ICameraDeviceCallbacks> & cameraCb,const String16 & cameraId,const String16 & clientPackageName,int clientUid,sp<hardware::camera2::ICameraDeviceUser> * device)1250 Status CameraService::connectDevice(
1251 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
1252 const String16& cameraId,
1253 const String16& clientPackageName,
1254 int clientUid,
1255 /*out*/
1256 sp<hardware::camera2::ICameraDeviceUser>* device) {
1257
1258 ATRACE_CALL();
1259 Status ret = Status::ok();
1260 String8 id = String8(cameraId);
1261 sp<CameraDeviceClient> client = nullptr;
1262 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
1263 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName,
1264 clientUid, USE_CALLING_PID, API_2,
1265 /*legacyMode*/ false, /*shimUpdateOnly*/ false,
1266 /*out*/client);
1267
1268 if(!ret.isOk()) {
1269 logRejected(id, getCallingPid(), String8(clientPackageName),
1270 ret.toString8());
1271 return ret;
1272 }
1273
1274 *device = client;
1275 return ret;
1276 }
1277
1278 template<class CALLBACK, class CLIENT>
connectHelper(const sp<CALLBACK> & cameraCb,const String8 & cameraId,int halVersion,const String16 & clientPackageName,int clientUid,int clientPid,apiLevel effectiveApiLevel,bool legacyMode,bool shimUpdateOnly,sp<CLIENT> & device)1279 Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
1280 int halVersion, const String16& clientPackageName, int clientUid, int clientPid,
1281 apiLevel effectiveApiLevel, bool legacyMode, bool shimUpdateOnly,
1282 /*out*/sp<CLIENT>& device) {
1283 binder::Status ret = binder::Status::ok();
1284
1285 String8 clientName8(clientPackageName);
1286
1287 int originalClientPid = 0;
1288
1289 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) for HAL version %s and "
1290 "Camera API version %d", clientPid, clientName8.string(), cameraId.string(),
1291 (halVersion == -1) ? "default" : std::to_string(halVersion).c_str(),
1292 static_cast<int>(effectiveApiLevel));
1293
1294 sp<CLIENT> client = nullptr;
1295 {
1296 // Acquire mServiceLock and prevent other clients from connecting
1297 std::unique_ptr<AutoConditionLock> lock =
1298 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1299
1300 if (lock == nullptr) {
1301 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
1302 , clientPid);
1303 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1304 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
1305 cameraId.string(), clientName8.string(), clientPid);
1306 }
1307
1308 // Enforce client permissions and do basic sanity checks
1309 if(!(ret = validateConnectLocked(cameraId, clientName8,
1310 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
1311 return ret;
1312 }
1313
1314 // Check the shim parameters after acquiring lock, if they have already been updated and
1315 // we were doing a shim update, return immediately
1316 if (shimUpdateOnly) {
1317 auto cameraState = getCameraState(cameraId);
1318 if (cameraState != nullptr) {
1319 if (!cameraState->getShimParams().isEmpty()) return ret;
1320 }
1321 }
1322
1323 status_t err;
1324
1325 sp<BasicClient> clientTmp = nullptr;
1326 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
1327 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
1328 IInterface::asBinder(cameraCb), clientName8, /*out*/&clientTmp,
1329 /*out*/&partial)) != NO_ERROR) {
1330 switch (err) {
1331 case -ENODEV:
1332 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1333 "No camera device with ID \"%s\" currently available",
1334 cameraId.string());
1335 case -EBUSY:
1336 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1337 "Higher-priority client using camera, ID \"%s\" currently unavailable",
1338 cameraId.string());
1339 default:
1340 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1341 "Unexpected error %s (%d) opening camera \"%s\"",
1342 strerror(-err), err, cameraId.string());
1343 }
1344 }
1345
1346 if (clientTmp.get() != nullptr) {
1347 // Handle special case for API1 MediaRecorder where the existing client is returned
1348 device = static_cast<CLIENT*>(clientTmp.get());
1349 return ret;
1350 }
1351
1352 // give flashlight a chance to close devices if necessary.
1353 mFlashlight->prepareDeviceOpen(cameraId);
1354
1355 int facing = -1;
1356 int deviceVersion = getDeviceVersion(cameraId, /*out*/&facing);
1357 if (facing == -1) {
1358 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.string());
1359 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1360 "Unable to get camera device \"%s\" facing", cameraId.string());
1361 }
1362
1363 sp<BasicClient> tmp = nullptr;
1364 if(!(ret = makeClient(this, cameraCb, clientPackageName, cameraId, facing, clientPid,
1365 clientUid, getpid(), legacyMode, halVersion, deviceVersion, effectiveApiLevel,
1366 /*out*/&tmp)).isOk()) {
1367 return ret;
1368 }
1369 client = static_cast<CLIENT*>(tmp.get());
1370
1371 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
1372 __FUNCTION__);
1373
1374 err = client->initialize(mCameraProviderManager);
1375 if (err != OK) {
1376 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
1377 // Errors could be from the HAL module open call or from AppOpsManager
1378 switch(err) {
1379 case BAD_VALUE:
1380 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1381 "Illegal argument to HAL module for camera \"%s\"", cameraId.string());
1382 case -EBUSY:
1383 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1384 "Camera \"%s\" is already open", cameraId.string());
1385 case -EUSERS:
1386 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1387 "Too many cameras already open, cannot open camera \"%s\"",
1388 cameraId.string());
1389 case PERMISSION_DENIED:
1390 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1391 "No permission to open camera \"%s\"", cameraId.string());
1392 case -EACCES:
1393 return STATUS_ERROR_FMT(ERROR_DISABLED,
1394 "Camera \"%s\" disabled by policy", cameraId.string());
1395 case -ENODEV:
1396 default:
1397 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1398 "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
1399 strerror(-err), err);
1400 }
1401 }
1402
1403 // Update shim paremeters for legacy clients
1404 if (effectiveApiLevel == API_1) {
1405 // Assume we have always received a Client subclass for API1
1406 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
1407 String8 rawParams = shimClient->getParameters();
1408 CameraParameters params(rawParams);
1409
1410 auto cameraState = getCameraState(cameraId);
1411 if (cameraState != nullptr) {
1412 cameraState->setShimParams(params);
1413 } else {
1414 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
1415 __FUNCTION__, cameraId.string());
1416 }
1417 }
1418
1419 if (shimUpdateOnly) {
1420 // If only updating legacy shim parameters, immediately disconnect client
1421 mServiceLock.unlock();
1422 client->disconnect();
1423 mServiceLock.lock();
1424 } else {
1425 // Otherwise, add client to active clients list
1426 finishConnectLocked(client, partial);
1427 }
1428 } // lock is destroyed, allow further connect calls
1429
1430 // Important: release the mutex here so the client can call back into the service from its
1431 // destructor (can be at the end of the call)
1432 device = client;
1433 return ret;
1434 }
1435
setTorchMode(const String16 & cameraId,bool enabled,const sp<IBinder> & clientBinder)1436 Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
1437 const sp<IBinder>& clientBinder) {
1438 Mutex::Autolock lock(mServiceLock);
1439
1440 ATRACE_CALL();
1441 if (enabled && clientBinder == nullptr) {
1442 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
1443 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1444 "Torch client Binder is null");
1445 }
1446
1447 String8 id = String8(cameraId.string());
1448 int uid = getCallingUid();
1449
1450 // verify id is valid.
1451 auto state = getCameraState(id);
1452 if (state == nullptr) {
1453 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
1454 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1455 "Camera ID \"%s\" is a not valid camera ID", id.string());
1456 }
1457
1458 StatusInternal cameraStatus = state->getStatus();
1459 if (cameraStatus != StatusInternal::PRESENT &&
1460 cameraStatus != StatusInternal::NOT_AVAILABLE) {
1461 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus);
1462 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1463 "Camera ID \"%s\" is a not valid camera ID", id.string());
1464 }
1465
1466 {
1467 Mutex::Autolock al(mTorchStatusMutex);
1468 TorchModeStatus status;
1469 status_t err = getTorchStatusLocked(id, &status);
1470 if (err != OK) {
1471 if (err == NAME_NOT_FOUND) {
1472 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1473 "Camera \"%s\" does not have a flash unit", id.string());
1474 }
1475 ALOGE("%s: getting current torch status failed for camera %s",
1476 __FUNCTION__, id.string());
1477 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1478 "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
1479 strerror(-err), err);
1480 }
1481
1482 if (status == TorchModeStatus::NOT_AVAILABLE) {
1483 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
1484 ALOGE("%s: torch mode of camera %s is not available because "
1485 "camera is in use", __FUNCTION__, id.string());
1486 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1487 "Torch for camera \"%s\" is not available due to an existing camera user",
1488 id.string());
1489 } else {
1490 ALOGE("%s: torch mode of camera %s is not available due to "
1491 "insufficient resources", __FUNCTION__, id.string());
1492 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1493 "Torch for camera \"%s\" is not available due to insufficient resources",
1494 id.string());
1495 }
1496 }
1497 }
1498
1499 {
1500 // Update UID map - this is used in the torch status changed callbacks, so must be done
1501 // before setTorchMode
1502 Mutex::Autolock al(mTorchUidMapMutex);
1503 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
1504 mTorchUidMap[id].first = uid;
1505 mTorchUidMap[id].second = uid;
1506 } else {
1507 // Set the pending UID
1508 mTorchUidMap[id].first = uid;
1509 }
1510 }
1511
1512 status_t err = mFlashlight->setTorchMode(id, enabled);
1513
1514 if (err != OK) {
1515 int32_t errorCode;
1516 String8 msg;
1517 switch (err) {
1518 case -ENOSYS:
1519 msg = String8::format("Camera \"%s\" has no flashlight",
1520 id.string());
1521 errorCode = ERROR_ILLEGAL_ARGUMENT;
1522 break;
1523 default:
1524 msg = String8::format(
1525 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
1526 id.string(), enabled, strerror(-err), err);
1527 errorCode = ERROR_INVALID_OPERATION;
1528 }
1529 ALOGE("%s: %s", __FUNCTION__, msg.string());
1530 return STATUS_ERROR(errorCode, msg.string());
1531 }
1532
1533 {
1534 // update the link to client's death
1535 Mutex::Autolock al(mTorchClientMapMutex);
1536 ssize_t index = mTorchClientMap.indexOfKey(id);
1537 if (enabled) {
1538 if (index == NAME_NOT_FOUND) {
1539 mTorchClientMap.add(id, clientBinder);
1540 } else {
1541 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
1542 mTorchClientMap.replaceValueAt(index, clientBinder);
1543 }
1544 clientBinder->linkToDeath(this);
1545 } else if (index != NAME_NOT_FOUND) {
1546 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
1547 }
1548 }
1549
1550 return Status::ok();
1551 }
1552
notifySystemEvent(int32_t eventId,const std::vector<int32_t> & args)1553 Status CameraService::notifySystemEvent(int32_t eventId,
1554 const std::vector<int32_t>& args) {
1555 ATRACE_CALL();
1556
1557 switch(eventId) {
1558 case ICameraService::EVENT_USER_SWITCHED: {
1559 doUserSwitch(/*newUserIds*/ args);
1560 break;
1561 }
1562 case ICameraService::EVENT_NONE:
1563 default: {
1564 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
1565 eventId);
1566 break;
1567 }
1568 }
1569 return Status::ok();
1570 }
1571
addListener(const sp<ICameraServiceListener> & listener,std::vector<hardware::CameraStatus> * cameraStatuses)1572 Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
1573 /*out*/
1574 std::vector<hardware::CameraStatus> *cameraStatuses) {
1575 ATRACE_CALL();
1576
1577 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
1578
1579 if (listener == nullptr) {
1580 ALOGE("%s: Listener must not be null", __FUNCTION__);
1581 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
1582 }
1583
1584 Mutex::Autolock lock(mServiceLock);
1585
1586 {
1587 Mutex::Autolock lock(mStatusListenerLock);
1588 for (auto& it : mListenerList) {
1589 if (IInterface::asBinder(it) == IInterface::asBinder(listener)) {
1590 ALOGW("%s: Tried to add listener %p which was already subscribed",
1591 __FUNCTION__, listener.get());
1592 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
1593 }
1594 }
1595
1596 mListenerList.push_back(listener);
1597 }
1598
1599 /* Collect current devices and status */
1600 {
1601 Mutex::Autolock lock(mCameraStatesLock);
1602 for (auto& i : mCameraStates) {
1603 cameraStatuses->emplace_back(i.first, mapToInterface(i.second->getStatus()));
1604 }
1605 }
1606
1607 /*
1608 * Immediately signal current torch status to this listener only
1609 * This may be a subset of all the devices, so don't include it in the response directly
1610 */
1611 {
1612 Mutex::Autolock al(mTorchStatusMutex);
1613 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
1614 String16 id = String16(mTorchStatusMap.keyAt(i).string());
1615 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
1616 }
1617 }
1618
1619 return Status::ok();
1620 }
1621
removeListener(const sp<ICameraServiceListener> & listener)1622 Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
1623 ATRACE_CALL();
1624
1625 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
1626
1627 if (listener == 0) {
1628 ALOGE("%s: Listener must not be null", __FUNCTION__);
1629 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
1630 }
1631
1632 Mutex::Autolock lock(mServiceLock);
1633
1634 {
1635 Mutex::Autolock lock(mStatusListenerLock);
1636 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
1637 if (IInterface::asBinder(*it) == IInterface::asBinder(listener)) {
1638 mListenerList.erase(it);
1639 return Status::ok();
1640 }
1641 }
1642 }
1643
1644 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
1645 __FUNCTION__, listener.get());
1646
1647 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
1648 }
1649
getLegacyParameters(int cameraId,String16 * parameters)1650 Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
1651
1652 ATRACE_CALL();
1653 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1654
1655 if (parameters == NULL) {
1656 ALOGE("%s: parameters must not be null", __FUNCTION__);
1657 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
1658 }
1659
1660 Status ret = Status::ok();
1661
1662 CameraParameters shimParams;
1663 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
1664 // Error logged by caller
1665 return ret;
1666 }
1667
1668 String8 shimParamsString8 = shimParams.flatten();
1669 String16 shimParamsString16 = String16(shimParamsString8);
1670
1671 *parameters = shimParamsString16;
1672
1673 return ret;
1674 }
1675
supportsCameraApi(const String16 & cameraId,int apiVersion,bool * isSupported)1676 Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
1677 /*out*/ bool *isSupported) {
1678 ATRACE_CALL();
1679
1680 const String8 id = String8(cameraId);
1681
1682 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
1683
1684 switch (apiVersion) {
1685 case API_VERSION_1:
1686 case API_VERSION_2:
1687 break;
1688 default:
1689 String8 msg = String8::format("Unknown API version %d", apiVersion);
1690 ALOGE("%s: %s", __FUNCTION__, msg.string());
1691 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
1692 }
1693
1694 int deviceVersion = getDeviceVersion(id);
1695 switch(deviceVersion) {
1696 case CAMERA_DEVICE_API_VERSION_1_0:
1697 case CAMERA_DEVICE_API_VERSION_3_0:
1698 case CAMERA_DEVICE_API_VERSION_3_1:
1699 if (apiVersion == API_VERSION_2) {
1700 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without shim",
1701 __FUNCTION__, id.string(), deviceVersion);
1702 *isSupported = false;
1703 } else { // if (apiVersion == API_VERSION_1) {
1704 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always supported",
1705 __FUNCTION__, id.string());
1706 *isSupported = true;
1707 }
1708 break;
1709 case CAMERA_DEVICE_API_VERSION_3_2:
1710 case CAMERA_DEVICE_API_VERSION_3_3:
1711 case CAMERA_DEVICE_API_VERSION_3_4:
1712 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
1713 __FUNCTION__, id.string());
1714 *isSupported = true;
1715 break;
1716 case -1: {
1717 String8 msg = String8::format("Unknown camera ID %s", id.string());
1718 ALOGE("%s: %s", __FUNCTION__, msg.string());
1719 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
1720 }
1721 default: {
1722 String8 msg = String8::format("Unknown device version %x for device %s",
1723 deviceVersion, id.string());
1724 ALOGE("%s: %s", __FUNCTION__, msg.string());
1725 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
1726 }
1727 }
1728
1729 return Status::ok();
1730 }
1731
removeByClient(const BasicClient * client)1732 void CameraService::removeByClient(const BasicClient* client) {
1733 Mutex::Autolock lock(mServiceLock);
1734 for (auto& i : mActiveClientManager.getAll()) {
1735 auto clientSp = i->getValue();
1736 if (clientSp.get() == client) {
1737 mActiveClientManager.remove(i);
1738 }
1739 }
1740 }
1741
evictClientIdByRemote(const wp<IBinder> & remote)1742 bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
1743 const int callingPid = getCallingPid();
1744 const int servicePid = getpid();
1745 bool ret = false;
1746 {
1747 // Acquire mServiceLock and prevent other clients from connecting
1748 std::unique_ptr<AutoConditionLock> lock =
1749 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1750
1751
1752 std::vector<sp<BasicClient>> evicted;
1753 for (auto& i : mActiveClientManager.getAll()) {
1754 auto clientSp = i->getValue();
1755 if (clientSp.get() == nullptr) {
1756 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
1757 mActiveClientManager.remove(i);
1758 continue;
1759 }
1760 if (remote == clientSp->getRemote() && (callingPid == servicePid ||
1761 callingPid == clientSp->getClientPid())) {
1762 mActiveClientManager.remove(i);
1763 evicted.push_back(clientSp);
1764
1765 // Notify the client of disconnection
1766 clientSp->notifyError(
1767 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
1768 CaptureResultExtras());
1769 }
1770 }
1771
1772 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1773 // other clients from connecting in mServiceLockWrapper if held
1774 mServiceLock.unlock();
1775
1776 // Do not clear caller identity, remote caller should be client proccess
1777
1778 for (auto& i : evicted) {
1779 if (i.get() != nullptr) {
1780 i->disconnect();
1781 ret = true;
1782 }
1783 }
1784
1785 // Reacquire mServiceLock
1786 mServiceLock.lock();
1787
1788 } // lock is destroyed, allow further connect calls
1789
1790 return ret;
1791 }
1792
getCameraState(const String8 & cameraId) const1793 std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
1794 const String8& cameraId) const {
1795 std::shared_ptr<CameraState> state;
1796 {
1797 Mutex::Autolock lock(mCameraStatesLock);
1798 auto iter = mCameraStates.find(cameraId);
1799 if (iter != mCameraStates.end()) {
1800 state = iter->second;
1801 }
1802 }
1803 return state;
1804 }
1805
removeClientLocked(const String8 & cameraId)1806 sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
1807 // Remove from active clients list
1808 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
1809 if (clientDescriptorPtr == nullptr) {
1810 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
1811 cameraId.string());
1812 return sp<BasicClient>{nullptr};
1813 }
1814
1815 return clientDescriptorPtr->getValue();
1816 }
1817
doUserSwitch(const std::vector<int32_t> & newUserIds)1818 void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
1819 // Acquire mServiceLock and prevent other clients from connecting
1820 std::unique_ptr<AutoConditionLock> lock =
1821 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1822
1823 std::set<userid_t> newAllowedUsers;
1824 for (size_t i = 0; i < newUserIds.size(); i++) {
1825 if (newUserIds[i] < 0) {
1826 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
1827 __FUNCTION__, newUserIds[i]);
1828 return;
1829 }
1830 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
1831 }
1832
1833
1834 if (newAllowedUsers == mAllowedUsers) {
1835 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
1836 return;
1837 }
1838
1839 logUserSwitch(mAllowedUsers, newAllowedUsers);
1840
1841 mAllowedUsers = std::move(newAllowedUsers);
1842
1843 // Current user has switched, evict all current clients.
1844 std::vector<sp<BasicClient>> evicted;
1845 for (auto& i : mActiveClientManager.getAll()) {
1846 auto clientSp = i->getValue();
1847
1848 if (clientSp.get() == nullptr) {
1849 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
1850 continue;
1851 }
1852
1853 // Don't evict clients that are still allowed.
1854 uid_t clientUid = clientSp->getClientUid();
1855 userid_t clientUserId = multiuser_get_user_id(clientUid);
1856 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
1857 continue;
1858 }
1859
1860 evicted.push_back(clientSp);
1861
1862 String8 curTime = getFormattedCurrentTime();
1863
1864 ALOGE("Evicting conflicting client for camera ID %s due to user change",
1865 i->getKey().string());
1866
1867 // Log the clients evicted
1868 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
1869 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
1870 " to user switch.", i->getKey().string(),
1871 String8{clientSp->getPackageName()}.string(),
1872 i->getOwnerId(), i->getPriority().getScore(),
1873 i->getPriority().getState()));
1874
1875 }
1876
1877 // Do not hold mServiceLock while disconnecting clients, but retain the condition
1878 // blocking other clients from connecting in mServiceLockWrapper if held.
1879 mServiceLock.unlock();
1880
1881 // Clear caller identity temporarily so client disconnect PID checks work correctly
1882 int64_t token = IPCThreadState::self()->clearCallingIdentity();
1883
1884 for (auto& i : evicted) {
1885 i->disconnect();
1886 }
1887
1888 IPCThreadState::self()->restoreCallingIdentity(token);
1889
1890 // Reacquire mServiceLock
1891 mServiceLock.lock();
1892 }
1893
logEvent(const char * event)1894 void CameraService::logEvent(const char* event) {
1895 String8 curTime = getFormattedCurrentTime();
1896 Mutex::Autolock l(mLogLock);
1897 mEventLog.add(String8::format("%s : %s", curTime.string(), event));
1898 }
1899
logDisconnected(const char * cameraId,int clientPid,const char * clientPackage)1900 void CameraService::logDisconnected(const char* cameraId, int clientPid,
1901 const char* clientPackage) {
1902 // Log the clients evicted
1903 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
1904 clientPackage, clientPid));
1905 }
1906
logConnected(const char * cameraId,int clientPid,const char * clientPackage)1907 void CameraService::logConnected(const char* cameraId, int clientPid,
1908 const char* clientPackage) {
1909 // Log the clients evicted
1910 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
1911 clientPackage, clientPid));
1912 }
1913
logRejected(const char * cameraId,int clientPid,const char * clientPackage,const char * reason)1914 void CameraService::logRejected(const char* cameraId, int clientPid,
1915 const char* clientPackage, const char* reason) {
1916 // Log the client rejected
1917 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
1918 cameraId, clientPackage, clientPid, reason));
1919 }
1920
logUserSwitch(const std::set<userid_t> & oldUserIds,const std::set<userid_t> & newUserIds)1921 void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
1922 const std::set<userid_t>& newUserIds) {
1923 String8 newUsers = toString(newUserIds);
1924 String8 oldUsers = toString(oldUserIds);
1925 if (oldUsers.size() == 0) {
1926 oldUsers = "<None>";
1927 }
1928 // Log the new and old users
1929 logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
1930 oldUsers.string(), newUsers.string()));
1931 }
1932
logDeviceRemoved(const char * cameraId,const char * reason)1933 void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
1934 // Log the device removal
1935 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
1936 }
1937
logDeviceAdded(const char * cameraId,const char * reason)1938 void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
1939 // Log the device removal
1940 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
1941 }
1942
logClientDied(int clientPid,const char * reason)1943 void CameraService::logClientDied(int clientPid, const char* reason) {
1944 // Log the device removal
1945 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
1946 }
1947
logServiceError(const char * msg,int errorCode)1948 void CameraService::logServiceError(const char* msg, int errorCode) {
1949 String8 curTime = getFormattedCurrentTime();
1950 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
1951 }
1952
onTransact(uint32_t code,const Parcel & data,Parcel * reply,uint32_t flags)1953 status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
1954 uint32_t flags) {
1955
1956 const int pid = getCallingPid();
1957 const int selfPid = getpid();
1958
1959 // Permission checks
1960 switch (code) {
1961 case BnCameraService::NOTIFYSYSTEMEVENT: {
1962 if (pid != selfPid) {
1963 // Ensure we're being called by system_server, or similar process with
1964 // permissions to notify the camera service about system events
1965 if (!checkCallingPermission(
1966 String16("android.permission.CAMERA_SEND_SYSTEM_EVENTS"))) {
1967 const int uid = getCallingUid();
1968 ALOGE("Permission Denial: cannot send updates to camera service about system"
1969 " events from pid=%d, uid=%d", pid, uid);
1970 return PERMISSION_DENIED;
1971 }
1972 }
1973 break;
1974 }
1975 }
1976
1977 return BnCameraService::onTransact(code, data, reply, flags);
1978 }
1979
1980 // We share the media players for shutter and recording sound for all clients.
1981 // A reference count is kept to determine when we will actually release the
1982 // media players.
1983
newMediaPlayer(const char * file)1984 MediaPlayer* CameraService::newMediaPlayer(const char *file) {
1985 MediaPlayer* mp = new MediaPlayer();
1986 if (mp->setDataSource(NULL /* httpService */, file, NULL) == NO_ERROR) {
1987 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
1988 mp->prepare();
1989 } else {
1990 ALOGE("Failed to load CameraService sounds: %s", file);
1991 return NULL;
1992 }
1993 return mp;
1994 }
1995
loadSound()1996 void CameraService::loadSound() {
1997 ATRACE_CALL();
1998
1999 Mutex::Autolock lock(mSoundLock);
2000 LOG1("CameraService::loadSound ref=%d", mSoundRef);
2001 if (mSoundRef++) return;
2002
2003 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
2004 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
2005 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
2006 }
2007
releaseSound()2008 void CameraService::releaseSound() {
2009 Mutex::Autolock lock(mSoundLock);
2010 LOG1("CameraService::releaseSound ref=%d", mSoundRef);
2011 if (--mSoundRef) return;
2012
2013 for (int i = 0; i < NUM_SOUNDS; i++) {
2014 if (mSoundPlayer[i] != 0) {
2015 mSoundPlayer[i]->disconnect();
2016 mSoundPlayer[i].clear();
2017 }
2018 }
2019 }
2020
playSound(sound_kind kind)2021 void CameraService::playSound(sound_kind kind) {
2022 ATRACE_CALL();
2023
2024 LOG1("playSound(%d)", kind);
2025 Mutex::Autolock lock(mSoundLock);
2026 sp<MediaPlayer> player = mSoundPlayer[kind];
2027 if (player != 0) {
2028 player->seekTo(0);
2029 player->start();
2030 }
2031 }
2032
2033 // ----------------------------------------------------------------------------
2034
Client(const sp<CameraService> & cameraService,const sp<ICameraClient> & cameraClient,const String16 & clientPackageName,const String8 & cameraIdStr,int cameraFacing,int clientPid,uid_t clientUid,int servicePid)2035 CameraService::Client::Client(const sp<CameraService>& cameraService,
2036 const sp<ICameraClient>& cameraClient,
2037 const String16& clientPackageName,
2038 const String8& cameraIdStr, int cameraFacing,
2039 int clientPid, uid_t clientUid,
2040 int servicePid) :
2041 CameraService::BasicClient(cameraService,
2042 IInterface::asBinder(cameraClient),
2043 clientPackageName,
2044 cameraIdStr, cameraFacing,
2045 clientPid, clientUid,
2046 servicePid),
2047 mCameraId(CameraService::cameraIdToInt(cameraIdStr))
2048 {
2049 int callingPid = getCallingPid();
2050 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
2051
2052 mRemoteCallback = cameraClient;
2053
2054 cameraService->loadSound();
2055
2056 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
2057 }
2058
2059 // tear down the client
~Client()2060 CameraService::Client::~Client() {
2061 ALOGV("~Client");
2062 mDestructionStarted = true;
2063
2064 sCameraService->releaseSound();
2065 // unconditionally disconnect. function is idempotent
2066 Client::disconnect();
2067 }
2068
2069 sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
2070
BasicClient(const sp<CameraService> & cameraService,const sp<IBinder> & remoteCallback,const String16 & clientPackageName,const String8 & cameraIdStr,int cameraFacing,int clientPid,uid_t clientUid,int servicePid)2071 CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
2072 const sp<IBinder>& remoteCallback,
2073 const String16& clientPackageName,
2074 const String8& cameraIdStr, int cameraFacing,
2075 int clientPid, uid_t clientUid,
2076 int servicePid):
2077 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing),
2078 mClientPackageName(clientPackageName), mClientPid(clientPid), mClientUid(clientUid),
2079 mServicePid(servicePid),
2080 mDisconnected(false),
2081 mRemoteBinder(remoteCallback)
2082 {
2083 if (sCameraService == nullptr) {
2084 sCameraService = cameraService;
2085 }
2086 mOpsActive = false;
2087 mDestructionStarted = false;
2088
2089 // In some cases the calling code has no access to the package it runs under.
2090 // For example, NDK camera API.
2091 // In this case we will get the packages for the calling UID and pick the first one
2092 // for attributing the app op. This will work correctly for runtime permissions
2093 // as for legacy apps we will toggle the app op for all packages in the UID.
2094 // The caveat is that the operation may be attributed to the wrong package and
2095 // stats based on app ops may be slightly off.
2096 if (mClientPackageName.size() <= 0) {
2097 sp<IServiceManager> sm = defaultServiceManager();
2098 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
2099 if (binder == 0) {
2100 ALOGE("Cannot get permission service");
2101 // Leave mClientPackageName unchanged (empty) and the further interaction
2102 // with camera will fail in BasicClient::startCameraOps
2103 return;
2104 }
2105
2106 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
2107 Vector<String16> packages;
2108
2109 permCtrl->getPackagesForUid(mClientUid, packages);
2110
2111 if (packages.isEmpty()) {
2112 ALOGE("No packages for calling UID");
2113 // Leave mClientPackageName unchanged (empty) and the further interaction
2114 // with camera will fail in BasicClient::startCameraOps
2115 return;
2116 }
2117 mClientPackageName = packages[0];
2118 }
2119 }
2120
~BasicClient()2121 CameraService::BasicClient::~BasicClient() {
2122 ALOGV("~BasicClient");
2123 mDestructionStarted = true;
2124 }
2125
disconnect()2126 binder::Status CameraService::BasicClient::disconnect() {
2127 binder::Status res = Status::ok();
2128 if (mDisconnected) {
2129 return res;
2130 }
2131 mDisconnected = true;
2132
2133 sCameraService->removeByClient(this);
2134 sCameraService->logDisconnected(mCameraIdStr, mClientPid,
2135 String8(mClientPackageName));
2136
2137 sp<IBinder> remote = getRemote();
2138 if (remote != nullptr) {
2139 remote->unlinkToDeath(sCameraService);
2140 }
2141
2142 finishCameraOps();
2143 // Notify flashlight that a camera device is closed.
2144 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
2145 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
2146 mClientPid);
2147
2148 // client shouldn't be able to call into us anymore
2149 mClientPid = 0;
2150
2151 return res;
2152 }
2153
dump(int,const Vector<String16> &)2154 status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
2155 // No dumping of clients directly over Binder,
2156 // must go through CameraService::dump
2157 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
2158 IPCThreadState::self()->getCallingUid(), NULL, 0);
2159 return OK;
2160 }
2161
getPackageName() const2162 String16 CameraService::BasicClient::getPackageName() const {
2163 return mClientPackageName;
2164 }
2165
2166
getClientPid() const2167 int CameraService::BasicClient::getClientPid() const {
2168 return mClientPid;
2169 }
2170
getClientUid() const2171 uid_t CameraService::BasicClient::getClientUid() const {
2172 return mClientUid;
2173 }
2174
canCastToApiClient(apiLevel level) const2175 bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
2176 // Defaults to API2.
2177 return level == API_2;
2178 }
2179
startCameraOps()2180 status_t CameraService::BasicClient::startCameraOps() {
2181 ATRACE_CALL();
2182
2183 int32_t res;
2184 // Notify app ops that the camera is not available
2185 mOpsCallback = new OpsCallback(this);
2186
2187 {
2188 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
2189 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
2190 }
2191
2192 mAppOpsManager.startWatchingMode(AppOpsManager::OP_CAMERA,
2193 mClientPackageName, mOpsCallback);
2194 res = mAppOpsManager.startOp(AppOpsManager::OP_CAMERA,
2195 mClientUid, mClientPackageName);
2196
2197 if (res == AppOpsManager::MODE_ERRORED) {
2198 ALOGI("Camera %s: Access for \"%s\" has been revoked",
2199 mCameraIdStr.string(), String8(mClientPackageName).string());
2200 return PERMISSION_DENIED;
2201 }
2202
2203 if (res == AppOpsManager::MODE_IGNORED) {
2204 ALOGI("Camera %s: Access for \"%s\" has been restricted",
2205 mCameraIdStr.string(), String8(mClientPackageName).string());
2206 // Return the same error as for device policy manager rejection
2207 return -EACCES;
2208 }
2209
2210 mOpsActive = true;
2211
2212 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
2213 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
2214
2215 // Transition device state to OPEN
2216 sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_OPEN,
2217 mCameraIdStr, mCameraFacing, mClientPackageName);
2218
2219 return OK;
2220 }
2221
finishCameraOps()2222 status_t CameraService::BasicClient::finishCameraOps() {
2223 ATRACE_CALL();
2224
2225 // Check if startCameraOps succeeded, and if so, finish the camera op
2226 if (mOpsActive) {
2227 // Notify app ops that the camera is available again
2228 mAppOpsManager.finishOp(AppOpsManager::OP_CAMERA, mClientUid,
2229 mClientPackageName);
2230 mOpsActive = false;
2231
2232 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
2233 StatusInternal::ENUMERATING};
2234
2235 // Transition to PRESENT if the camera is not in either of the rejected states
2236 sCameraService->updateStatus(StatusInternal::PRESENT,
2237 mCameraIdStr, rejected);
2238
2239 // Transition device state to CLOSED
2240 sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_CLOSED,
2241 mCameraIdStr, mCameraFacing, mClientPackageName);
2242 }
2243 // Always stop watching, even if no camera op is active
2244 if (mOpsCallback != NULL) {
2245 mAppOpsManager.stopWatchingMode(mOpsCallback);
2246 }
2247 mOpsCallback.clear();
2248
2249 return OK;
2250 }
2251
opChanged(int32_t op,const String16 & packageName)2252 void CameraService::BasicClient::opChanged(int32_t op, const String16& packageName) {
2253 ATRACE_CALL();
2254
2255 String8 name(packageName);
2256 String8 myName(mClientPackageName);
2257
2258 if (op != AppOpsManager::OP_CAMERA) {
2259 ALOGW("Unexpected app ops notification received: %d", op);
2260 return;
2261 }
2262
2263 int32_t res;
2264 res = mAppOpsManager.checkOp(AppOpsManager::OP_CAMERA,
2265 mClientUid, mClientPackageName);
2266 ALOGV("checkOp returns: %d, %s ", res,
2267 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
2268 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
2269 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
2270 "UNKNOWN");
2271
2272 if (res != AppOpsManager::MODE_ALLOWED) {
2273 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
2274 myName.string());
2275 // Reset the client PID to allow server-initiated disconnect,
2276 // and to prevent further calls by client.
2277 mClientPid = getCallingPid();
2278 CaptureResultExtras resultExtras; // a dummy result (invalid)
2279 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_SERVICE, resultExtras);
2280 disconnect();
2281 }
2282 }
2283
2284 // ----------------------------------------------------------------------------
2285
notifyError(int32_t errorCode,const CaptureResultExtras & resultExtras)2286 void CameraService::Client::notifyError(int32_t errorCode,
2287 const CaptureResultExtras& resultExtras) {
2288 (void) errorCode;
2289 (void) resultExtras;
2290 if (mRemoteCallback != NULL) {
2291 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, CAMERA_ERROR_RELEASED, 0);
2292 } else {
2293 ALOGE("mRemoteCallback is NULL!!");
2294 }
2295 }
2296
2297 // NOTE: function is idempotent
disconnect()2298 binder::Status CameraService::Client::disconnect() {
2299 ALOGV("Client::disconnect");
2300 return BasicClient::disconnect();
2301 }
2302
canCastToApiClient(apiLevel level) const2303 bool CameraService::Client::canCastToApiClient(apiLevel level) const {
2304 return level == API_1;
2305 }
2306
OpsCallback(wp<BasicClient> client)2307 CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
2308 mClient(client) {
2309 }
2310
opChanged(int32_t op,const String16 & packageName)2311 void CameraService::Client::OpsCallback::opChanged(int32_t op,
2312 const String16& packageName) {
2313 sp<BasicClient> client = mClient.promote();
2314 if (client != NULL) {
2315 client->opChanged(op, packageName);
2316 }
2317 }
2318
2319 // ----------------------------------------------------------------------------
2320 // CameraState
2321 // ----------------------------------------------------------------------------
2322
CameraState(const String8 & id,int cost,const std::set<String8> & conflicting)2323 CameraService::CameraState::CameraState(const String8& id, int cost,
2324 const std::set<String8>& conflicting) : mId(id),
2325 mStatus(StatusInternal::PRESENT), mCost(cost), mConflicting(conflicting) {}
2326
~CameraState()2327 CameraService::CameraState::~CameraState() {}
2328
getStatus() const2329 CameraService::StatusInternal CameraService::CameraState::getStatus() const {
2330 Mutex::Autolock lock(mStatusLock);
2331 return mStatus;
2332 }
2333
getShimParams() const2334 CameraParameters CameraService::CameraState::getShimParams() const {
2335 return mShimParams;
2336 }
2337
setShimParams(const CameraParameters & params)2338 void CameraService::CameraState::setShimParams(const CameraParameters& params) {
2339 mShimParams = params;
2340 }
2341
getCost() const2342 int CameraService::CameraState::getCost() const {
2343 return mCost;
2344 }
2345
getConflicting() const2346 std::set<String8> CameraService::CameraState::getConflicting() const {
2347 return mConflicting;
2348 }
2349
getId() const2350 String8 CameraService::CameraState::getId() const {
2351 return mId;
2352 }
2353
2354 // ----------------------------------------------------------------------------
2355 // ClientEventListener
2356 // ----------------------------------------------------------------------------
2357
onClientAdded(const resource_policy::ClientDescriptor<String8,sp<CameraService::BasicClient>> & descriptor)2358 void CameraService::ClientEventListener::onClientAdded(
2359 const resource_policy::ClientDescriptor<String8,
2360 sp<CameraService::BasicClient>>& descriptor) {
2361 const auto& basicClient = descriptor.getValue();
2362 if (basicClient.get() != nullptr) {
2363 BatteryNotifier& notifier(BatteryNotifier::getInstance());
2364 notifier.noteStartCamera(descriptor.getKey(),
2365 static_cast<int>(basicClient->getClientUid()));
2366 }
2367 }
2368
onClientRemoved(const resource_policy::ClientDescriptor<String8,sp<CameraService::BasicClient>> & descriptor)2369 void CameraService::ClientEventListener::onClientRemoved(
2370 const resource_policy::ClientDescriptor<String8,
2371 sp<CameraService::BasicClient>>& descriptor) {
2372 const auto& basicClient = descriptor.getValue();
2373 if (basicClient.get() != nullptr) {
2374 BatteryNotifier& notifier(BatteryNotifier::getInstance());
2375 notifier.noteStopCamera(descriptor.getKey(),
2376 static_cast<int>(basicClient->getClientUid()));
2377 }
2378 }
2379
2380
2381 // ----------------------------------------------------------------------------
2382 // CameraClientManager
2383 // ----------------------------------------------------------------------------
2384
CameraClientManager()2385 CameraService::CameraClientManager::CameraClientManager() {
2386 setListener(std::make_shared<ClientEventListener>());
2387 }
2388
~CameraClientManager()2389 CameraService::CameraClientManager::~CameraClientManager() {}
2390
getCameraClient(const String8 & id) const2391 sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
2392 const String8& id) const {
2393 auto descriptor = get(id);
2394 if (descriptor == nullptr) {
2395 return sp<BasicClient>{nullptr};
2396 }
2397 return descriptor->getValue();
2398 }
2399
toString() const2400 String8 CameraService::CameraClientManager::toString() const {
2401 auto all = getAll();
2402 String8 ret("[");
2403 bool hasAny = false;
2404 for (auto& i : all) {
2405 hasAny = true;
2406 String8 key = i->getKey();
2407 int32_t cost = i->getCost();
2408 int32_t pid = i->getOwnerId();
2409 int32_t score = i->getPriority().getScore();
2410 int32_t state = i->getPriority().getState();
2411 auto conflicting = i->getConflicting();
2412 auto clientSp = i->getValue();
2413 String8 packageName;
2414 userid_t clientUserId = 0;
2415 if (clientSp.get() != nullptr) {
2416 packageName = String8{clientSp->getPackageName()};
2417 uid_t clientUid = clientSp->getClientUid();
2418 clientUserId = multiuser_get_user_id(clientUid);
2419 }
2420 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
2421 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
2422
2423 if (clientSp.get() != nullptr) {
2424 ret.appendFormat("User Id: %d, ", clientUserId);
2425 }
2426 if (packageName.size() != 0) {
2427 ret.appendFormat("Client Package Name: %s", packageName.string());
2428 }
2429
2430 ret.append(", Conflicting Client Devices: {");
2431 for (auto& j : conflicting) {
2432 ret.appendFormat("%s, ", j.string());
2433 }
2434 ret.append("})");
2435 }
2436 if (hasAny) ret.append("\n");
2437 ret.append("]\n");
2438 return ret;
2439 }
2440
makeClientDescriptor(const String8 & key,const sp<BasicClient> & value,int32_t cost,const std::set<String8> & conflictingKeys,int32_t score,int32_t ownerId,int32_t state)2441 CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
2442 const String8& key, const sp<BasicClient>& value, int32_t cost,
2443 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
2444 int32_t state) {
2445
2446 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
2447 key, value, cost, conflictingKeys, score, ownerId, state);
2448 }
2449
makeClientDescriptor(const sp<BasicClient> & value,const CameraService::DescriptorPtr & partial)2450 CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
2451 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
2452 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
2453 partial->getConflicting(), partial->getPriority().getScore(),
2454 partial->getOwnerId(), partial->getPriority().getState());
2455 }
2456
2457 // ----------------------------------------------------------------------------
2458
2459 static const int kDumpLockRetries = 50;
2460 static const int kDumpLockSleep = 60000;
2461
tryLock(Mutex & mutex)2462 static bool tryLock(Mutex& mutex)
2463 {
2464 bool locked = false;
2465 for (int i = 0; i < kDumpLockRetries; ++i) {
2466 if (mutex.tryLock() == NO_ERROR) {
2467 locked = true;
2468 break;
2469 }
2470 usleep(kDumpLockSleep);
2471 }
2472 return locked;
2473 }
2474
dump(int fd,const Vector<String16> & args)2475 status_t CameraService::dump(int fd, const Vector<String16>& args) {
2476 ATRACE_CALL();
2477
2478 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
2479 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
2480 getCallingPid(),
2481 getCallingUid());
2482 return NO_ERROR;
2483 }
2484 bool locked = tryLock(mServiceLock);
2485 // failed to lock - CameraService is probably deadlocked
2486 if (!locked) {
2487 dprintf(fd, "!! CameraService may be deadlocked !!\n");
2488 }
2489
2490 if (!mInitialized) {
2491 dprintf(fd, "!! No camera HAL available !!\n");
2492
2493 // Dump event log for error information
2494 dumpEventLog(fd);
2495
2496 if (locked) mServiceLock.unlock();
2497 return NO_ERROR;
2498 }
2499 dprintf(fd, "\n== Service global info: ==\n\n");
2500 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
2501 dprintf(fd, "Number of normal camera devices: %d\n", mNumberOfNormalCameras);
2502 String8 activeClientString = mActiveClientManager.toString();
2503 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
2504 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
2505
2506 dumpEventLog(fd);
2507
2508 bool stateLocked = tryLock(mCameraStatesLock);
2509 if (!stateLocked) {
2510 dprintf(fd, "CameraStates in use, may be deadlocked\n");
2511 }
2512
2513 for (auto& state : mCameraStates) {
2514 String8 cameraId = state.first;
2515
2516 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
2517
2518 CameraParameters p = state.second->getShimParams();
2519 if (!p.isEmpty()) {
2520 dprintf(fd, " Camera1 API shim is using parameters:\n ");
2521 p.dump(fd, args);
2522 }
2523
2524 auto clientDescriptor = mActiveClientManager.get(cameraId);
2525 if (clientDescriptor != nullptr) {
2526 dprintf(fd, " Device %s is open. Client instance dump:\n",
2527 cameraId.string());
2528 dprintf(fd, " Client priority score: %d state: %d\n",
2529 clientDescriptor->getPriority().getScore(),
2530 clientDescriptor->getPriority().getState());
2531 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
2532
2533 auto client = clientDescriptor->getValue();
2534 dprintf(fd, " Client package: %s\n",
2535 String8(client->getPackageName()).string());
2536
2537 client->dumpClient(fd, args);
2538 } else {
2539 dprintf(fd, " Device %s is closed, no client instance\n",
2540 cameraId.string());
2541 }
2542
2543 }
2544
2545 if (stateLocked) mCameraStatesLock.unlock();
2546
2547 if (locked) mServiceLock.unlock();
2548
2549 mCameraProviderManager->dump(fd, args);
2550
2551 dprintf(fd, "\n== Vendor tags: ==\n\n");
2552
2553 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
2554 if (desc == NULL) {
2555 sp<VendorTagDescriptorCache> cache =
2556 VendorTagDescriptorCache::getGlobalVendorTagCache();
2557 if (cache == NULL) {
2558 dprintf(fd, "No vendor tags.\n");
2559 } else {
2560 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
2561 }
2562 } else {
2563 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
2564 }
2565
2566 // Dump camera traces if there were any
2567 dprintf(fd, "\n");
2568 camera3::CameraTraces::dump(fd, args);
2569
2570 // Process dump arguments, if any
2571 int n = args.size();
2572 String16 verboseOption("-v");
2573 String16 unreachableOption("--unreachable");
2574 for (int i = 0; i < n; i++) {
2575 if (args[i] == verboseOption) {
2576 // change logging level
2577 if (i + 1 >= n) continue;
2578 String8 levelStr(args[i+1]);
2579 int level = atoi(levelStr.string());
2580 dprintf(fd, "\nSetting log level to %d.\n", level);
2581 setLogLevel(level);
2582 } else if (args[i] == unreachableOption) {
2583 // Dump memory analysis
2584 // TODO - should limit be an argument parameter?
2585 UnreachableMemoryInfo info;
2586 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
2587 if (!success) {
2588 dprintf(fd, "\n== Unable to dump unreachable memory. "
2589 "Try disabling SELinux enforcement. ==\n");
2590 } else {
2591 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
2592 std::string s = info.ToString(/*log_contents*/ true);
2593 write(fd, s.c_str(), s.size());
2594 }
2595 }
2596 }
2597 return NO_ERROR;
2598 }
2599
dumpEventLog(int fd)2600 void CameraService::dumpEventLog(int fd) {
2601 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
2602
2603 Mutex::Autolock l(mLogLock);
2604 for (const auto& msg : mEventLog) {
2605 dprintf(fd, " %s\n", msg.string());
2606 }
2607
2608 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
2609 dprintf(fd, " ...\n");
2610 } else if (mEventLog.size() == 0) {
2611 dprintf(fd, " [no events yet]\n");
2612 }
2613 dprintf(fd, "\n");
2614 }
2615
handleTorchClientBinderDied(const wp<IBinder> & who)2616 void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
2617 Mutex::Autolock al(mTorchClientMapMutex);
2618 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
2619 if (mTorchClientMap[i] == who) {
2620 // turn off the torch mode that was turned on by dead client
2621 String8 cameraId = mTorchClientMap.keyAt(i);
2622 status_t res = mFlashlight->setTorchMode(cameraId, false);
2623 if (res) {
2624 ALOGE("%s: torch client died but couldn't turn off torch: "
2625 "%s (%d)", __FUNCTION__, strerror(-res), res);
2626 return;
2627 }
2628 mTorchClientMap.removeItemsAt(i);
2629 break;
2630 }
2631 }
2632 }
2633
binderDied(const wp<IBinder> & who)2634 /*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
2635
2636 /**
2637 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
2638 * binder driver
2639 */
2640
2641 logClientDied(getCallingPid(), String8("Binder died unexpectedly"));
2642
2643 // check torch client
2644 handleTorchClientBinderDied(who);
2645
2646 // check camera device client
2647 if(!evictClientIdByRemote(who)) {
2648 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
2649 return;
2650 }
2651
2652 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
2653 __FUNCTION__);
2654 }
2655
updateStatus(StatusInternal status,const String8 & cameraId)2656 void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
2657 updateStatus(status, cameraId, {});
2658 }
2659
updateStatus(StatusInternal status,const String8 & cameraId,std::initializer_list<StatusInternal> rejectSourceStates)2660 void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
2661 std::initializer_list<StatusInternal> rejectSourceStates) {
2662 // Do not lock mServiceLock here or can get into a deadlock from
2663 // connect() -> disconnect -> updateStatus
2664
2665 auto state = getCameraState(cameraId);
2666
2667 if (state == nullptr) {
2668 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
2669 cameraId.string());
2670 return;
2671 }
2672
2673 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
2674 // of the listeners with both the mStatusStatus and mStatusListenerLock held
2675 state->updateStatus(status, cameraId, rejectSourceStates, [this]
2676 (const String8& cameraId, StatusInternal status) {
2677
2678 if (status != StatusInternal::ENUMERATING) {
2679 // Update torch status if it has a flash unit.
2680 Mutex::Autolock al(mTorchStatusMutex);
2681 TorchModeStatus torchStatus;
2682 if (getTorchStatusLocked(cameraId, &torchStatus) !=
2683 NAME_NOT_FOUND) {
2684 TorchModeStatus newTorchStatus =
2685 status == StatusInternal::PRESENT ?
2686 TorchModeStatus::AVAILABLE_OFF :
2687 TorchModeStatus::NOT_AVAILABLE;
2688 if (torchStatus != newTorchStatus) {
2689 onTorchStatusChangedLocked(cameraId, newTorchStatus);
2690 }
2691 }
2692 }
2693
2694 Mutex::Autolock lock(mStatusListenerLock);
2695
2696 for (auto& listener : mListenerList) {
2697 listener->onStatusChanged(mapToInterface(status), String16(cameraId));
2698 }
2699 });
2700 }
2701
2702 template<class Func>
updateStatus(StatusInternal status,const String8 & cameraId,std::initializer_list<StatusInternal> rejectSourceStates,Func onStatusUpdatedLocked)2703 void CameraService::CameraState::updateStatus(StatusInternal status,
2704 const String8& cameraId,
2705 std::initializer_list<StatusInternal> rejectSourceStates,
2706 Func onStatusUpdatedLocked) {
2707 Mutex::Autolock lock(mStatusLock);
2708 StatusInternal oldStatus = mStatus;
2709 mStatus = status;
2710
2711 if (oldStatus == status) {
2712 return;
2713 }
2714
2715 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
2716 cameraId.string(), oldStatus, status);
2717
2718 if (oldStatus == StatusInternal::NOT_PRESENT &&
2719 (status != StatusInternal::PRESENT &&
2720 status != StatusInternal::ENUMERATING)) {
2721
2722 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
2723 __FUNCTION__);
2724 mStatus = oldStatus;
2725 return;
2726 }
2727
2728 /**
2729 * Sometimes we want to conditionally do a transition.
2730 * For example if a client disconnects, we want to go to PRESENT
2731 * only if we weren't already in NOT_PRESENT or ENUMERATING.
2732 */
2733 for (auto& rejectStatus : rejectSourceStates) {
2734 if (oldStatus == rejectStatus) {
2735 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
2736 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
2737 mStatus = oldStatus;
2738 return;
2739 }
2740 }
2741
2742 onStatusUpdatedLocked(cameraId, status);
2743 }
2744
updateProxyDeviceState(int newState,const String8 & cameraId,int facing,const String16 & clientName)2745 void CameraService::updateProxyDeviceState(int newState,
2746 const String8& cameraId, int facing, const String16& clientName) {
2747 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
2748 if (proxyBinder == nullptr) return;
2749 String16 id(cameraId);
2750 proxyBinder->notifyCameraState(id, newState, facing, clientName);
2751 }
2752
getTorchStatusLocked(const String8 & cameraId,TorchModeStatus * status) const2753 status_t CameraService::getTorchStatusLocked(
2754 const String8& cameraId,
2755 TorchModeStatus *status) const {
2756 if (!status) {
2757 return BAD_VALUE;
2758 }
2759 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2760 if (index == NAME_NOT_FOUND) {
2761 // invalid camera ID or the camera doesn't have a flash unit
2762 return NAME_NOT_FOUND;
2763 }
2764
2765 *status = mTorchStatusMap.valueAt(index);
2766 return OK;
2767 }
2768
setTorchStatusLocked(const String8 & cameraId,TorchModeStatus status)2769 status_t CameraService::setTorchStatusLocked(const String8& cameraId,
2770 TorchModeStatus status) {
2771 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2772 if (index == NAME_NOT_FOUND) {
2773 return BAD_VALUE;
2774 }
2775 mTorchStatusMap.editValueAt(index) = status;
2776
2777 return OK;
2778 }
2779
2780 }; // namespace android
2781