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