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