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