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