blob: 5740038b0dac34086e876ff09da67e07608590b3 [file] [log] [blame]
Mathias Agopian65ab4712010-07-14 17:59:35 -07001/*
Ruben Brunkd1176ef2014-02-21 10:51:38 -08002 * 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 */
Mathias Agopian65ab4712010-07-14 17:59:35 -070016
17#define LOG_TAG "CameraService"
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -070018#define ATRACE_TAG ATRACE_TAG_CAMERA
Iliyan Malchev8951a972011-04-14 16:55:59 -070019//#define LOG_NDEBUG 0
Mathias Agopian65ab4712010-07-14 17:59:35 -070020
Ruben Brunkcc776712015-02-17 20:18:47 -080021#include <algorithm>
22#include <climits>
Mathias Agopian65ab4712010-07-14 17:59:35 -070023#include <stdio.h>
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -080024#include <cstdlib>
Ruben Brunkcc776712015-02-17 20:18:47 -080025#include <cstring>
26#include <ctime>
27#include <string>
Mathias Agopian65ab4712010-07-14 17:59:35 -070028#include <sys/types.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080029#include <inttypes.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070030#include <pthread.h>
Avichal Rakesh84147132021-11-11 17:47:11 -080031#include <poll.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070032
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080033#include <android/hardware/ICamera.h>
34#include <android/hardware/ICameraClient.h>
35
Alex Deymo9c2a2c22016-08-25 11:59:14 -070036#include <android-base/macros.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080037#include <android-base/parseint.h>
Jayant Chowdharyb61526c2019-05-13 19:37:42 -070038#include <android-base/stringprintf.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080039#include <binder/ActivityManager.h>
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -080040#include <binder/AppOpsManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070041#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070042#include <binder/MemoryBase.h>
43#include <binder/MemoryHeapBase.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080044#include <binder/PermissionController.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080045#include <binder/IResultReceiver.h>
Steven Moreland89a2c5c2020-01-31 15:02:25 -080046#include <binderthreadstate/CallerUtils.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070047#include <cutils/atomic.h>
Nipun Kwatrab5ca4612010-09-11 19:31:10 -070048#include <cutils/properties.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080049#include <cutils/misc.h>
Mathias Agopiandf712ea2012-02-25 18:48:35 -080050#include <gui/Surface.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070051#include <hardware/hardware.h>
Jayant Chowdharybe543d42018-08-15 13:16:14 -070052#include "hidl/HidlCameraService.h"
53#include <hidl/HidlTransportSupport.h>
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -080054#include <hwbinder/IPCThreadState.h>
Eino-Ville Talvalad89821e2016-04-20 11:23:50 -070055#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070056#include <media/AudioSystem.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080057#include <media/IMediaHTTPService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070058#include <media/mediaplayer.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070059#include <mediautils/BatteryNotifier.h>
Steven Moreland886d7322021-04-02 04:19:45 +000060#include <processinfo/ProcessInfoService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070061#include <utils/Errors.h>
62#include <utils/Log.h>
63#include <utils/String16.h>
Svet Ganov94ec46f2018-06-08 15:03:46 -070064#include <utils/SystemClock.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080065#include <utils/Trace.h>
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080066#include <utils/CallStack.h>
Chien-Yu Chen98a668f2015-12-18 14:10:33 -080067#include <private/android_filesystem_config.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080068#include <system/camera_vendor_tags.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070069#include <system/camera_metadata.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080070
Ruben Brunkb2119af2014-05-09 19:57:56 -070071#include <system/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070072
73#include "CameraService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070074#include "api1/Camera2Client.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070075#include "api2/CameraDeviceClient.h"
Igor Murashkinff3e31d2013-10-23 16:40:06 -070076#include "utils/CameraTraces.h"
Emilian Peevbd8c5032018-02-14 23:05:40 +000077#include "utils/TagMonitor.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070078#include "utils/CameraThreadState.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070079#include "utils/CameraServiceProxyWrapper.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070080
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080081namespace {
82 const char* kPermissionServiceName = "permission";
83}; // namespace anonymous
84
Mathias Agopian65ab4712010-07-14 17:59:35 -070085namespace android {
86
Jayant Chowdharyb61526c2019-05-13 19:37:42 -070087using base::StringPrintf;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080088using binder::Status;
Austin Borgerea931242021-12-13 23:10:41 +000089using namespace camera3;
Jayant Chowdharybe543d42018-08-15 13:16:14 -070090using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -080091using hardware::ICamera;
92using hardware::ICameraClient;
93using hardware::ICameraServiceListener;
Cliff Wud8cae102021-03-11 01:37:42 +080094using hardware::camera2::ICameraInjectionCallback;
95using hardware::camera2::ICameraInjectionSession;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080096using hardware::camera2::utils::CameraIdAndSessionConfiguration;
97using hardware::camera2::utils::ConcurrentCameraIdCombination;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080098
Mathias Agopian65ab4712010-07-14 17:59:35 -070099// ----------------------------------------------------------------------------
100// Logging support -- this is for debugging only
101// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700102volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700103
Steve Blockb8a80522011-12-20 16:23:08 +0000104#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
105#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700106
107static void setLogLevel(int level) {
108 android_atomic_write(level, &gLogLevel);
109}
110
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800111// Convenience methods for constructing binder::Status objects for error returns
112
113#define STATUS_ERROR(errorCode, errorString) \
114 binder::Status::fromServiceSpecificError(errorCode, \
115 String8::format("%s:%d: %s", __FUNCTION__, __LINE__, errorString))
116
117#define STATUS_ERROR_FMT(errorCode, errorString, ...) \
118 binder::Status::fromServiceSpecificError(errorCode, \
119 String8::format("%s:%d: " errorString, __FUNCTION__, __LINE__, \
120 __VA_ARGS__))
121
Mathias Agopian65ab4712010-07-14 17:59:35 -0700122// ----------------------------------------------------------------------------
123
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700124static const String16 sDumpPermission("android.permission.DUMP");
Svet Ganova453d0d2018-01-11 15:37:58 -0800125static const String16 sManageCameraPermission("android.permission.MANAGE_CAMERA");
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700126static const String16 sCameraPermission("android.permission.CAMERA");
127static const String16 sSystemCameraPermission("android.permission.SYSTEM_CAMERA");
128static const String16
129 sCameraSendSystemEventsPermission("android.permission.CAMERA_SEND_SYSTEM_EVENTS");
Shuzhen Wang695044d2020-03-06 09:02:23 -0800130static const String16 sCameraOpenCloseListenerPermission(
131 "android.permission.CAMERA_OPEN_CLOSE_LISTENER");
Cliff Wud8cae102021-03-11 01:37:42 +0800132static const String16
133 sCameraInjectExternalCameraPermission("android.permission.CAMERA_INJECT_EXTERNAL_CAMERA");
Rucha Katakwardf223072021-06-15 10:21:00 -0700134const char *sFileName = "lastOpenSessionDumpFile";
Eino-Ville Talvala7c602c32021-03-20 17:00:18 -0700135static constexpr int32_t kVendorClientScore = resource_policy::PERCEPTIBLE_APP_ADJ;
136static constexpr int32_t kVendorClientState = ActivityManager::PROCESS_STATE_PERSISTENT_UI;
137
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800138const String8 CameraService::kOfflineDevice("offline-");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -0700139const String16 CameraService::kWatchAllClientsFlag("all");
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700140
Rucha Katakward9ea6452021-05-06 11:57:16 -0700141// Set to keep track of logged service error events.
142static std::set<String8> sServiceErrorEventSet;
143
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800144CameraService::CameraService() :
145 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800146 mNumberOfCameras(0),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700147 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700148 mSoundRef(0), mInitialized(false),
149 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000150 ALOGI("CameraService started (pid=%d)", getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800151 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Rucha Katakwardf223072021-06-15 10:21:00 -0700152 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
153 if (mMemFd == -1) {
154 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
155 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700156}
157
Iliyan Malchev8951a972011-04-14 16:55:59 -0700158void CameraService::onFirstRef()
159{
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -0700160
Ruben Brunkcc776712015-02-17 20:18:47 -0800161 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800162
Iliyan Malchev8951a972011-04-14 16:55:59 -0700163 BnCameraService::onFirstRef();
164
Ruben Brunk99e69712015-05-26 17:25:07 -0700165 // Update battery life tracking if service is restarting
166 BatteryNotifier& notifier(BatteryNotifier::getInstance());
167 notifier.noteResetCamera();
168 notifier.noteResetFlashlight();
169
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800170 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800171
Emilian Peevf53f66e2017-04-11 14:29:43 +0100172 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800173 if (res == OK) {
174 mInitialized = true;
175 }
176
Svet Ganova453d0d2018-01-11 15:37:58 -0800177 mUidPolicy = new UidPolicy(this);
178 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800179 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
180 mSensorPrivacyPolicy->registerSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800181 mInjectionStatusListener = new InjectionStatusListener(this);
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700182 mAppOps.setCameraAudioRestriction(mAudioRestriction);
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700183 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
184 if (hcs->registerAsService() != android::OK) {
185 ALOGE("%s: Failed to register default android.frameworks.cameraservice.service@1.0",
186 __FUNCTION__);
187 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700188
189 // This needs to be last call in this function, so that it's as close to
190 // ServiceManager::addService() as possible.
Shuzhen Wang316781a2020-08-18 18:11:01 -0700191 CameraServiceProxyWrapper::pingCameraServiceProxy();
Shuzhen Wang24b44152019-09-20 10:38:11 -0700192 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800193}
194
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800195status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800196 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100197
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800198 std::vector<std::string> deviceIds;
199 {
200 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800201
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800202 if (nullptr == mCameraProviderManager.get()) {
203 mCameraProviderManager = new CameraProviderManager();
204 res = mCameraProviderManager->initialize(this);
205 if (res != OK) {
206 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
207 __FUNCTION__, strerror(-res), res);
Rucha Katakward9ea6452021-05-06 11:57:16 -0700208 logServiceError(String8::format("Unable to initialize camera provider manager"),
209 ERROR_DISCONNECTED);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800210 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100211 }
212 }
213
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800214
215 // Setup vendor tags before we call get_camera_info the first time
216 // because HAL might need to setup static vendor keys in get_camera_info
217 // TODO: maybe put this into CameraProviderManager::initialize()?
218 mCameraProviderManager->setUpVendorTags();
219
220 if (nullptr == mFlashlight.get()) {
221 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700222 }
223
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800224 res = mFlashlight->findFlashUnits();
225 if (res != OK) {
226 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
227 }
228
229 deviceIds = mCameraProviderManager->getCameraDeviceIds();
230 }
231
232
233 for (auto& cameraId : deviceIds) {
234 String8 id8 = String8(cameraId.c_str());
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800235 if (getCameraState(id8) == nullptr) {
236 onDeviceStatusChanged(id8, CameraDeviceStatus::PRESENT);
237 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800238 }
239
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700240 // Derive primary rear/front cameras, and filter their charactierstics.
241 // This needs to be done after all cameras are enumerated and camera ids are sorted.
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700242 if (SessionConfigurationUtils::IS_PERF_CLASS) {
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700243 // Assume internal cameras are advertised from the same
244 // provider. If multiple providers are registered at different time,
245 // and each provider contains multiple internal color cameras, the current
246 // logic may filter the characteristics of more than one front/rear color
247 // cameras.
248 Mutex::Autolock l(mServiceLock);
249 filterSPerfClassCharacteristicsLocked();
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700250 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700251
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800252 return OK;
253}
254
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700255void CameraService::broadcastTorchModeStatus(const String8& cameraId, TorchModeStatus status,
256 SystemCameraKind systemCameraKind) {
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800257 Mutex::Autolock lock(mStatusListenerLock);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800258 for (auto& i : mListenerList) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700259 if (shouldSkipStatusUpdates(systemCameraKind, i->isVendorListener(), i->getListenerPid(),
260 i->getListenerUid())) {
261 ALOGV("Skipping torch callback for system-only camera device %s",
262 cameraId.c_str());
263 continue;
264 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700265 i->getListener()->onTorchStatusChanged(mapToInterface(status), String16{cameraId});
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800266 }
267}
268
Mathias Agopian65ab4712010-07-14 17:59:35 -0700269CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800270 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800271 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800272 mSensorPrivacyPolicy->unregisterSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800273 mInjectionStatusListener->removeListener();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700274}
275
Emilian Peevaee727d2017-05-04 16:35:48 +0100276void CameraService::onNewProviderRegistered() {
277 enumerateProviders();
278}
279
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700280void CameraService::filterAPI1SystemCameraLocked(
281 const std::vector<std::string> &normalDeviceIds) {
282 mNormalDeviceIdsWithoutSystemCamera.clear();
283 for (auto &deviceId : normalDeviceIds) {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700284 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
285 if (getSystemCameraKind(String8(deviceId.c_str()), &deviceKind) != OK) {
286 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, deviceId.c_str());
287 continue;
288 }
289 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700290 // All system camera ids will necessarily come after public camera
291 // device ids as per the HAL interface contract.
292 break;
293 }
294 mNormalDeviceIdsWithoutSystemCamera.push_back(deviceId);
295 }
296 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
297 mNormalDeviceIdsWithoutSystemCamera.size());
298}
299
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700300status_t CameraService::getSystemCameraKind(const String8& cameraId, SystemCameraKind *kind) const {
301 auto state = getCameraState(cameraId);
302 if (state != nullptr) {
303 *kind = state->getSystemCameraKind();
304 return OK;
305 }
306 // Hidden physical camera ids won't have CameraState
307 return mCameraProviderManager->getSystemCameraKind(cameraId.c_str(), kind);
308}
309
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800310void CameraService::updateCameraNumAndIds() {
311 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700312 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
313 // Excludes hidden secure cameras
314 mNumberOfCameras =
315 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
316 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800317 mNormalDeviceIds =
318 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700319 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800320}
321
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700322void CameraService::filterSPerfClassCharacteristicsLocked() {
Shuzhen Wang89db2992021-05-20 13:09:48 -0700323 // To claim to be S Performance primary cameras, the cameras must be
324 // backward compatible. So performance class primary camera Ids must be API1
325 // compatible.
326 bool firstRearCameraSeen = false, firstFrontCameraSeen = false;
327 for (const auto& cameraId : mNormalDeviceIdsWithoutSystemCamera) {
328 int facing = -1;
329 int orientation = 0;
330 String8 cameraId8(cameraId.c_str());
331 getDeviceVersion(cameraId8, /*out*/&facing, /*out*/&orientation);
332 if (facing == -1) {
333 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
334 return;
335 }
336
337 if ((facing == hardware::CAMERA_FACING_BACK && !firstRearCameraSeen) ||
338 (facing == hardware::CAMERA_FACING_FRONT && !firstFrontCameraSeen)) {
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700339 status_t res = mCameraProviderManager->filterSmallJpegSizes(cameraId);
340 if (res == OK) {
341 mPerfClassPrimaryCameraIds.insert(cameraId);
342 } else {
343 ALOGE("%s: Failed to filter small JPEG sizes for performance class primary "
344 "camera %s: %s(%d)", __FUNCTION__, cameraId.c_str(), strerror(-res), res);
345 break;
346 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700347
348 if (facing == hardware::CAMERA_FACING_BACK) {
349 firstRearCameraSeen = true;
350 }
351 if (facing == hardware::CAMERA_FACING_FRONT) {
352 firstFrontCameraSeen = true;
353 }
354 }
355
356 if (firstRearCameraSeen && firstFrontCameraSeen) {
357 break;
358 }
359 }
360}
361
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100362void CameraService::addStates(const String8 id) {
363 std::string cameraId(id.c_str());
Jayant Chowdhary0bd38522021-11-05 17:49:27 -0700364 CameraResourceCost cost;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100365 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
366 if (res != OK) {
367 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
368 return;
369 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000370 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700371 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
372 if (res != OK) {
373 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
374 return;
375 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000376 std::vector<std::string> physicalCameraIds;
377 mCameraProviderManager->isLogicalCamera(cameraId, &physicalCameraIds);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100378 std::set<String8> conflicting;
379 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
380 conflicting.emplace(String8(cost.conflictingDevices[i].c_str()));
381 }
382
383 {
384 Mutex::Autolock lock(mCameraStatesLock);
385 mCameraStates.emplace(id, std::make_shared<CameraState>(id, cost.resourceCost,
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000386 conflicting, deviceKind, physicalCameraIds));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100387 }
388
389 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100390 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100391 mTorchStatusMap.add(id, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800392
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700393 broadcastTorchModeStatus(id, TorchModeStatus::AVAILABLE_OFF, deviceKind);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100394 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800395
396 updateCameraNumAndIds();
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100397 logDeviceAdded(id, "Device added");
398}
399
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100400void CameraService::removeStates(const String8 id) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800401 updateCameraNumAndIds();
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100402 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100403 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100404 mTorchStatusMap.removeItem(id);
405 }
406
407 {
408 Mutex::Autolock lock(mCameraStatesLock);
409 mCameraStates.erase(id);
410 }
411}
412
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800413void CameraService::onDeviceStatusChanged(const String8& id,
414 CameraDeviceStatus newHalStatus) {
415 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
416 id.string(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700417
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800418 StatusInternal newStatus = mapToInternal(newHalStatus);
419
Ruben Brunkcc776712015-02-17 20:18:47 -0800420 std::shared_ptr<CameraState> state = getCameraState(id);
421
422 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700423 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100424 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700425 __FUNCTION__, id.string());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100426
427 // First add as absent to make sure clients are notified below
428 addStates(id);
429
430 updateStatus(newStatus, id);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700431 } else {
432 ALOGE("%s: Bad camera ID %s", __FUNCTION__, id.string());
433 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700434 return;
435 }
436
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800437 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800438
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800439 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800440 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700441 return;
442 }
443
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800444 if (newStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700445 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
446 newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800447
448 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
449 // to this device until the status changes
450 updateStatus(StatusInternal::NOT_PRESENT, id);
451
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800452 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700453 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800454 // Don't do this in updateStatus to avoid deadlock over mServiceLock
455 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700456
Ruben Brunkcc776712015-02-17 20:18:47 -0800457 // Remove cached shim parameters
458 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700459
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800460 // Remove online as well as offline client from the list of active clients,
461 // if they are present
462 clientToDisconnectOnline = removeClientLocked(id);
463 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + id);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700464 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800465
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800466 disconnectClient(id, clientToDisconnectOnline);
467 disconnectClient(kOfflineDevice + id, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700468
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100469 removeStates(id);
Ruben Brunkcc776712015-02-17 20:18:47 -0800470 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800471 if (oldStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700472 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
473 newStatus));
474 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800475 updateStatus(newStatus, id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700476 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800477}
Igor Murashkincba2c162013-03-20 15:56:31 -0700478
Shuzhen Wang43858162020-01-10 13:42:15 -0800479void CameraService::onDeviceStatusChanged(const String8& id,
480 const String8& physicalId,
481 CameraDeviceStatus newHalStatus) {
482 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
483 __FUNCTION__, id.string(), physicalId.string(), newHalStatus);
484
485 StatusInternal newStatus = mapToInternal(newHalStatus);
486
487 std::shared_ptr<CameraState> state = getCameraState(id);
488
489 if (state == nullptr) {
490 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
491 __FUNCTION__, id.string(), physicalId.string());
492 return;
493 }
494
495 StatusInternal logicalCameraStatus = state->getStatus();
496 if (logicalCameraStatus != StatusInternal::PRESENT &&
497 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
498 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
499 __FUNCTION__, physicalId.string(), newHalStatus, logicalCameraStatus);
500 return;
501 }
502
503 bool updated = false;
504 if (newStatus == StatusInternal::PRESENT) {
505 updated = state->removeUnavailablePhysicalId(physicalId);
506 } else {
507 updated = state->addUnavailablePhysicalId(physicalId);
508 }
509
510 if (updated) {
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800511 String8 idCombo = id + " : " + physicalId;
512 if (newStatus == StatusInternal::PRESENT) {
513 logDeviceAdded(idCombo,
514 String8::format("Device status changed to %d", newStatus));
515 } else {
516 logDeviceRemoved(idCombo,
517 String8::format("Device status changed to %d", newStatus));
518 }
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700519 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
520 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
521 if (getSystemCameraKind(id, &deviceKind) != OK) {
522 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.string());
523 return;
524 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800525 String16 id16(id), physicalId16(physicalId);
526 Mutex::Autolock lock(mStatusListenerLock);
527 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700528 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
529 listener->getListenerPid(), listener->getListenerUid())) {
530 ALOGV("Skipping discovery callback for system-only camera device %s",
531 id.c_str());
532 continue;
533 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800534 listener->getListener()->onPhysicalCameraStatusChanged(mapToInterface(newStatus),
535 id16, physicalId16);
536 }
537 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700538}
539
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800540void CameraService::disconnectClient(const String8& id, sp<BasicClient> clientToDisconnect) {
541 if (clientToDisconnect.get() != nullptr) {
542 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
543 __FUNCTION__, id.string());
544 // Notify the client of disconnection
545 clientToDisconnect->notifyError(
546 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
547 CaptureResultExtras{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800548 clientToDisconnect->disconnect();
549 }
550}
551
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800552void CameraService::onTorchStatusChanged(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800553 TorchModeStatus newStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700554 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
555 status_t res = getSystemCameraKind(cameraId, &systemCameraKind);
556 if (res != OK) {
557 ALOGE("%s: Could not get system camera kind for camera id %s", __FUNCTION__,
558 cameraId.string());
559 return;
560 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800561 Mutex::Autolock al(mTorchStatusMutex);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700562 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800563}
564
Jayant Chowdhary46ef0f52021-10-05 14:36:13 -0700565
566void CameraService::onTorchStatusChanged(const String8& cameraId,
567 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
568 Mutex::Autolock al(mTorchStatusMutex);
569 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
570}
571
Rucha Katakwar38284522021-11-10 11:25:21 -0800572void CameraService::broadcastTorchStrengthLevel(const String8& cameraId,
573 int32_t newStrengthLevel) {
574 Mutex::Autolock lock(mStatusListenerLock);
575 for (auto& i : mListenerList) {
576 i->getListener()->onTorchStrengthLevelChanged(String16{cameraId},
577 newStrengthLevel);
578 }
579}
580
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800581void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700582 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800583 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
584 __FUNCTION__, cameraId.string(), newStatus);
585
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800586 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800587 status_t res = getTorchStatusLocked(cameraId, &status);
588 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700589 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
590 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800591 return;
592 }
593 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800594 return;
595 }
596
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800597 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800598 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800599 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
600 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800601 return;
602 }
603
Ruben Brunkcc776712015-02-17 20:18:47 -0800604 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700605 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700606 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700607 auto iter = mTorchUidMap.find(cameraId);
608 if (iter != mTorchUidMap.end()) {
609 int oldUid = iter->second.second;
610 int newUid = iter->second.first;
611 BatteryNotifier& notifier(BatteryNotifier::getInstance());
612 if (oldUid != newUid) {
613 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800614 if (status == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700615 notifier.noteFlashlightOff(cameraId, oldUid);
616 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800617 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700618 notifier.noteFlashlightOn(cameraId, newUid);
619 }
620 iter->second.second = newUid;
621 } else {
622 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800623 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700624 notifier.noteFlashlightOn(cameraId, oldUid);
625 } else {
626 notifier.noteFlashlightOff(cameraId, oldUid);
627 }
628 }
629 }
630 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700631 broadcastTorchModeStatus(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800632}
633
Jayant Chowdharyc3198c32021-07-28 20:59:14 +0000634static bool hasPermissionsForSystemCamera(int callingPid, int callingUid,
635 bool logPermissionFailure = false) {
636 return checkPermission(sSystemCameraPermission, callingPid, callingUid,
637 logPermissionFailure) &&
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700638 checkPermission(sCameraPermission, callingPid, callingUid);
639}
640
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800641Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700642 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100643 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700644 bool hasSystemCameraPermissions =
645 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
646 CameraThreadState::getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700647 switch (type) {
648 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700649 if (hasSystemCameraPermissions) {
650 *numCameras = static_cast<int>(mNormalDeviceIds.size());
651 } else {
652 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
653 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800654 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700655 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700656 if (hasSystemCameraPermissions) {
657 *numCameras = mNumberOfCameras;
658 } else {
659 *numCameras = mNumberOfCamerasWithoutSystemCamera;
660 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800661 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700662 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800663 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700664 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800665 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
666 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700667 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800668 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700669}
670
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800671Status CameraService::getCameraInfo(int cameraId,
672 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700673 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100674 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700675 std::string cameraIdStr = cameraIdIntToStrLocked(cameraId);
676 if (shouldRejectSystemCameraConnection(String8(cameraIdStr.c_str()))) {
677 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
678 "characteristics for system only device %s: ", cameraIdStr.c_str());
679 }
Emilian Peevaee727d2017-05-04 16:35:48 +0100680
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800681 if (!mInitialized) {
Rucha Katakward9ea6452021-05-06 11:57:16 -0700682 logServiceError(String8::format("Camera subsystem is not available"),ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800683 return STATUS_ERROR(ERROR_DISCONNECTED,
684 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -0700685 }
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700686 bool hasSystemCameraPermissions =
687 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
688 CameraThreadState::getCallingUid());
689 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
690 if (hasSystemCameraPermissions) {
691 cameraIdBound = mNumberOfCameras;
692 }
693 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800694 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
695 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700696 }
697
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800698 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800699 status_t err = mCameraProviderManager->getCameraInfo(
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700700 cameraIdStr.c_str(), cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100701 if (err != OK) {
702 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
703 "Error retrieving camera info from device %d: %s (%d)", cameraId,
704 strerror(-err), err);
Rucha Katakward9ea6452021-05-06 11:57:16 -0700705 logServiceError(String8::format("Error retrieving camera info from device %d",cameraId),
706 ERROR_INVALID_OPERATION);
Ruben Brunkcc776712015-02-17 20:18:47 -0800707 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100708
Ruben Brunkcc776712015-02-17 20:18:47 -0800709 return ret;
710}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700711
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800712std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700713 const std::vector<std::string> *deviceIds = &mNormalDeviceIdsWithoutSystemCamera;
714 auto callingPid = CameraThreadState::getCallingPid();
715 auto callingUid = CameraThreadState::getCallingUid();
Jayant Chowdharyc3198c32021-07-28 20:59:14 +0000716 if (checkPermission(sSystemCameraPermission, callingPid, callingUid,
717 /*logPermissionFailure*/false) || getpid() == callingPid) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700718 deviceIds = &mNormalDeviceIds;
719 }
720 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(deviceIds->size())) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800721 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700722 __FUNCTION__, cameraIdInt, deviceIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800723 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800724 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800725
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700726 return (*deviceIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800727}
728
729String8 CameraService::cameraIdIntToStr(int cameraIdInt) {
730 Mutex::Autolock lock(mServiceLock);
731 return String8(cameraIdIntToStrLocked(cameraIdInt).c_str());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800732}
733
734Status CameraService::getCameraCharacteristics(const String16& cameraId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700735 int targetSdkVersion, CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700736 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700737 if (!cameraInfo) {
738 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800739 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -0700740 }
741
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800742 if (!mInitialized) {
743 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Rucha Katakward9ea6452021-05-06 11:57:16 -0700744 logServiceError(String8::format("Camera subsystem is not available"),ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800745 return STATUS_ERROR(ERROR_DISCONNECTED,
746 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -0700747 }
748
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700749 if (shouldRejectSystemCameraConnection(String8(cameraId))) {
750 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
751 "characteristics for system only device %s: ", String8(cameraId).string());
752 }
753
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800754 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800755
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700756
757 std::string cameraIdStr = String8(cameraId).string();
758 bool overrideForPerfClass =
759 SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
760 cameraIdStr, targetSdkVersion);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100761 status_t res = mCameraProviderManager->getCameraCharacteristics(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700762 cameraIdStr, overrideForPerfClass, cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100763 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700764 if (res == NAME_NOT_FOUND) {
765 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
766 "characteristics for unknown device %s: %s (%d)", String8(cameraId).string(),
767 strerror(-res), res);
768 } else {
Rucha Katakward9ea6452021-05-06 11:57:16 -0700769 logServiceError(String8::format("Unable to retrieve camera characteristics for "
770 "device %s.", String8(cameraId).string()),ERROR_INVALID_OPERATION);
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700771 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
772 "characteristics for device %s: %s (%d)", String8(cameraId).string(),
773 strerror(-res), res);
774 }
Ruben Brunkb2119af2014-05-09 19:57:56 -0700775 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700776 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
777 if (getSystemCameraKind(String8(cameraId), &deviceKind) != OK) {
778 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, String8(cameraId).string());
779 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera kind "
780 "for device %s", String8(cameraId).string());
781 }
Jayant Chowdhary12361932018-08-27 14:46:13 -0700782 int callingPid = CameraThreadState::getCallingPid();
783 int callingUid = CameraThreadState::getCallingUid();
Emilian Peeve20c6372018-08-14 18:45:53 +0100784 std::vector<int32_t> tagsRemoved;
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700785 // If it's not calling from cameraserver, check the permission only if
786 // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
787 // it would've already been checked in shouldRejectSystemCameraConnection.
Emilian Peeve20c6372018-08-14 18:45:53 +0100788 if ((callingPid != getpid()) &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700789 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700790 !checkPermission(sCameraPermission, callingPid, callingUid)) {
Emilian Peeve20c6372018-08-14 18:45:53 +0100791 res = cameraInfo->removePermissionEntries(
792 mCameraProviderManager->getProviderTagIdLocked(String8(cameraId).string()),
793 &tagsRemoved);
794 if (res != OK) {
795 cameraInfo->clear();
796 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
797 " characteristics needing camera permission for device %s: %s (%d)",
798 String8(cameraId).string(), strerror(-res), res);
799 }
800 }
801
802 if (!tagsRemoved.empty()) {
803 res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
804 tagsRemoved.data(), tagsRemoved.size());
805 if (res != OK) {
806 cameraInfo->clear();
807 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
808 "keys needing permission for device %s: %s (%d)", String8(cameraId).string(),
809 strerror(-res), res);
810 }
811 }
812
Zhijun He2b59be82013-09-25 10:14:30 -0700813 return ret;
814}
815
Rucha Katakwar38284522021-11-10 11:25:21 -0800816Status CameraService::getTorchStrengthLevel(const String16& cameraId,
817 int32_t* torchStrength) {
818 ATRACE_CALL();
819 Mutex::Autolock l(mServiceLock);
820 if (!mInitialized) {
821 ALOGE("%s: Camera HAL couldn't be initialized.", __FUNCTION__);
822 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera HAL couldn't be initialized.");
823 }
824
825 if(torchStrength == NULL) {
826 ALOGE("%s: strength level must not be null.", __FUNCTION__);
827 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Strength level should not be null.");
828 }
829
830 status_t res = mCameraProviderManager->getTorchStrengthLevel(String8(cameraId).string(),
831 torchStrength);
832 if (res != OK) {
833 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve torch "
834 "strength level for device %s: %s (%d)", String8(cameraId).string(),
835 strerror(-res), res);
836 }
837 ALOGI("%s: Torch strength level is: %d", __FUNCTION__, *torchStrength);
838 return Status::ok();
839}
840
Ruben Brunkcc776712015-02-17 20:18:47 -0800841String8 CameraService::getFormattedCurrentTime() {
842 time_t now = time(nullptr);
843 char formattedTime[64];
844 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
845 return String8(formattedTime);
846}
847
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800848Status CameraService::getCameraVendorTagDescriptor(
849 /*out*/
850 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700851 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800852 if (!mInitialized) {
853 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800854 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800855 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -0800856 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
857 if (globalDescriptor != nullptr) {
858 *desc = *(globalDescriptor.get());
859 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800860 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800861}
862
Emilian Peev71c73a22017-03-21 16:35:51 +0000863Status CameraService::getCameraVendorTagCache(
864 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
865 ATRACE_CALL();
866 if (!mInitialized) {
867 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
868 return STATUS_ERROR(ERROR_DISCONNECTED,
869 "Camera subsystem not available");
870 }
871 sp<VendorTagDescriptorCache> globalCache =
872 VendorTagDescriptorCache::getGlobalVendorTagCache();
873 if (globalCache != nullptr) {
874 *cache = *(globalCache.get());
875 }
876 return Status::ok();
877}
878
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -0700879void CameraService::clearCachedVariables() {
880 BasicClient::BasicClient::sCameraService = nullptr;
881}
882
Emilian Peevb91f1802021-03-23 14:50:28 -0700883int CameraService::getDeviceVersion(const String8& cameraId, int* facing, int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700884 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800885
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800886 int deviceVersion = 0;
887
Emilian Peevf53f66e2017-04-11 14:29:43 +0100888 status_t res;
889 hardware::hidl_version maxVersion{0,0};
890 res = mCameraProviderManager->getHighestSupportedVersion(cameraId.string(),
891 &maxVersion);
892 if (res != OK) return -1;
893 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800894
Emilian Peevf53f66e2017-04-11 14:29:43 +0100895 hardware::CameraInfo info;
896 if (facing) {
897 res = mCameraProviderManager->getCameraInfo(cameraId.string(), &info);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -0800898 if (res != OK) return -1;
Emilian Peevf53f66e2017-04-11 14:29:43 +0100899 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -0700900 if (orientation) {
901 *orientation = info.orientation;
902 }
Igor Murashkin634a5152013-02-20 17:15:11 -0800903 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100904
Igor Murashkin634a5152013-02-20 17:15:11 -0800905 return deviceVersion;
906}
907
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800908Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700909 switch(err) {
910 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800911 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800912 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800913 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
914 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800915 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800916 return STATUS_ERROR(ERROR_DISCONNECTED,
917 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700918 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800919 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
920 "Camera HAL encountered error %d: %s",
921 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700922 }
Igor Murashkinbfc99152013-02-27 12:55:20 -0800923}
924
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800925Status CameraService::makeClient(const sp<CameraService>& cameraService,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800926 const sp<IInterface>& cameraCb, const String16& packageName,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700927 const std::optional<String16>& featureId, const String8& cameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -0700928 int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700929 int servicePid, int deviceVersion, apiLevel effectiveApiLevel, bool overrideForPerfClass,
Ruben Brunkcc776712015-02-17 20:18:47 -0800930 /*out*/sp<BasicClient>* client) {
931
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700932 // Create CameraClient based on device version reported by the HAL.
933 switch(deviceVersion) {
934 case CAMERA_DEVICE_API_VERSION_1_0:
935 ALOGE("Camera using old HAL version: %d", deviceVersion);
936 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
937 "Camera device \"%s\" HAL version %d no longer supported",
938 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800939 break;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700940 case CAMERA_DEVICE_API_VERSION_3_0:
941 case CAMERA_DEVICE_API_VERSION_3_1:
942 case CAMERA_DEVICE_API_VERSION_3_2:
943 case CAMERA_DEVICE_API_VERSION_3_3:
944 case CAMERA_DEVICE_API_VERSION_3_4:
945 case CAMERA_DEVICE_API_VERSION_3_5:
946 case CAMERA_DEVICE_API_VERSION_3_6:
Shuzhen Wang83bff122020-11-20 15:51:39 -0800947 case CAMERA_DEVICE_API_VERSION_3_7:
Shuzhen Wang90708ea2021-11-04 11:40:49 -0700948 case CAMERA_DEVICE_API_VERSION_3_8:
Ruben Brunkcc776712015-02-17 20:18:47 -0800949 if (effectiveApiLevel == API_1) { // Camera1 API route
950 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800951 *client = new Camera2Client(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800952 cameraId, api1CameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -0700953 facing, sensorOrientation, clientPid, clientUid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700954 servicePid, overrideForPerfClass);
Ruben Brunkcc776712015-02-17 20:18:47 -0800955 } else { // Camera2 API route
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800956 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
957 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800958 *client = new CameraDeviceClient(cameraService, tmp, packageName, featureId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700959 cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid,
960 overrideForPerfClass);
Ruben Brunkcc776712015-02-17 20:18:47 -0800961 }
962 break;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700963 default:
Ruben Brunkcc776712015-02-17 20:18:47 -0800964 // Should not be reachable
965 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800966 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800967 "Camera device \"%s\" has unknown HAL version %d",
968 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800969 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800970 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800971}
972
Ruben Brunk6267b532015-04-30 17:44:07 -0700973String8 CameraService::toString(std::set<userid_t> intSet) {
974 String8 s("");
975 bool first = true;
976 for (userid_t i : intSet) {
977 if (first) {
978 s.appendFormat("%d", i);
979 first = false;
980 } else {
981 s.appendFormat(", %d", i);
982 }
983 }
984 return s;
985}
986
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800987int32_t CameraService::mapToInterface(TorchModeStatus status) {
988 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
989 switch (status) {
990 case TorchModeStatus::NOT_AVAILABLE:
991 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
992 break;
993 case TorchModeStatus::AVAILABLE_OFF:
994 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
995 break;
996 case TorchModeStatus::AVAILABLE_ON:
997 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
998 break;
999 default:
1000 ALOGW("Unknown new flash status: %d", status);
1001 }
1002 return serviceStatus;
1003}
1004
1005CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
1006 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
1007 switch (status) {
1008 case CameraDeviceStatus::NOT_PRESENT:
1009 serviceStatus = StatusInternal::NOT_PRESENT;
1010 break;
1011 case CameraDeviceStatus::PRESENT:
1012 serviceStatus = StatusInternal::PRESENT;
1013 break;
1014 case CameraDeviceStatus::ENUMERATING:
1015 serviceStatus = StatusInternal::ENUMERATING;
1016 break;
1017 default:
1018 ALOGW("Unknown new HAL device status: %d", status);
1019 }
1020 return serviceStatus;
1021}
1022
1023int32_t CameraService::mapToInterface(StatusInternal status) {
1024 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1025 switch (status) {
1026 case StatusInternal::NOT_PRESENT:
1027 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1028 break;
1029 case StatusInternal::PRESENT:
1030 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
1031 break;
1032 case StatusInternal::ENUMERATING:
1033 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
1034 break;
1035 case StatusInternal::NOT_AVAILABLE:
1036 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
1037 break;
1038 case StatusInternal::UNKNOWN:
1039 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
1040 break;
1041 default:
1042 ALOGW("Unknown new internal device status: %d", status);
1043 }
1044 return serviceStatus;
1045}
1046
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001047Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001048 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -07001049
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001050 String16 internalPackageName("cameraserver");
Ruben Brunkcc776712015-02-17 20:18:47 -08001051 String8 id = String8::format("%d", cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001052 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001053 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001054 if (!(ret = connectHelper<ICameraClient,Client>(
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001055 sp<ICameraClient>{nullptr}, id, cameraId,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001056 internalPackageName, {}, uid, USE_CALLING_PID,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001057 API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0,
1058 /*targetSdkVersion*/ __ANDROID_API_FUTURE__, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001059 ).isOk()) {
1060 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
Ruben Brunkb2119af2014-05-09 19:57:56 -07001061 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001062 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001063}
1064
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001065Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -07001066 /*out*/
1067 CameraParameters* parameters) {
1068
1069 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1070
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001071 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001072
1073 if (parameters == NULL) {
1074 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001075 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001076 }
1077
Ruben Brunkcc776712015-02-17 20:18:47 -08001078 String8 id = String8::format("%d", cameraId);
1079
1080 // Check if we already have parameters
1081 {
1082 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001083 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001084 auto cameraState = getCameraState(id);
1085 if (cameraState == nullptr) {
1086 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001087 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1088 "Invalid camera ID: %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001089 }
1090 CameraParameters p = cameraState->getShimParams();
1091 if (!p.isEmpty()) {
1092 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001093 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001094 }
1095 }
1096
Jayant Chowdhary12361932018-08-27 14:46:13 -07001097 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001098 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001099 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001100 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001101 // Error already logged by callee
1102 return ret;
1103 }
1104
1105 // Check for parameters again
1106 {
1107 // Scope for service lock
1108 Mutex::Autolock lock(mServiceLock);
1109 auto cameraState = getCameraState(id);
1110 if (cameraState == nullptr) {
1111 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001112 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1113 "Invalid camera ID: %s", id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001114 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001115 CameraParameters p = cameraState->getShimParams();
1116 if (!p.isEmpty()) {
1117 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001118 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001119 }
1120 }
1121
Ruben Brunkcc776712015-02-17 20:18:47 -08001122 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1123 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001124 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001125}
1126
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001127// Can camera service trust the caller based on the calling UID?
1128static bool isTrustedCallingUid(uid_t uid) {
1129 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001130 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001131 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001132 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001133 return true;
1134 default:
1135 return false;
1136 }
1137}
1138
Nicholas Sauera3620332019-04-03 14:05:17 -07001139static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1140 PermissionController pc;
1141 uid = pc.getPackageUid(packageName, 0);
1142 if (uid <= 0) {
1143 ALOGE("Unknown package: '%s'", String8(packageName).string());
1144 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
1145 return BAD_VALUE;
1146 }
1147
1148 if (userId < 0) {
1149 ALOGE("Invalid user: %d", userId);
1150 dprintf(err, "Invalid user: %d\n", userId);
1151 return BAD_VALUE;
1152 }
1153
1154 uid = multiuser_get_uid(userId, uid);
1155 return NO_ERROR;
1156}
1157
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001158Status CameraService::validateConnectLocked(const String8& cameraId,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001159 const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
1160 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001161
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001162#ifdef __BRILLO__
1163 UNUSED(clientName8);
1164 UNUSED(clientUid);
1165 UNUSED(clientPid);
1166 UNUSED(originalClientPid);
1167#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001168 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1169 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001170 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001171 return allowed;
1172 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001173#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001174
Jayant Chowdhary12361932018-08-27 14:46:13 -07001175 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001176
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001177 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001178 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1179 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001180 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1181 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001182 }
1183
Ruben Brunkcc776712015-02-17 20:18:47 -08001184 if (getCameraState(cameraId) == nullptr) {
1185 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1186 cameraId.string());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001187 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1188 "No camera device with ID \"%s\" available", cameraId.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001189 }
1190
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001191 status_t err = checkIfDeviceIsUsable(cameraId);
1192 if (err != NO_ERROR) {
1193 switch(err) {
1194 case -ENODEV:
1195 case -EBUSY:
1196 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1197 "No camera device with ID \"%s\" currently available", cameraId.string());
1198 default:
1199 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1200 "Unknown error connecting to ID \"%s\"", cameraId.string());
1201 }
1202 }
1203 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001204}
1205
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001206Status CameraService::validateClientPermissionsLocked(const String8& cameraId,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001207 const String8& clientName8, int& clientUid, int& clientPid,
1208 /*out*/int& originalClientPid) const {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001209 int callingPid = CameraThreadState::getCallingPid();
1210 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001211
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001212 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001213 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001214 clientUid = callingUid;
1215 } else if (!isTrustedCallingUid(callingUid)) {
1216 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1217 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001218 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1219 "Untrusted caller (calling PID %d, UID %d) trying to "
1220 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1221 callingPid, callingUid, cameraId.string(),
1222 clientName8.string(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001223 }
1224
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001225 // Check if we can trust clientPid
1226 if (clientPid == USE_CALLING_PID) {
1227 clientPid = callingPid;
1228 } else if (!isTrustedCallingUid(callingUid)) {
1229 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1230 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001231 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1232 "Untrusted caller (calling PID %d, UID %d) trying to "
1233 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1234 callingPid, callingUid, cameraId.string(),
1235 clientName8.string(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001236 }
1237
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001238 if (shouldRejectSystemCameraConnection(cameraId)) {
1239 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1240 cameraId.c_str());
1241 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
1242 "available", cameraId.string());
1243 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001244 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1245 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1246 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
1247 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
1248 "found while trying to query device kind", cameraId.string());
1249
1250 }
1251
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001252 // If it's not calling from cameraserver, check the permission if the
1253 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1254 // android.permission.SYSTEM_CAMERA for system only camera devices).
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001255 if (callingPid != getpid() &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001256 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001257 !checkPermission(sCameraPermission, clientPid, clientUid)) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001258 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001259 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1260 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
1261 clientName8.string(), clientUid, clientPid, cameraId.string());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001262 }
1263
Svet Ganova453d0d2018-01-11 15:37:58 -08001264 // Make sure the UID is in an active state to use the camera
Svet Ganov7b4ab782018-03-25 12:48:10 -07001265 if (!mUidPolicy->isUidActive(callingUid, String16(clientName8))) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001266 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001267 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1268 clientPid, clientUid);
1269 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001270 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1271 "calling UID %d proc state %" PRId32 ")",
1272 clientName8.string(), clientUid, clientPid, cameraId.string(),
1273 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001274 }
1275
Michael Grooverd1d435a2018-12-18 17:39:42 -08001276 // If sensor privacy is enabled then prevent access to the camera
1277 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1278 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1279 return STATUS_ERROR_FMT(ERROR_DISABLED,
1280 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
1281 "is enabled", clientName8.string(), clientUid, clientPid, cameraId.string());
1282 }
1283
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001284 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1285 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001286 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001287 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001288
Ruben Brunk6267b532015-04-30 17:44:07 -07001289 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001290
Ruben Brunka8ca9152015-04-07 14:23:40 -07001291 // Only allow clients who are being used by the current foreground device user, unless calling
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001292 // from our own process OR the caller is using the cameraserver's HIDL interface.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001293 if (getCurrentServingCall() != BinderCallType::HWBINDER && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001294 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001295 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1296 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
1297 toString(mAllowedUsers).string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001298 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1299 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
1300 clientUserId, cameraId.string());
Ruben Brunk36597b22015-03-20 22:15:57 -07001301 }
1302
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001303 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001304}
1305
1306status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
1307 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001308 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001309 if (cameraState == nullptr) {
1310 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1311 cameraId.string());
1312 return -ENODEV;
1313 }
1314
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001315 StatusInternal currentStatus = cameraState->getStatus();
1316 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001317 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
1318 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001319 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001320 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001321 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
1322 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001323 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001324 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001325
Ruben Brunkcc776712015-02-17 20:18:47 -08001326 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001327}
1328
Ruben Brunkcc776712015-02-17 20:18:47 -08001329void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001330 const CameraService::DescriptorPtr& desc, int oomScoreOffset) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001331
Ruben Brunkcc776712015-02-17 20:18:47 -08001332 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001333 auto clientDescriptor =
1334 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
1335 oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08001336 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1337
1338 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
1339 String8(client->getPackageName()));
1340
1341 if (evicted.size() > 0) {
1342 // This should never happen - clients should already have been removed in disconnect
1343 for (auto& i : evicted) {
1344 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
1345 __FUNCTION__, i->getKey().string());
1346 }
1347
1348 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1349 __FUNCTION__);
1350 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001351
1352 // And register a death notification for the client callback. Do
1353 // this last to avoid Binder policy where a nested Binder
1354 // transaction might be pre-empted to service the client death
1355 // notification if the client process dies before linkToDeath is
1356 // invoked.
1357 sp<IBinder> remoteCallback = client->getRemote();
1358 if (remoteCallback != nullptr) {
1359 remoteCallback->linkToDeath(this);
1360 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001361}
1362
1363status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
1364 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001365 int oomScoreOffset,
Ruben Brunkcc776712015-02-17 20:18:47 -08001366 /*out*/
1367 sp<BasicClient>* client,
1368 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001369 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001370 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001371 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001372 DescriptorPtr clientDescriptor;
1373 {
1374 if (effectiveApiLevel == API_1) {
1375 // If we are using API1, any existing client for this camera ID with the same remote
1376 // should be returned rather than evicted to allow MediaRecorder to work properly.
1377
1378 auto current = mActiveClientManager.get(cameraId);
1379 if (current != nullptr) {
1380 auto clientSp = current->getValue();
1381 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001382 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
Shuzhen Wangb2d43f62021-08-25 14:01:11 -07001383 ALOGW("CameraService connect called with a different"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001384 " API level, evicting prior client...");
1385 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001386 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001387 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001388 *client = clientSp;
1389 return NO_ERROR;
1390 }
1391 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001392 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001393 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001394
Ruben Brunkcc776712015-02-17 20:18:47 -08001395 // Get current active client PIDs
1396 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1397 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001398
Emilian Peev8131a262017-02-01 12:33:43 +00001399 std::vector<int> priorityScores(ownerPids.size());
1400 std::vector<int> states(ownerPids.size());
Igor Murashkine6800ce2013-03-04 17:25:57 -08001401
Emilian Peev8131a262017-02-01 12:33:43 +00001402 // Get priority scores of all active PIDs
1403 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1404 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1405 /*out*/&priorityScores[0]);
1406 if (err != OK) {
1407 ALOGE("%s: Priority score query failed: %d",
1408 __FUNCTION__, err);
1409 return err;
1410 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001411
Ruben Brunkcc776712015-02-17 20:18:47 -08001412 // Update all active clients' priorities
Emilian Peev8131a262017-02-01 12:33:43 +00001413 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
Ruben Brunkcc776712015-02-17 20:18:47 -08001414 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
Emilian Peev8131a262017-02-01 12:33:43 +00001415 pidToPriorityMap.emplace(ownerPids[i],
Jayant Chowdharyc578a502019-05-08 10:57:54 -07001416 resource_policy::ClientPriority(priorityScores[i], states[i],
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001417 /* isVendorClient won't get copied over*/ false,
1418 /* oomScoreOffset won't get copied over*/ 0));
Ruben Brunkcc776712015-02-17 20:18:47 -08001419 }
1420 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001421
Ruben Brunkcc776712015-02-17 20:18:47 -08001422 // Get state for the given cameraId
1423 auto state = getCameraState(cameraId);
1424 if (state == nullptr) {
1425 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1426 clientPid, cameraId.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001427 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001428 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001429 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001430
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001431 int32_t actualScore = priorityScores[priorityScores.size() - 1];
1432 int32_t actualState = states[states.size() - 1];
1433
1434 // Make descriptor for incoming client. We store the oomScoreOffset
1435 // since we might need it later on new handleEvictionsLocked and
1436 // ProcessInfoService would not take that into account.
Shuzhen Wang2db86ff2018-04-25 01:11:17 +00001437 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001438 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001439 state->getConflicting(), actualScore, clientPid, actualState,
1440 oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08001441
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001442 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1443
Ruben Brunkcc776712015-02-17 20:18:47 -08001444 // Find clients that would be evicted
1445 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1446
1447 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1448 // background, so we cannot do evictions
1449 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1450 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1451 " priority).", clientPid);
1452
1453 sp<BasicClient> clientSp = clientDescriptor->getValue();
1454 String8 curTime = getFormattedCurrentTime();
1455 auto incompatibleClients =
1456 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1457
1458 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Emilian Peev8131a262017-02-01 12:33:43 +00001459 "(PID %d, score %d state %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001460 cameraId.string(), packageName.string(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001461 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001462
1463 for (auto& i : incompatibleClients) {
1464 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001465 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
1466 i->getKey().string(),
1467 String8{i->getValue()->getPackageName()}.string(),
1468 i->getOwnerId(), i->getPriority().getScore(),
1469 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001470 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00001471 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(),
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001472 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001473 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001474 }
1475
1476 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001477 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001478 mEventLog.add(msg);
1479
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001480 auto current = mActiveClientManager.get(cameraId);
1481 if (current != nullptr) {
1482 return -EBUSY; // CAMERA_IN_USE
1483 } else {
1484 return -EUSERS; // MAX_CAMERAS_IN_USE
1485 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001486 }
1487
1488 for (auto& i : evicted) {
1489 sp<BasicClient> clientSp = i->getValue();
1490 if (clientSp.get() == nullptr) {
1491 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1492
1493 // TODO: Remove this
1494 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1495 __FUNCTION__);
1496 mActiveClientManager.remove(i);
1497 continue;
1498 }
1499
1500 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1501 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001502 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001503
Ruben Brunkcc776712015-02-17 20:18:47 -08001504 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001505 logEvent(String8::format("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00001506 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1507 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001508 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
Emilian Peev8131a262017-02-01 12:33:43 +00001509 i->getOwnerId(), i->getPriority().getScore(),
1510 i->getPriority().getState(), cameraId.string(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001511 packageName.string(), clientPid, clientPriority.getScore(),
1512 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08001513
1514 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001515 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001516 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001517 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001518 }
1519
Ruben Brunkcc776712015-02-17 20:18:47 -08001520 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1521 // other clients from connecting in mServiceLockWrapper if held
1522 mServiceLock.unlock();
1523
1524 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07001525 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001526
1527 // Destroy evicted clients
1528 for (auto& i : evictedClients) {
1529 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001530 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001531 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001532
Jayant Chowdhary12361932018-08-27 14:46:13 -07001533 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08001534
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001535 for (const auto& i : evictedClients) {
1536 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1537 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1538 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1539 if (ret == TIMED_OUT) {
1540 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1541 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1542 mActiveClientManager.toString().string());
1543 return -EBUSY;
1544 }
1545 if (ret != NO_ERROR) {
1546 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1547 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1548 ret, mActiveClientManager.toString().string());
1549 return ret;
1550 }
1551 }
1552
1553 evictedClients.clear();
1554
Ruben Brunkcc776712015-02-17 20:18:47 -08001555 // Once clients have been disconnected, relock
1556 mServiceLock.lock();
1557
1558 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1559 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1560 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001561 }
1562
Ruben Brunkcc776712015-02-17 20:18:47 -08001563 *partial = clientDescriptor;
1564 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001565}
1566
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001567Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001568 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001569 int api1CameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001570 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001571 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001572 int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001573 int targetSdkVersion,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001574 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001575 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001576
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001577 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001578 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001579
1580 String8 id = cameraIdIntToStr(api1CameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001581 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001582 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001583 clientPackageName, {}, clientUid, clientPid, API_1,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001584 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001585
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001586 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001587 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001588 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001589 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001590 }
1591
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001592 *device = client;
1593 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001594}
1595
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001596bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
1597 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001598 // If the client is not a vendor client, don't add listener if
1599 // a) the camera is a publicly hidden secure camera OR
1600 // b) the camera is a system only camera and the client doesn't
1601 // have android.permission.SYSTEM_CAMERA permissions.
1602 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
1603 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1604 !hasPermissionsForSystemCamera(clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001605 return true;
1606 }
1607 return false;
1608}
1609
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001610bool CameraService::shouldRejectSystemCameraConnection(const String8& cameraId) const {
1611 // Rules for rejection:
1612 // 1) If cameraserver tries to access this camera device, accept the
1613 // connection.
1614 // 2) The camera device is a publicly hidden secure camera device AND some
1615 // component is trying to access it on a non-hwbinder thread (generally a non HAL client),
1616 // reject it.
1617 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
1618 // and the serving thread is a non hwbinder thread, the client must have
1619 // android.permission.SYSTEM_CAMERA permissions to connect.
1620
1621 int cPid = CameraThreadState::getCallingPid();
1622 int cUid = CameraThreadState::getCallingUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001623 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
1624 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001625 // This isn't a known camera ID, so it's not a system camera
1626 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
1627 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001628 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001629
1630 // (1) Cameraserver trying to connect, accept.
1631 if (CameraThreadState::getCallingPid() == getpid()) {
1632 return false;
1633 }
1634 // (2)
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001635 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001636 systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
1637 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
1638 return true;
1639 }
1640 // (3) Here we only check for permissions if it is a system only camera device. This is since
1641 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
1642 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
1643 // same behavior for system camera devices.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001644 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001645 systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Jayant Chowdharyc3198c32021-07-28 20:59:14 +00001646 !hasPermissionsForSystemCamera(cPid, cUid, /*logPermissionFailure*/true)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001647 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
1648 cameraId.c_str());
1649 return true;
1650 }
1651
1652 return false;
1653}
1654
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001655Status CameraService::connectDevice(
1656 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001657 const String16& cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001658 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001659 const std::optional<String16>& clientFeatureId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001660 int clientUid, int oomScoreOffset, int targetSdkVersion,
Ruben Brunkcc776712015-02-17 20:18:47 -08001661 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001662 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001663
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001664 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001665 Status ret = Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001666 String8 id = String8(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001667 sp<CameraDeviceClient> client = nullptr;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001668 String16 clientPackageNameAdj = clientPackageName;
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001669 int callingPid = CameraThreadState::getCallingPid();
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001670
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001671 if (getCurrentServingCall() == BinderCallType::HWBINDER) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001672 std::string vendorClient =
1673 StringPrintf("vendor.client.pid<%d>", CameraThreadState::getCallingPid());
1674 clientPackageNameAdj = String16(vendorClient.c_str());
1675 }
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001676
1677 if (oomScoreOffset < 0) {
1678 String8 msg =
1679 String8::format("Cannot increase the priority of a client %s pid %d for "
1680 "camera id %s", String8(clientPackageNameAdj).string(), callingPid,
1681 id.string());
1682 ALOGE("%s: %s", __FUNCTION__, msg.string());
1683 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
1684 }
1685
1686 // enforce system camera permissions
1687 if (oomScoreOffset > 0 &&
1688 !hasPermissionsForSystemCamera(callingPid, CameraThreadState::getCallingUid())) {
1689 String8 msg =
1690 String8::format("Cannot change the priority of a client %s pid %d for "
1691 "camera id %s without SYSTEM_CAMERA permissions",
1692 String8(clientPackageNameAdj).string(), callingPid, id.string());
1693 ALOGE("%s: %s", __FUNCTION__, msg.string());
1694 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.string());
1695 }
1696
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001697 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001698 /*api1CameraId*/-1, clientPackageNameAdj, clientFeatureId,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001699 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, oomScoreOffset,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001700 targetSdkVersion, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08001701
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001702 if(!ret.isOk()) {
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001703 logRejected(id, callingPid, String8(clientPackageNameAdj), ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001704 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001705 }
1706
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001707 *device = client;
Rucha Katakwardf223072021-06-15 10:21:00 -07001708 Mutex::Autolock lock(mServiceLock);
1709
1710 // Clear the previous cached logs and reposition the
1711 // file offset to beginning of the file to log new data.
1712 // If either truncate or lseek fails, close the previous file and create a new one.
1713 if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
1714 ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
1715 // Close the previous memfd.
1716 close(mMemFd);
1717 // If failure to wipe the data, then create a new file and
1718 // assign the new value to mMemFd.
1719 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
1720 if (mMemFd == -1) {
1721 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
1722 }
1723 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001724 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001725}
1726
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001727template<class CALLBACK, class CLIENT>
1728Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001729 int api1CameraId, const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001730 const std::optional<String16>& clientFeatureId, int clientUid, int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001731 apiLevel effectiveApiLevel, bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001732 /*out*/sp<CLIENT>& device) {
1733 binder::Status ret = binder::Status::ok();
1734
1735 String8 clientName8(clientPackageName);
1736
1737 int originalClientPid = 0;
1738
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001739 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001740 "Camera API version %d", clientPid, clientName8.string(), cameraId.string(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001741 static_cast<int>(effectiveApiLevel));
1742
Shuzhen Wang316781a2020-08-18 18:11:01 -07001743 nsecs_t openTimeNs = systemTime();
1744
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001745 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001746 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07001747 int orientation = 0;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001748 bool isNdk = (clientPackageName.size() == 0);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001749 {
1750 // Acquire mServiceLock and prevent other clients from connecting
1751 std::unique_ptr<AutoConditionLock> lock =
1752 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1753
1754 if (lock == nullptr) {
1755 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
1756 , clientPid);
1757 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1758 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
1759 cameraId.string(), clientName8.string(), clientPid);
1760 }
1761
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07001762 // Enforce client permissions and do basic validity checks
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001763 if(!(ret = validateConnectLocked(cameraId, clientName8,
1764 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
1765 return ret;
1766 }
1767
1768 // Check the shim parameters after acquiring lock, if they have already been updated and
1769 // we were doing a shim update, return immediately
1770 if (shimUpdateOnly) {
1771 auto cameraState = getCameraState(cameraId);
1772 if (cameraState != nullptr) {
1773 if (!cameraState->getShimParams().isEmpty()) return ret;
1774 }
1775 }
1776
1777 status_t err;
1778
1779 sp<BasicClient> clientTmp = nullptr;
1780 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
1781 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001782 IInterface::asBinder(cameraCb), clientName8, oomScoreOffset, /*out*/&clientTmp,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001783 /*out*/&partial)) != NO_ERROR) {
1784 switch (err) {
1785 case -ENODEV:
1786 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1787 "No camera device with ID \"%s\" currently available",
1788 cameraId.string());
1789 case -EBUSY:
1790 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1791 "Higher-priority client using camera, ID \"%s\" currently unavailable",
1792 cameraId.string());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001793 case -EUSERS:
1794 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1795 "Too many cameras already open, cannot open camera \"%s\"",
1796 cameraId.string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001797 default:
1798 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1799 "Unexpected error %s (%d) opening camera \"%s\"",
1800 strerror(-err), err, cameraId.string());
1801 }
1802 }
1803
1804 if (clientTmp.get() != nullptr) {
1805 // Handle special case for API1 MediaRecorder where the existing client is returned
1806 device = static_cast<CLIENT*>(clientTmp.get());
1807 return ret;
1808 }
1809
1810 // give flashlight a chance to close devices if necessary.
1811 mFlashlight->prepareDeviceOpen(cameraId);
1812
Emilian Peevb91f1802021-03-23 14:50:28 -07001813 int deviceVersion = getDeviceVersion(cameraId, /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08001814 if (facing == -1) {
1815 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.string());
1816 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1817 "Unable to get camera device \"%s\" facing", cameraId.string());
1818 }
1819
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001820 sp<BasicClient> tmp = nullptr;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001821 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
1822 mPerfClassPrimaryCameraIds, cameraId.string(), targetSdkVersion);
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001823 if(!(ret = makeClient(this, cameraCb, clientPackageName, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07001824 cameraId, api1CameraId, facing, orientation,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001825 clientPid, clientUid, getpid(),
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001826 deviceVersion, effectiveApiLevel, overrideForPerfClass,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001827 /*out*/&tmp)).isOk()) {
1828 return ret;
1829 }
1830 client = static_cast<CLIENT*>(tmp.get());
1831
1832 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
1833 __FUNCTION__);
1834
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07001835 String8 monitorTags = isClientWatched(client.get()) ? mMonitorTags : String8("");
1836 err = client->initialize(mCameraProviderManager, monitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001837 if (err != OK) {
1838 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001839 // Errors could be from the HAL module open call or from AppOpsManager
1840 switch(err) {
1841 case BAD_VALUE:
1842 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1843 "Illegal argument to HAL module for camera \"%s\"", cameraId.string());
1844 case -EBUSY:
1845 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1846 "Camera \"%s\" is already open", cameraId.string());
1847 case -EUSERS:
1848 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1849 "Too many cameras already open, cannot open camera \"%s\"",
1850 cameraId.string());
1851 case PERMISSION_DENIED:
1852 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1853 "No permission to open camera \"%s\"", cameraId.string());
1854 case -EACCES:
1855 return STATUS_ERROR_FMT(ERROR_DISABLED,
1856 "Camera \"%s\" disabled by policy", cameraId.string());
1857 case -ENODEV:
1858 default:
1859 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1860 "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
1861 strerror(-err), err);
1862 }
1863 }
1864
1865 // Update shim paremeters for legacy clients
1866 if (effectiveApiLevel == API_1) {
1867 // Assume we have always received a Client subclass for API1
1868 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
1869 String8 rawParams = shimClient->getParameters();
1870 CameraParameters params(rawParams);
1871
1872 auto cameraState = getCameraState(cameraId);
1873 if (cameraState != nullptr) {
1874 cameraState->setShimParams(params);
1875 } else {
1876 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
1877 __FUNCTION__, cameraId.string());
1878 }
1879 }
1880
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001881 // Set rotate-and-crop override behavior
1882 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
1883 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
Emilian Peev5368ebf2021-10-08 17:52:18 -07001884 } else if (effectiveApiLevel == API_2) {
Emilian Peev065b2c12021-11-23 13:12:57 -08001885
1886 client->setRotateAndCropOverride(
1887 CameraServiceProxyWrapper::getRotateAndCropOverride(
1888 clientPackageName, facing, multiuser_get_user_id(clientUid)));
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001889 }
1890
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08001891 // Set camera muting behavior
Valentin Iftimec0b8d472021-07-23 20:21:06 +02001892 bool isCameraPrivacyEnabled =
1893 mSensorPrivacyPolicy->isCameraPrivacyEnabled(multiuser_get_user_id(clientUid));
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08001894 if (client->supportsCameraMute()) {
Valentin Iftimec0b8d472021-07-23 20:21:06 +02001895 client->setCameraMute(
1896 mOverrideCameraMuteMode || isCameraPrivacyEnabled);
1897 } else if (isCameraPrivacyEnabled) {
1898 // no camera mute supported, but privacy is on! => disconnect
1899 ALOGI("Camera mute not supported for package: %s, camera id: %s",
1900 String8(client->getPackageName()).string(), cameraId.string());
1901 // Do not hold mServiceLock while disconnecting clients, but
1902 // retain the condition blocking other clients from connecting
1903 // in mServiceLockWrapper if held.
1904 mServiceLock.unlock();
1905 // Clear caller identity temporarily so client disconnect PID
1906 // checks work correctly
1907 int64_t token = CameraThreadState::clearCallingIdentity();
1908 // Note AppOp to trigger the "Unblock" dialog
1909 client->noteAppOp();
1910 client->disconnect();
1911 CameraThreadState::restoreCallingIdentity(token);
1912 // Reacquire mServiceLock
1913 mServiceLock.lock();
1914
1915 return STATUS_ERROR_FMT(ERROR_DISABLED,
1916 "Camera \"%s\" disabled due to camera mute", cameraId.string());
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08001917 }
1918
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001919 if (shimUpdateOnly) {
1920 // If only updating legacy shim parameters, immediately disconnect client
1921 mServiceLock.unlock();
1922 client->disconnect();
1923 mServiceLock.lock();
1924 } else {
1925 // Otherwise, add client to active clients list
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001926 finishConnectLocked(client, partial, oomScoreOffset);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001927 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001928
1929 client->setImageDumpMask(mImageDumpMask);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001930 } // lock is destroyed, allow further connect calls
1931
1932 // Important: release the mutex here so the client can call back into the service from its
1933 // destructor (can be at the end of the call)
1934 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001935
1936 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
1937 CameraServiceProxyWrapper::logOpen(cameraId, facing, clientPackageName,
1938 effectiveApiLevel, isNdk, openLatencyMs);
1939
Cliff Wud3a05312021-04-26 23:07:31 +08001940 {
1941 Mutex::Autolock lock(mInjectionParametersLock);
1942 if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
1943 mInjectionInitPending = false;
1944 status_t res = NO_ERROR;
1945 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
1946 if (clientDescriptor != nullptr) {
Cliff Wu646bd612021-11-23 23:21:29 +08001947 sp<BasicClient> clientSp = clientDescriptor->getValue();
1948 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
1949 if(res != OK) {
1950 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1951 "No camera device with ID \"%s\" currently available",
1952 mInjectionExternalCamId.string());
1953 }
1954 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08001955 if (res != OK) {
1956 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
1957 }
1958 } else {
1959 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
1960 __FUNCTION__, mInjectionInternalCamId.string());
1961 res = NO_INIT;
1962 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
1963 }
1964 }
1965 }
1966
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001967 return ret;
1968}
1969
Emilian Peevb2bc5a42019-11-20 16:02:14 -08001970status_t CameraService::addOfflineClient(String8 cameraId, sp<BasicClient> offlineClient) {
1971 if (offlineClient.get() == nullptr) {
1972 return BAD_VALUE;
1973 }
1974
1975 {
1976 // Acquire mServiceLock and prevent other clients from connecting
1977 std::unique_ptr<AutoConditionLock> lock =
1978 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1979
1980 if (lock == nullptr) {
1981 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
1982 , __FUNCTION__, offlineClient->getClientPid());
1983 return TIMED_OUT;
1984 }
1985
1986 auto onlineClientDesc = mActiveClientManager.get(cameraId);
1987 if (onlineClientDesc.get() == nullptr) {
1988 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
1989 cameraId.c_str());
1990 return BAD_VALUE;
1991 }
1992
1993 // Offline clients do not evict or conflict with other online devices. Resource sharing
1994 // conflicts are handled by the camera provider which will either succeed or fail before
1995 // reaching this method.
1996 const auto& onlinePriority = onlineClientDesc->getPriority();
1997 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
1998 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
1999 /*conflictingKeys*/ std::set<String8>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002000 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
2001 /*ommScoreOffset*/ 0);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002002
2003 // Allow only one offline device per camera
2004 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
2005 if (!incompatibleClients.empty()) {
2006 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
2007 return BAD_VALUE;
2008 }
2009
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002010 String8 monitorTags = isClientWatched(offlineClient.get()) ? mMonitorTags : String8("");
2011 auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002012 if (err != OK) {
2013 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
2014 return err;
2015 }
2016
2017 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
2018 if (evicted.size() > 0) {
2019 for (auto& i : evicted) {
2020 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
2021 __FUNCTION__, i->getKey().string());
2022 }
2023
2024 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
2025 "properly", __FUNCTION__);
2026
2027 return BAD_VALUE;
2028 }
2029
2030 logConnectedOffline(offlineClientDesc->getKey(),
2031 static_cast<int>(offlineClientDesc->getOwnerId()),
2032 String8(offlineClient->getPackageName()));
2033
2034 sp<IBinder> remoteCallback = offlineClient->getRemote();
2035 if (remoteCallback != nullptr) {
2036 remoteCallback->linkToDeath(this);
2037 }
2038 } // lock is destroyed, allow further connect calls
2039
2040 return OK;
2041}
2042
Rucha Katakwar38284522021-11-10 11:25:21 -08002043Status CameraService::turnOnTorchWithStrengthLevel(const String16& cameraId, int32_t torchStrength,
2044 const sp<IBinder>& clientBinder) {
2045 Mutex::Autolock lock(mServiceLock);
2046
2047 ATRACE_CALL();
2048 if (clientBinder == nullptr) {
2049 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
2050 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2051 "Torch client binder in null.");
2052 }
2053
2054 String8 id = String8(cameraId.string());
2055 int uid = CameraThreadState::getCallingUid();
2056
2057 if (shouldRejectSystemCameraConnection(id)) {
2058 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to change the strength level"
2059 "for system only device %s: ", id.string());
2060 }
2061
2062 // verify id is valid
2063 auto state = getCameraState(id);
2064 if (state == nullptr) {
2065 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
2066 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2067 "Camera ID \"%s\" is a not valid camera ID", id.string());
2068 }
2069
2070 StatusInternal cameraStatus = state->getStatus();
2071 if (cameraStatus != StatusInternal::NOT_AVAILABLE &&
2072 cameraStatus != StatusInternal::PRESENT) {
2073 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(),
2074 (int)cameraStatus);
2075 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2076 "Camera ID \"%s\" is a not valid camera ID", id.string());
2077 }
2078
2079 {
2080 Mutex::Autolock al(mTorchStatusMutex);
2081 TorchModeStatus status;
2082 status_t err = getTorchStatusLocked(id, &status);
2083 if (err != OK) {
2084 if (err == NAME_NOT_FOUND) {
2085 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2086 "Camera \"%s\" does not have a flash unit", id.string());
2087 }
2088 ALOGE("%s: getting current torch status failed for camera %s",
2089 __FUNCTION__, id.string());
2090 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2091 "Error changing torch strength level for camera \"%s\": %s (%d)",
2092 id.string(), strerror(-err), err);
2093 }
2094
2095 if (status == TorchModeStatus::NOT_AVAILABLE) {
2096 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
2097 ALOGE("%s: torch mode of camera %s is not available because "
2098 "camera is in use.", __FUNCTION__, id.string());
2099 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2100 "Torch for camera \"%s\" is not available due to an existing camera user",
2101 id.string());
2102 } else {
2103 ALOGE("%s: torch mode of camera %s is not available due to "
2104 "insufficient resources", __FUNCTION__, id.string());
2105 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2106 "Torch for camera \"%s\" is not available due to insufficient resources",
2107 id.string());
2108 }
2109 }
2110 }
2111
2112 {
2113 Mutex::Autolock al(mTorchUidMapMutex);
2114 updateTorchUidMapLocked(cameraId, uid);
2115 }
2116 // Check if the current torch strength level is same as the new one.
2117 bool shouldSkipTorchStrengthUpdates = mCameraProviderManager->shouldSkipTorchStrengthUpdate(
2118 id.string(), torchStrength);
2119
2120 status_t err = mFlashlight->turnOnTorchWithStrengthLevel(id, torchStrength);
2121
2122 if (err != OK) {
2123 int32_t errorCode;
2124 String8 msg;
2125 switch (err) {
2126 case -ENOSYS:
2127 msg = String8::format("Camera \"%s\" has no flashlight.",
2128 id.string());
2129 errorCode = ERROR_ILLEGAL_ARGUMENT;
2130 break;
2131 case -EBUSY:
2132 msg = String8::format("Camera \"%s\" is in use",
2133 id.string());
2134 errorCode = ERROR_CAMERA_IN_USE;
2135 break;
2136 default:
2137 msg = String8::format("Changing torch strength level failed.");
2138 errorCode = ERROR_INVALID_OPERATION;
2139
2140 }
2141 ALOGE("%s: %s", __FUNCTION__, msg.string());
2142 return STATUS_ERROR(errorCode, msg.string());
2143 }
2144
2145 {
2146 // update the link to client's death
2147 // Store the last client that turns on each camera's torch mode.
2148 Mutex::Autolock al(mTorchClientMapMutex);
2149 ssize_t index = mTorchClientMap.indexOfKey(id);
2150 if (index == NAME_NOT_FOUND) {
2151 mTorchClientMap.add(id, clientBinder);
2152 } else {
2153 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
2154 mTorchClientMap.replaceValueAt(index, clientBinder);
2155 }
2156 clientBinder->linkToDeath(this);
2157 }
2158
2159 int clientPid = CameraThreadState::getCallingPid();
2160 const char *id_cstr = id.c_str();
2161 ALOGI("%s: Torch strength for camera id %s changed to %d for client PID %d",
2162 __FUNCTION__, id_cstr, torchStrength, clientPid);
2163 if (!shouldSkipTorchStrengthUpdates) {
2164 broadcastTorchStrengthLevel(id, torchStrength);
2165 }
2166 return Status::ok();
2167}
2168
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002169Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002170 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002171 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002172
2173 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07002174 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002175 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002176 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2177 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002178 }
2179
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002180 String8 id = String8(cameraId.string());
Jayant Chowdhary12361932018-08-27 14:46:13 -07002181 int uid = CameraThreadState::getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002182
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002183 if (shouldRejectSystemCameraConnection(id)) {
2184 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
2185 " for system only device %s: ", id.string());
2186 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002187 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08002188 auto state = getCameraState(id);
2189 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07002190 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002191 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2192 "Camera ID \"%s\" is a not valid camera ID", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08002193 }
2194
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002195 StatusInternal cameraStatus = state->getStatus();
2196 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002197 cameraStatus != StatusInternal::NOT_AVAILABLE) {
2198 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002199 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2200 "Camera ID \"%s\" is a not valid camera ID", id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002201 }
2202
2203 {
2204 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002205 TorchModeStatus status;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002206 status_t err = getTorchStatusLocked(id, &status);
2207 if (err != OK) {
2208 if (err == NAME_NOT_FOUND) {
2209 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2210 "Camera \"%s\" does not have a flash unit", id.string());
2211 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002212 ALOGE("%s: getting current torch status failed for camera %s",
2213 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002214 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2215 "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
2216 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002217 }
2218
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002219 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002220 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002221 ALOGE("%s: torch mode of camera %s is not available because "
2222 "camera is in use", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002223 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2224 "Torch for camera \"%s\" is not available due to an existing camera user",
2225 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002226 } else {
2227 ALOGE("%s: torch mode of camera %s is not available due to "
2228 "insufficient resources", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002229 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2230 "Torch for camera \"%s\" is not available due to insufficient resources",
2231 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002232 }
2233 }
2234 }
2235
Ruben Brunk99e69712015-05-26 17:25:07 -07002236 {
2237 // Update UID map - this is used in the torch status changed callbacks, so must be done
2238 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07002239 Mutex::Autolock al(mTorchUidMapMutex);
Rucha Katakwar38284522021-11-10 11:25:21 -08002240 updateTorchUidMapLocked(cameraId, uid);
Ruben Brunk99e69712015-05-26 17:25:07 -07002241 }
2242
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002243 status_t err = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07002244
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002245 if (err != OK) {
2246 int32_t errorCode;
2247 String8 msg;
2248 switch (err) {
2249 case -ENOSYS:
2250 msg = String8::format("Camera \"%s\" has no flashlight",
2251 id.string());
2252 errorCode = ERROR_ILLEGAL_ARGUMENT;
2253 break;
Dijack Dongc8a6f252021-09-17 16:21:16 +08002254 case -EBUSY:
2255 msg = String8::format("Camera \"%s\" is in use",
2256 id.string());
2257 errorCode = ERROR_CAMERA_IN_USE;
2258 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002259 default:
2260 msg = String8::format(
2261 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
2262 id.string(), enabled, strerror(-err), err);
2263 errorCode = ERROR_INVALID_OPERATION;
2264 }
2265 ALOGE("%s: %s", __FUNCTION__, msg.string());
Rucha Katakward9ea6452021-05-06 11:57:16 -07002266 logServiceError(msg,errorCode);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002267 return STATUS_ERROR(errorCode, msg.string());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002268 }
2269
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002270 {
2271 // update the link to client's death
2272 Mutex::Autolock al(mTorchClientMapMutex);
2273 ssize_t index = mTorchClientMap.indexOfKey(id);
2274 if (enabled) {
2275 if (index == NAME_NOT_FOUND) {
2276 mTorchClientMap.add(id, clientBinder);
2277 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07002278 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002279 mTorchClientMap.replaceValueAt(index, clientBinder);
2280 }
2281 clientBinder->linkToDeath(this);
2282 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07002283 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002284 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002285 }
2286
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002287 int clientPid = CameraThreadState::getCallingPid();
2288 const char *id_cstr = id.c_str();
2289 const char *torchState = enabled ? "on" : "off";
2290 ALOGI("Torch for camera id %s turned %s for client PID %d", id_cstr, torchState, clientPid);
2291 logTorchEvent(id_cstr, torchState , clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002292 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002293}
2294
Rucha Katakwar38284522021-11-10 11:25:21 -08002295void CameraService::updateTorchUidMapLocked(const String16& cameraId, int uid) {
2296 String8 id = String8(cameraId.string());
2297 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
2298 mTorchUidMap[id].first = uid;
2299 mTorchUidMap[id].second = uid;
2300 } else {
2301 // Set the pending UID
2302 mTorchUidMap[id].first = uid;
2303 }
2304}
2305
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002306Status CameraService::notifySystemEvent(int32_t eventId,
2307 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002308 const int pid = CameraThreadState::getCallingPid();
2309 const int selfPid = getpid();
2310
2311 // Permission checks
2312 if (pid != selfPid) {
2313 // Ensure we're being called by system_server, or similar process with
2314 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002315 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002316 const int uid = CameraThreadState::getCallingUid();
2317 ALOGE("Permission Denial: cannot send updates to camera service about system"
2318 " events from pid=%d, uid=%d", pid, uid);
2319 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09002320 "No permission to send updates to camera service about system events"
2321 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002322 }
2323 }
2324
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002325 ATRACE_CALL();
2326
Ruben Brunk36597b22015-03-20 22:15:57 -07002327 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002328 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08002329 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002330 // from a system server crash
2331 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08002332 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002333 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07002334 break;
2335 }
Valentin Iftime29e2e152021-08-13 15:17:33 +02002336 case ICameraService::EVENT_USB_DEVICE_ATTACHED:
2337 case ICameraService::EVENT_USB_DEVICE_DETACHED: {
2338 // Notify CameraProviderManager for lazy HALs
2339 mCameraProviderManager->notifyUsbDeviceEvent(eventId,
2340 std::to_string(args[0]));
2341 break;
2342 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002343 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07002344 default: {
2345 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
2346 eventId);
2347 break;
2348 }
2349 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002350 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002351}
2352
Emilian Peev53722fa2019-02-22 17:47:20 -08002353void CameraService::notifyMonitoredUids() {
2354 Mutex::Autolock lock(mStatusListenerLock);
2355
2356 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002357 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Emilian Peev53722fa2019-02-22 17:47:20 -08002358 if (!ret.isOk()) {
2359 ALOGE("%s: Failed to trigger permission callback: %d", __FUNCTION__,
2360 ret.exceptionCode());
2361 }
2362 }
2363}
2364
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002365Status CameraService::notifyDeviceStateChange(int64_t newState) {
2366 const int pid = CameraThreadState::getCallingPid();
2367 const int selfPid = getpid();
2368
2369 // Permission checks
2370 if (pid != selfPid) {
2371 // Ensure we're being called by system_server, or similar process with
2372 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002373 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002374 const int uid = CameraThreadState::getCallingUid();
2375 ALOGE("Permission Denial: cannot send updates to camera service about device"
2376 " state changes from pid=%d, uid=%d", pid, uid);
2377 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2378 "No permission to send updates to camera service about device state"
2379 " changes from pid=%d, uid=%d", pid, uid);
2380 }
2381 }
2382
2383 ATRACE_CALL();
2384
Jayant Chowdhary0bd38522021-11-05 17:49:27 -07002385 mCameraProviderManager->notifyDeviceStateChange(newState);
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002386
2387 return Status::ok();
2388}
2389
Emilian Peev8b64f282021-03-25 16:49:57 -07002390Status CameraService::notifyDisplayConfigurationChange() {
2391 ATRACE_CALL();
2392 const int callingPid = CameraThreadState::getCallingPid();
2393 const int selfPid = getpid();
2394
2395 // Permission checks
2396 if (callingPid != selfPid) {
2397 // Ensure we're being called by system_server, or similar process with
2398 // permissions to notify the camera service about system events
2399 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
2400 const int uid = CameraThreadState::getCallingUid();
2401 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
2402 " changes from pid=%d, uid=%d", callingPid, uid);
2403 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2404 "No permission to send updates to camera service about orientation"
2405 " changes from pid=%d, uid=%d", callingPid, uid);
2406 }
2407 }
2408
2409 Mutex::Autolock lock(mServiceLock);
2410
2411 // Don't do anything if rotate-and-crop override via cmd is active
2412 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
2413
2414 const auto clients = mActiveClientManager.getAll();
2415 for (auto& current : clients) {
2416 if (current != nullptr) {
2417 const auto basicClient = current->getValue();
Emilian Peeve23f1d92021-09-20 14:56:01 -07002418 if (basicClient.get() != nullptr && basicClient->canCastToApiClient(API_2)) {
Emilian Peev065b2c12021-11-23 13:12:57 -08002419 basicClient->setRotateAndCropOverride(
2420 CameraServiceProxyWrapper::getRotateAndCropOverride(
2421 basicClient->getPackageName(),
2422 basicClient->getCameraFacing(),
2423 multiuser_get_user_id(basicClient->getClientUid())));
Emilian Peev8b64f282021-03-25 16:49:57 -07002424 }
2425 }
2426 }
2427
2428 return Status::ok();
2429}
2430
2431Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002432 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
2433 ATRACE_CALL();
2434 if (!concurrentCameraIds) {
2435 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
2436 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
2437 }
2438
2439 if (!mInitialized) {
2440 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Rucha Katakward9ea6452021-05-06 11:57:16 -07002441 logServiceError(String8::format("Camera subsystem is not available"),ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002442 return STATUS_ERROR(ERROR_DISCONNECTED,
2443 "Camera subsystem is not available");
2444 }
2445 // First call into the provider and get the set of concurrent camera
2446 // combinations
2447 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07002448 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002449 for (auto &combination : concurrentCameraCombinations) {
2450 std::vector<std::string> validCombination;
2451 for (auto &cameraId : combination) {
2452 // if the camera state is not present, skip
2453 String8 cameraIdStr(cameraId.c_str());
2454 auto state = getCameraState(cameraIdStr);
2455 if (state == nullptr) {
2456 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
2457 continue;
2458 }
2459 StatusInternal status = state->getStatus();
2460 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
2461 continue;
2462 }
2463 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
2464 continue;
2465 }
2466 validCombination.push_back(cameraId);
2467 }
2468 if (validCombination.size() != 0) {
2469 concurrentCameraIds->push_back(std::move(validCombination));
2470 }
2471 }
2472 return Status::ok();
2473}
2474
2475Status CameraService::isConcurrentSessionConfigurationSupported(
2476 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002477 int targetSdkVersion, /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002478 if (!isSupported) {
2479 ALOGE("%s: isSupported is NULL", __FUNCTION__);
2480 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
2481 }
2482
2483 if (!mInitialized) {
2484 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2485 return STATUS_ERROR(ERROR_DISCONNECTED,
2486 "Camera subsystem is not available");
2487 }
2488
2489 // Check for camera permissions
2490 int callingPid = CameraThreadState::getCallingPid();
2491 int callingUid = CameraThreadState::getCallingUid();
2492 if ((callingPid != getpid()) && !checkPermission(sCameraPermission, callingPid, callingUid)) {
2493 ALOGE("%s: pid %d doesn't have camera permissions", __FUNCTION__, callingPid);
2494 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2495 "android.permission.CAMERA needed to call"
2496 "isConcurrentSessionConfigurationSupported");
2497 }
2498
2499 status_t res =
2500 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002501 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
2502 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002503 if (res != OK) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07002504 logServiceError(String8::format("Unable to query session configuration support"),
2505 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002506 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
2507 "support %s (%d)", strerror(-res), res);
2508 }
2509 return Status::ok();
2510}
2511
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002512Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
2513 /*out*/
2514 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002515 return addListenerHelper(listener, cameraStatuses);
2516}
2517
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002518binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
2519 std::vector<hardware::CameraStatus>* cameraStatuses) {
2520 return addListenerHelper(listener, cameraStatuses, false, true);
2521}
2522
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002523Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
2524 /*out*/
2525 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002526 bool isVendorListener, bool isProcessLocalTest) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002527
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002528 ATRACE_CALL();
2529
Igor Murashkinbfc99152013-02-27 12:55:20 -08002530 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08002531
Ruben Brunk3450ba72015-06-16 11:00:37 -07002532 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002533 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002534 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002535 }
2536
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002537 auto clientUid = CameraThreadState::getCallingUid();
2538 auto clientPid = CameraThreadState::getCallingPid();
Shuzhen Wang695044d2020-03-06 09:02:23 -08002539 bool openCloseCallbackAllowed = checkPermission(sCameraOpenCloseListenerPermission,
Jayant Chowdharyc3198c32021-07-28 20:59:14 +00002540 clientPid, clientUid, /*logPermissionFailure*/false);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002541
Igor Murashkinbfc99152013-02-27 12:55:20 -08002542 Mutex::Autolock lock(mServiceLock);
2543
Ruben Brunkcc776712015-02-17 20:18:47 -08002544 {
2545 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08002546 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002547 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002548 ALOGW("%s: Tried to add listener %p which was already subscribed",
2549 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002550 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08002551 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002552 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002553
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002554 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08002555 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
2556 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002557 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08002558 if (ret != NO_ERROR) {
2559 String8 msg = String8::format("Failed to initialize service listener: %s (%d)",
2560 strerror(-ret), ret);
Rucha Katakward9ea6452021-05-06 11:57:16 -07002561 logServiceError(msg,ERROR_ILLEGAL_ARGUMENT);
Emilian Peev53722fa2019-02-22 17:47:20 -08002562 ALOGE("%s: %s", __FUNCTION__, msg.string());
2563 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
2564 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002565 // The listener still needs to be added to the list of listeners, regardless of what
2566 // permissions the listener process has / whether it is a vendor listener. Since it might be
2567 // eligible to listen to other camera ids.
2568 mListenerList.emplace_back(serviceListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08002569 mUidPolicy->registerMonitorUid(clientUid);
Igor Murashkinbfc99152013-02-27 12:55:20 -08002570 }
2571
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002572 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07002573 {
Ruben Brunkcc776712015-02-17 20:18:47 -08002574 Mutex::Autolock lock(mCameraStatesLock);
2575 for (auto& i : mCameraStates) {
Shuzhen Wang43858162020-01-10 13:42:15 -08002576 cameraStatuses->emplace_back(i.first,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07002577 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
2578 openCloseCallbackAllowed ? i.second->getClientPackage() : String8::empty());
Igor Murashkincba2c162013-03-20 15:56:31 -07002579 }
2580 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002581 // Remove the camera statuses that should be hidden from the client, we do
2582 // this after collecting the states in order to avoid holding
2583 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
2584 // the same time.
2585 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
2586 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
2587 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
2588 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
2589 ALOGE("%s: Invalid camera id %s, skipping status update",
2590 __FUNCTION__, s.cameraId.c_str());
2591 return true;
2592 }
2593 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
2594 clientUid);}), cameraStatuses->end());
2595
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002596 //cameraStatuses will have non-eligible camera ids removed.
2597 std::set<String16> idsChosenForCallback;
2598 for (const auto &s : *cameraStatuses) {
2599 idsChosenForCallback.insert(String16(s.cameraId));
2600 }
Igor Murashkincba2c162013-03-20 15:56:31 -07002601
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002602 /*
2603 * Immediately signal current torch status to this listener only
2604 * This may be a subset of all the devices, so don't include it in the response directly
2605 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002606 {
2607 Mutex::Autolock al(mTorchStatusMutex);
2608 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002609 String16 id = String16(mTorchStatusMap.keyAt(i).string());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002610 // The camera id is visible to the client. Fine to send torch
2611 // callback.
2612 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
2613 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
2614 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002615 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002616 }
2617
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002618 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08002619}
Ruben Brunkcc776712015-02-17 20:18:47 -08002620
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002621Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002622 ATRACE_CALL();
2623
Igor Murashkinbfc99152013-02-27 12:55:20 -08002624 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
2625
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002626 if (listener == 0) {
2627 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002628 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002629 }
2630
Igor Murashkinbfc99152013-02-27 12:55:20 -08002631 Mutex::Autolock lock(mServiceLock);
2632
Ruben Brunkcc776712015-02-17 20:18:47 -08002633 {
2634 Mutex::Autolock lock(mStatusListenerLock);
2635 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002636 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
2637 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid());
2638 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08002639 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002640 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002641 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002642 }
2643 }
2644
2645 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
2646 __FUNCTION__, listener.get());
2647
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002648 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08002649}
2650
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002651Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002652
2653 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002654 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
2655
2656 if (parameters == NULL) {
2657 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002658 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07002659 }
2660
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002661 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002662
2663 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002664 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07002665 // Error logged by caller
2666 return ret;
2667 }
2668
2669 String8 shimParamsString8 = shimParams.flatten();
2670 String16 shimParamsString16 = String16(shimParamsString8);
2671
2672 *parameters = shimParamsString16;
2673
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002674 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07002675}
2676
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002677Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
2678 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002679 ATRACE_CALL();
2680
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002681 const String8 id = String8(cameraId);
2682
2683 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002684
2685 switch (apiVersion) {
2686 case API_VERSION_1:
2687 case API_VERSION_2:
2688 break;
2689 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002690 String8 msg = String8::format("Unknown API version %d", apiVersion);
2691 ALOGE("%s: %s", __FUNCTION__, msg.string());
2692 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002693 }
2694
Emilian Peev28ad2ea2017-02-07 16:14:32 +00002695 int deviceVersion = getDeviceVersion(id);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002696 switch (deviceVersion) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002697 case CAMERA_DEVICE_API_VERSION_1_0:
2698 case CAMERA_DEVICE_API_VERSION_3_0:
2699 case CAMERA_DEVICE_API_VERSION_3_1:
2700 if (apiVersion == API_VERSION_2) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002701 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without shim",
2702 __FUNCTION__, id.string(), deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002703 *isSupported = false;
2704 } else { // if (apiVersion == API_VERSION_1) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002705 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always supported",
2706 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002707 *isSupported = true;
2708 }
2709 break;
2710 case CAMERA_DEVICE_API_VERSION_3_2:
2711 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -07002712 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002713 case CAMERA_DEVICE_API_VERSION_3_5:
Yin-Chia Yeh56d98ba2020-01-16 16:57:14 -08002714 case CAMERA_DEVICE_API_VERSION_3_6:
Shuzhen Wang83bff122020-11-20 15:51:39 -08002715 case CAMERA_DEVICE_API_VERSION_3_7:
Shuzhen Wang90708ea2021-11-04 11:40:49 -07002716 case CAMERA_DEVICE_API_VERSION_3_8:
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002717 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
2718 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002719 *isSupported = true;
2720 break;
2721 case -1: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002722 String8 msg = String8::format("Unknown camera ID %s", id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002723 ALOGE("%s: %s", __FUNCTION__, msg.string());
2724 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002725 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002726 default: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002727 String8 msg = String8::format("Unknown device version %x for device %s",
2728 deviceVersion, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002729 ALOGE("%s: %s", __FUNCTION__, msg.string());
2730 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
2731 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07002732 }
2733
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002734 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002735}
2736
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002737Status CameraService::isHiddenPhysicalCamera(const String16& cameraId,
2738 /*out*/ bool *isSupported) {
2739 ATRACE_CALL();
2740
2741 const String8 id = String8(cameraId);
2742
2743 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
2744 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(id.string());
2745
2746 return Status::ok();
2747}
2748
Cliff Wud8cae102021-03-11 01:37:42 +08002749Status CameraService::injectCamera(
2750 const String16& packageName, const String16& internalCamId,
2751 const String16& externalCamId,
2752 const sp<ICameraInjectionCallback>& callback,
2753 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08002754 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08002755 ATRACE_CALL();
2756
2757 if (!checkCallingPermission(sCameraInjectExternalCameraPermission)) {
2758 const int pid = CameraThreadState::getCallingPid();
2759 const int uid = CameraThreadState::getCallingUid();
2760 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
2761 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2762 "Permission Denial: no permission to inject camera");
2763 }
2764
2765 ALOGV(
2766 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
2767 "%s",
2768 __FUNCTION__, String8(packageName).string(),
2769 String8(internalCamId).string(), String8(externalCamId).string());
2770
Cliff Wud3a05312021-04-26 23:07:31 +08002771 {
2772 Mutex::Autolock lock(mInjectionParametersLock);
2773 mInjectionInternalCamId = String8(internalCamId);
2774 mInjectionExternalCamId = String8(externalCamId);
Cliff Wu646bd612021-11-23 23:21:29 +08002775 mInjectionStatusListener->addListener(callback);
2776 *cameraInjectionSession = new CameraInjectionSession(this);
Cliff Wud3a05312021-04-26 23:07:31 +08002777 status_t res = NO_ERROR;
2778 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2779 // If the client already exists, we can directly connect to the camera device through the
2780 // client's injectCamera(), otherwise we need to wait until the client is established
2781 // (execute connectHelper()) before injecting the camera to the camera device.
2782 if (clientDescriptor != nullptr) {
2783 mInjectionInitPending = false;
Cliff Wu646bd612021-11-23 23:21:29 +08002784 sp<BasicClient> clientSp = clientDescriptor->getValue();
2785 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2786 if(res != OK) {
2787 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2788 "No camera device with ID \"%s\" currently available",
2789 mInjectionExternalCamId.string());
2790 }
2791 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08002792 if(res != OK) {
2793 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2794 }
2795 } else {
2796 mInjectionInitPending = true;
2797 }
2798 }
Cliff Wud8cae102021-03-11 01:37:42 +08002799
Cliff Wud3a05312021-04-26 23:07:31 +08002800 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08002801}
2802
Ruben Brunkcc776712015-02-17 20:18:47 -08002803void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002804 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002805 for (auto& i : mActiveClientManager.getAll()) {
2806 auto clientSp = i->getValue();
2807 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002808 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08002809 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08002810 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07002811 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002812 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08002813}
2814
Ruben Brunkcc776712015-02-17 20:18:47 -08002815bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002816 bool ret = false;
2817 {
2818 // Acquire mServiceLock and prevent other clients from connecting
2819 std::unique_ptr<AutoConditionLock> lock =
2820 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08002821
Igor Murashkin634a5152013-02-20 17:15:11 -08002822
Ruben Brunkcc776712015-02-17 20:18:47 -08002823 std::vector<sp<BasicClient>> evicted;
2824 for (auto& i : mActiveClientManager.getAll()) {
2825 auto clientSp = i->getValue();
2826 if (clientSp.get() == nullptr) {
2827 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2828 mActiveClientManager.remove(i);
2829 continue;
2830 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08002831 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002832 mActiveClientManager.remove(i);
2833 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08002834
Ruben Brunkcc776712015-02-17 20:18:47 -08002835 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002836 clientSp->notifyError(
2837 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002838 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08002839 }
2840 }
2841
Ruben Brunkcc776712015-02-17 20:18:47 -08002842 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2843 // other clients from connecting in mServiceLockWrapper if held
2844 mServiceLock.unlock();
2845
Ruben Brunk36597b22015-03-20 22:15:57 -07002846 // Do not clear caller identity, remote caller should be client proccess
2847
Ruben Brunkcc776712015-02-17 20:18:47 -08002848 for (auto& i : evicted) {
2849 if (i.get() != nullptr) {
2850 i->disconnect();
2851 ret = true;
2852 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002853 }
2854
Ruben Brunkcc776712015-02-17 20:18:47 -08002855 // Reacquire mServiceLock
2856 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08002857
Ruben Brunkcc776712015-02-17 20:18:47 -08002858 } // lock is destroyed, allow further connect calls
2859
2860 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07002861}
2862
Ruben Brunkcc776712015-02-17 20:18:47 -08002863std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
2864 const String8& cameraId) const {
2865 std::shared_ptr<CameraState> state;
2866 {
2867 Mutex::Autolock lock(mCameraStatesLock);
2868 auto iter = mCameraStates.find(cameraId);
2869 if (iter != mCameraStates.end()) {
2870 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002871 }
2872 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002873 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002874}
2875
Ruben Brunkcc776712015-02-17 20:18:47 -08002876sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
2877 // Remove from active clients list
2878 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
2879 if (clientDescriptorPtr == nullptr) {
2880 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
2881 cameraId.string());
2882 return sp<BasicClient>{nullptr};
2883 }
2884
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002885 sp<BasicClient> client = clientDescriptorPtr->getValue();
2886 if (client.get() != nullptr) {
2887 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
2888 }
2889 return client;
Keun young Parkd8973a72012-03-28 14:13:09 -07002890}
2891
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002892void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07002893 // Acquire mServiceLock and prevent other clients from connecting
2894 std::unique_ptr<AutoConditionLock> lock =
2895 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
2896
Ruben Brunk6267b532015-04-30 17:44:07 -07002897 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002898 for (size_t i = 0; i < newUserIds.size(); i++) {
2899 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07002900 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002901 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07002902 return;
2903 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002904 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07002905 }
2906
Ruben Brunka8ca9152015-04-07 14:23:40 -07002907
Ruben Brunk6267b532015-04-30 17:44:07 -07002908 if (newAllowedUsers == mAllowedUsers) {
2909 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
2910 return;
2911 }
2912
2913 logUserSwitch(mAllowedUsers, newAllowedUsers);
2914
2915 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07002916
2917 // Current user has switched, evict all current clients.
2918 std::vector<sp<BasicClient>> evicted;
2919 for (auto& i : mActiveClientManager.getAll()) {
2920 auto clientSp = i->getValue();
2921
2922 if (clientSp.get() == nullptr) {
2923 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2924 continue;
2925 }
2926
Ruben Brunk6267b532015-04-30 17:44:07 -07002927 // Don't evict clients that are still allowed.
2928 uid_t clientUid = clientSp->getClientUid();
2929 userid_t clientUserId = multiuser_get_user_id(clientUid);
2930 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
2931 continue;
2932 }
2933
Ruben Brunk36597b22015-03-20 22:15:57 -07002934 evicted.push_back(clientSp);
2935
2936 String8 curTime = getFormattedCurrentTime();
2937
2938 ALOGE("Evicting conflicting client for camera ID %s due to user change",
2939 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07002940
Ruben Brunk36597b22015-03-20 22:15:57 -07002941 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002942 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00002943 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
2944 " to user switch.", i->getKey().string(),
2945 String8{clientSp->getPackageName()}.string(),
2946 i->getOwnerId(), i->getPriority().getScore(),
2947 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07002948
2949 }
2950
2951 // Do not hold mServiceLock while disconnecting clients, but retain the condition
2952 // blocking other clients from connecting in mServiceLockWrapper if held.
2953 mServiceLock.unlock();
2954
2955 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07002956 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07002957
2958 for (auto& i : evicted) {
2959 i->disconnect();
2960 }
2961
Jayant Chowdhary12361932018-08-27 14:46:13 -07002962 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07002963
2964 // Reacquire mServiceLock
2965 mServiceLock.lock();
2966}
Ruben Brunkcc776712015-02-17 20:18:47 -08002967
Ruben Brunka8ca9152015-04-07 14:23:40 -07002968void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002969 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07002970 Mutex::Autolock l(mLogLock);
Rucha Katakward9ea6452021-05-06 11:57:16 -07002971 String8 msg = String8::format("%s : %s", curTime.string(), event);
2972 // For service error events, print the msg only once.
2973 if(!msg.contains("SERVICE ERROR")) {
2974 mEventLog.add(msg);
2975 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
2976 // Error event not added to the dumpsys log before
2977 mEventLog.add(msg);
2978 sServiceErrorEventSet.insert(msg);
2979 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002980}
2981
Ruben Brunka8ca9152015-04-07 14:23:40 -07002982void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002983 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002984 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002985 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002986 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002987}
2988
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002989void CameraService::logDisconnectedOffline(const char* cameraId, int clientPid,
2990 const char* clientPackage) {
2991 // Log the clients evicted
2992 logEvent(String8::format("DISCONNECT offline device %s client for package %s (PID %d)",
2993 cameraId, clientPackage, clientPid));
2994}
2995
Ruben Brunka8ca9152015-04-07 14:23:40 -07002996void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002997 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002998 // Log the clients evicted
2999 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003000 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003001}
3002
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003003void CameraService::logConnectedOffline(const char* cameraId, int clientPid,
3004 const char* clientPackage) {
3005 // Log the clients evicted
3006 logEvent(String8::format("CONNECT offline device %s client for package %s (PID %d)", cameraId,
3007 clientPackage, clientPid));
3008}
3009
Ruben Brunka8ca9152015-04-07 14:23:40 -07003010void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003011 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003012 // Log the client rejected
3013 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003014 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003015}
3016
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003017void CameraService::logTorchEvent(const char* cameraId, const char *torchState, int clientPid) {
3018 // Log torch event
3019 logEvent(String8::format("Torch for camera id %s turned %s for client PID %d", cameraId,
3020 torchState, clientPid));
3021}
3022
Ruben Brunk6267b532015-04-30 17:44:07 -07003023void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
3024 const std::set<userid_t>& newUserIds) {
3025 String8 newUsers = toString(newUserIds);
3026 String8 oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003027 if (oldUsers.size() == 0) {
3028 oldUsers = "<None>";
3029 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07003030 // Log the new and old users
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003031 logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
Ruben Brunk6267b532015-04-30 17:44:07 -07003032 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003033}
3034
3035void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
3036 // Log the device removal
3037 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
3038}
3039
3040void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
3041 // Log the device removal
3042 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
3043}
3044
3045void CameraService::logClientDied(int clientPid, const char* reason) {
3046 // Log the device removal
3047 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07003048}
3049
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003050void CameraService::logServiceError(const char* msg, int errorCode) {
3051 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08003052 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003053}
3054
Ruben Brunk36597b22015-03-20 22:15:57 -07003055status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
3056 uint32_t flags) {
3057
Mathias Agopian65ab4712010-07-14 17:59:35 -07003058 // Permission checks
3059 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003060 case SHELL_COMMAND_TRANSACTION: {
3061 int in = data.readFileDescriptor();
3062 int out = data.readFileDescriptor();
3063 int err = data.readFileDescriptor();
3064 int argc = data.readInt32();
3065 Vector<String16> args;
3066 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
3067 args.add(data.readString16());
3068 }
3069 sp<IBinder> unusedCallback;
3070 sp<IResultReceiver> resultReceiver;
3071 status_t status;
3072 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
3073 return status;
3074 }
3075 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
3076 return status;
3077 }
3078 status = shellCommand(in, out, err, args);
3079 if (resultReceiver != nullptr) {
3080 resultReceiver->send(status);
3081 }
3082 return NO_ERROR;
3083 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003084 }
3085
3086 return BnCameraService::onTransact(code, data, reply, flags);
3087}
3088
Mathias Agopian65ab4712010-07-14 17:59:35 -07003089// We share the media players for shutter and recording sound for all clients.
3090// A reference count is kept to determine when we will actually release the
3091// media players.
3092
Jaekyun Seokef498052018-03-23 13:09:44 +09003093sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
3094 sp<MediaPlayer> mp = new MediaPlayer();
3095 status_t error;
3096 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08003097 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09003098 error = mp->prepare();
3099 }
3100 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00003101 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09003102 mp->disconnect();
3103 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003104 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003105 }
3106 return mp;
3107}
3108
username5755fea2018-12-27 09:48:08 +08003109void CameraService::increaseSoundRef() {
3110 Mutex::Autolock lock(mSoundLock);
3111 mSoundRef++;
3112}
3113
3114void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003115 ATRACE_CALL();
3116
username5755fea2018-12-27 09:48:08 +08003117 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
3118 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
3119 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
3120 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
3121 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
3122 }
3123 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
3124 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
3125 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
3126 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003127 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08003128 }
3129 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
3130 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
3131 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
3132 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
3133 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003134 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003135}
3136
username5755fea2018-12-27 09:48:08 +08003137void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003138 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08003139 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003140 if (--mSoundRef) return;
3141
3142 for (int i = 0; i < NUM_SOUNDS; i++) {
3143 if (mSoundPlayer[i] != 0) {
3144 mSoundPlayer[i]->disconnect();
3145 mSoundPlayer[i].clear();
3146 }
3147 }
3148}
3149
3150void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003151 ATRACE_CALL();
3152
Mathias Agopian65ab4712010-07-14 17:59:35 -07003153 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07003154 if (kind < 0 || kind >= NUM_SOUNDS) {
3155 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
3156 return;
3157 }
3158
Mathias Agopian65ab4712010-07-14 17:59:35 -07003159 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08003160 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003161 sp<MediaPlayer> player = mSoundPlayer[kind];
3162 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08003163 player->seekTo(0);
3164 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003165 }
3166}
3167
3168// ----------------------------------------------------------------------------
3169
3170CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07003171 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003172 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09003173 const std::optional<String16>& clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003174 const String8& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07003175 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003176 int clientPid, uid_t clientUid,
3177 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08003178 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08003179 IInterface::asBinder(cameraClient),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08003180 clientPackageName, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07003181 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003182 clientPid, clientUid,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003183 servicePid),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003184 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08003185{
Jayant Chowdhary12361932018-08-27 14:46:13 -07003186 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003187 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003188
Igor Murashkin44cfcf02013-03-01 16:22:28 -08003189 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003190
username5755fea2018-12-27 09:48:08 +08003191 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003192
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003193 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003194}
3195
Mathias Agopian65ab4712010-07-14 17:59:35 -07003196// tear down the client
3197CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003198 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08003199 mDestructionStarted = true;
3200
username5755fea2018-12-27 09:48:08 +08003201 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003202 // unconditionally disconnect. function is idempotent
3203 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003204}
3205
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003206sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
3207
Igor Murashkin634a5152013-02-20 17:15:11 -08003208CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003209 const sp<IBinder>& remoteCallback,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09003210 const String16& clientPackageName, const std::optional<String16>& clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07003211 const String8& cameraIdStr, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003212 int clientPid, uid_t clientUid,
3213 int servicePid):
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003214 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07003215 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09003216 mClientPackageName(clientPackageName), mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08003217 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003218 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07003219 mDisconnected(false), mUidIsTrusted(false),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003220 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003221 mRemoteBinder(remoteCallback),
3222 mOpsActive(false),
3223 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08003224{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003225 if (sCameraService == nullptr) {
3226 sCameraService = cameraService;
3227 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08003228
3229 // In some cases the calling code has no access to the package it runs under.
3230 // For example, NDK camera API.
3231 // In this case we will get the packages for the calling UID and pick the first one
3232 // for attributing the app op. This will work correctly for runtime permissions
3233 // as for legacy apps we will toggle the app op for all packages in the UID.
3234 // The caveat is that the operation may be attributed to the wrong package and
3235 // stats based on app ops may be slightly off.
3236 if (mClientPackageName.size() <= 0) {
3237 sp<IServiceManager> sm = defaultServiceManager();
3238 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
3239 if (binder == 0) {
3240 ALOGE("Cannot get permission service");
3241 // Leave mClientPackageName unchanged (empty) and the further interaction
3242 // with camera will fail in BasicClient::startCameraOps
3243 return;
3244 }
3245
3246 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
3247 Vector<String16> packages;
3248
3249 permCtrl->getPackagesForUid(mClientUid, packages);
3250
3251 if (packages.isEmpty()) {
3252 ALOGE("No packages for calling UID");
3253 // Leave mClientPackageName unchanged (empty) and the further interaction
3254 // with camera will fail in BasicClient::startCameraOps
3255 return;
3256 }
3257 mClientPackageName = packages[0];
3258 }
Steven Moreland89a2c5c2020-01-31 15:02:25 -08003259 if (getCurrentServingCall() != BinderCallType::HWBINDER) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003260 mAppOpsManager = std::make_unique<AppOpsManager>();
3261 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07003262
3263 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08003264}
3265
3266CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003267 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08003268 mDestructionStarted = true;
3269}
3270
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003271binder::Status CameraService::BasicClient::disconnect() {
3272 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003273 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003274 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07003275 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07003276 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08003277
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003278 sCameraService->removeByClient(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003279 sCameraService->logDisconnected(mCameraIdStr, mClientPid, String8(mClientPackageName));
Peter Kalauskasa29c1352018-10-10 12:05:42 -07003280 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
3281 mCameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003282
3283 sp<IBinder> remote = getRemote();
3284 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003285 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08003286 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003287
3288 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07003289 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003290 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
3291 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
3292 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003293
Igor Murashkincba2c162013-03-20 15:56:31 -07003294 // client shouldn't be able to call into us anymore
3295 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003296
3297 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08003298}
3299
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08003300status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
3301 // No dumping of clients directly over Binder,
3302 // must go through CameraService::dump
3303 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07003304 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08003305 return OK;
3306}
3307
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07003308status_t CameraService::BasicClient::startWatchingTags(const String8&, int) {
3309 // Can't watch tags directly, must go through CameraService::startWatchingTags
3310 return OK;
3311}
3312
3313status_t CameraService::BasicClient::stopWatchingTags(int) {
3314 // Can't watch tags directly, must go through CameraService::stopWatchingTags
3315 return OK;
3316}
3317
3318status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
3319 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
3320 return OK;
3321}
3322
Ruben Brunkcc776712015-02-17 20:18:47 -08003323String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003324 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08003325}
3326
Emilian Peev8b64f282021-03-25 16:49:57 -07003327int CameraService::BasicClient::getCameraFacing() const {
3328 return mCameraFacing;
3329}
3330
3331int CameraService::BasicClient::getCameraOrientation() const {
3332 return mOrientation;
3333}
Ruben Brunkcc776712015-02-17 20:18:47 -08003334
3335int CameraService::BasicClient::getClientPid() const {
3336 return mClientPid;
3337}
3338
Ruben Brunk6267b532015-04-30 17:44:07 -07003339uid_t CameraService::BasicClient::getClientUid() const {
3340 return mClientUid;
3341}
3342
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003343bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
3344 // Defaults to API2.
3345 return level == API_2;
3346}
3347
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07003348status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003349 {
3350 Mutex::Autolock l(mAudioRestrictionLock);
3351 mAudioRestriction = mode;
3352 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07003353 sCameraService->updateAudioRestriction();
3354 return OK;
3355}
3356
3357int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003358 return sCameraService->updateAudioRestriction();
3359}
3360
3361int32_t CameraService::BasicClient::getAudioRestriction() const {
3362 Mutex::Autolock l(mAudioRestrictionLock);
3363 return mAudioRestriction;
3364}
3365
3366bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
3367 switch (mode) {
3368 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
3369 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
3370 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
3371 return true;
3372 default:
3373 return false;
3374 }
3375}
3376
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003377status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
3378 if (mode == AppOpsManager::MODE_ERRORED) {
3379 ALOGI("Camera %s: Access for \"%s\" has been revoked",
3380 mCameraIdStr.string(), String8(mClientPackageName).string());
3381 return PERMISSION_DENIED;
3382 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
3383 // If the calling Uid is trusted (a native service), the AppOpsManager could
3384 // return MODE_IGNORED. Do not treat such case as error.
3385 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
3386 mClientPackageName);
3387 bool isCameraPrivacyEnabled =
3388 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled(
3389 multiuser_get_user_id(mClientUid));
3390 if (!isUidActive || !isCameraPrivacyEnabled) {
3391 ALOGI("Camera %s: Access for \"%s\" has been restricted",
3392 mCameraIdStr.string(), String8(mClientPackageName).string());
3393 // Return the same error as for device policy manager rejection
3394 return -EACCES;
3395 }
3396 }
3397 return OK;
3398}
3399
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003400status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003401 ATRACE_CALL();
3402
Igor Murashkine6800ce2013-03-04 17:25:57 -08003403 {
3404 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003405 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08003406 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003407 if (mAppOpsManager != nullptr) {
3408 // Notify app ops that the camera is not available
3409 mOpsCallback = new OpsCallback(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003410 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
3411 mClientPackageName, mOpsCallback);
Igor Murashkine6800ce2013-03-04 17:25:57 -08003412
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003413 // Just check for camera acccess here on open - delay startOp until
3414 // camera frames start streaming in startCameraStreamingOps
3415 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
3416 mClientPackageName);
3417 status_t res = handleAppOpMode(mode);
3418 if (res != OK) {
3419 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003420 }
Svetoslav28e8ef72015-05-11 19:21:31 -07003421 }
3422
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003423 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003424
3425 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003426 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003427
Emilian Peev53722fa2019-02-22 17:47:20 -08003428 sCameraService->mUidPolicy->registerMonitorUid(mClientUid);
3429
Shuzhen Wang695044d2020-03-06 09:02:23 -08003430 // Notify listeners of camera open/close status
3431 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
3432
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003433 return OK;
3434}
3435
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003436status_t CameraService::BasicClient::startCameraStreamingOps() {
3437 ATRACE_CALL();
3438
3439 if (!mOpsActive) {
3440 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
3441 return INVALID_OPERATION;
3442 }
3443 if (mOpsStreaming) {
3444 ALOGV("%s: Streaming already active!", __FUNCTION__);
3445 return OK;
3446 }
3447
3448 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
3449 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
3450
3451 if (mAppOpsManager != nullptr) {
3452 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
3453 mClientPackageName, /*startIfModeDefault*/ false, mClientFeatureId,
3454 String16("start camera ") + String16(mCameraIdStr));
3455 status_t res = handleAppOpMode(mode);
3456 if (res != OK) {
3457 return res;
3458 }
3459 }
3460
3461 mOpsStreaming = true;
3462
3463 return OK;
3464}
3465
Valentin Iftimec0b8d472021-07-23 20:21:06 +02003466status_t CameraService::BasicClient::noteAppOp() {
3467 ATRACE_CALL();
3468
3469 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d",
3470 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
3471
3472 // noteAppOp is only used for when camera mute is not supported, in order
3473 // to trigger the sensor privacy "Unblock" dialog
3474 if (mAppOpsManager != nullptr) {
3475 int32_t mode = mAppOpsManager->noteOp(AppOpsManager::OP_CAMERA, mClientUid,
3476 mClientPackageName, mClientFeatureId,
3477 String16("start camera ") + String16(mCameraIdStr));
3478 status_t res = handleAppOpMode(mode);
3479 if (res != OK) {
3480 return res;
3481 }
3482 }
3483
3484 return OK;
3485}
3486
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003487status_t CameraService::BasicClient::finishCameraStreamingOps() {
3488 ATRACE_CALL();
3489
3490 if (!mOpsActive) {
3491 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
3492 return INVALID_OPERATION;
3493 }
3494 if (!mOpsStreaming) {
3495 ALOGV("%s: Streaming not active!", __FUNCTION__);
3496 return OK;
3497 }
3498
3499 if (mAppOpsManager != nullptr) {
3500 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
3501 mClientPackageName, mClientFeatureId);
3502 mOpsStreaming = false;
3503 }
3504
3505 return OK;
3506}
3507
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003508status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003509 ATRACE_CALL();
3510
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003511 if (mOpsStreaming) {
3512 // Make sure we've notified everyone about camera stopping
3513 finishCameraStreamingOps();
3514 }
3515
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003516 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003517 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003518 mOpsActive = false;
3519
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01003520 // This function is called when a client disconnects. This should
3521 // release the camera, but actually only if it was in a proper
3522 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003523 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01003524 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003525
Ruben Brunkcc776712015-02-17 20:18:47 -08003526 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003527 sCameraService->updateStatus(StatusInternal::PRESENT,
3528 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003529 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003530 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003531 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
3532 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08003533 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003534 mOpsCallback.clear();
3535
Emilian Peev53722fa2019-02-22 17:47:20 -08003536 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid);
3537
Shuzhen Wang695044d2020-03-06 09:02:23 -08003538 // Notify listeners of camera open/close status
3539 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
3540
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003541 return OK;
3542}
3543
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003544void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003545 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003546 if (mAppOpsManager == nullptr) {
3547 return;
3548 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003549 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003550 if (op != AppOpsManager::OP_CAMERA) {
3551 ALOGW("Unexpected app ops notification received: %d", op);
3552 return;
3553 }
3554
3555 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003556 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003557 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003558 ALOGV("checkOp returns: %d, %s ", res,
3559 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
3560 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
3561 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
3562 "UNKNOWN");
3563
Shuzhen Wang64900852021-02-05 09:03:29 -08003564 if (res == AppOpsManager::MODE_ERRORED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003565 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003566 String8(mClientPackageName).string());
Svet Ganova453d0d2018-01-11 15:37:58 -08003567 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08003568 } else if (res == AppOpsManager::MODE_IGNORED) {
3569 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Evan Severson09ab4002021-02-10 14:15:19 -08003570 bool isCameraPrivacyEnabled =
3571 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled(
3572 multiuser_get_user_id(mClientUid));
Shuzhen Wang64900852021-02-05 09:03:29 -08003573 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d",
3574 mCameraIdStr.string(), String8(mClientPackageName).string(),
3575 mUidIsTrusted, isUidActive);
3576 // If the calling Uid is trusted (a native service), or the client Uid is active (WAR for
3577 // b/175320666), the AppOpsManager could return MODE_IGNORED. Do not treat such cases as
3578 // error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02003579 if (!mUidIsTrusted) {
3580 if (isUidActive && isCameraPrivacyEnabled && supportsCameraMute()) {
3581 setCameraMute(true);
3582 } else if (!isUidActive
3583 || (isCameraPrivacyEnabled && !supportsCameraMute())) {
3584 block();
3585 }
Shuzhen Wang64900852021-02-05 09:03:29 -08003586 }
Evan Severson09ab4002021-02-10 14:15:19 -08003587 } else if (res == AppOpsManager::MODE_ALLOWED) {
3588 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003589 }
3590}
3591
Svet Ganova453d0d2018-01-11 15:37:58 -08003592void CameraService::BasicClient::block() {
3593 ATRACE_CALL();
3594
3595 // Reset the client PID to allow server-initiated disconnect,
3596 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003597 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08003598 CaptureResultExtras resultExtras; // a dummy result (invalid)
3599 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
3600 disconnect();
3601}
3602
Mathias Agopian65ab4712010-07-14 17:59:35 -07003603// ----------------------------------------------------------------------------
3604
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003605void CameraService::Client::notifyError(int32_t errorCode,
Jianing Weicb0652e2014-03-12 18:29:36 -07003606 const CaptureResultExtras& resultExtras) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08003607 (void) resultExtras;
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003608 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07003609 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
3610 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
3611 api1ErrorCode = CAMERA_ERROR_DISABLED;
3612 }
3613 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003614 } else {
3615 ALOGE("mRemoteCallback is NULL!!");
3616 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003617}
3618
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003619// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003620binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003621 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003622 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08003623}
3624
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003625bool CameraService::Client::canCastToApiClient(apiLevel level) const {
3626 return level == API_1;
3627}
3628
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003629CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
3630 mClient(client) {
3631}
3632
3633void CameraService::Client::OpsCallback::opChanged(int32_t op,
3634 const String16& packageName) {
3635 sp<BasicClient> client = mClient.promote();
3636 if (client != NULL) {
3637 client->opChanged(op, packageName);
3638 }
3639}
3640
Mathias Agopian65ab4712010-07-14 17:59:35 -07003641// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08003642// UidPolicy
3643// ----------------------------------------------------------------------------
3644
3645void CameraService::UidPolicy::registerSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003646 Mutex::Autolock _l(mUidLock);
3647
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003648 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07003649 status_t res = mAm.linkToDeath(this);
3650 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08003651 | ActivityManager::UID_OBSERVER_IDLE
Emilian Peev53722fa2019-02-22 17:47:20 -08003652 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganova453d0d2018-01-11 15:37:58 -08003653 ActivityManager::PROCESS_STATE_UNKNOWN,
3654 String16("cameraserver"));
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003655 if (res == OK) {
3656 mRegistered = true;
3657 ALOGV("UidPolicy: Registered with ActivityManager");
3658 }
Svet Ganova453d0d2018-01-11 15:37:58 -08003659}
3660
3661void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003662 Mutex::Autolock _l(mUidLock);
3663
Steven Moreland2f348142019-07-02 15:59:07 -07003664 mAm.unregisterUidObserver(this);
3665 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003666 mRegistered = false;
3667 mActiveUids.clear();
3668 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08003669}
3670
3671void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
3672 onUidIdle(uid, disabled);
3673}
3674
3675void CameraService::UidPolicy::onUidActive(uid_t uid) {
3676 Mutex::Autolock _l(mUidLock);
3677 mActiveUids.insert(uid);
3678}
3679
3680void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
3681 bool deleted = false;
3682 {
3683 Mutex::Autolock _l(mUidLock);
3684 if (mActiveUids.erase(uid) > 0) {
3685 deleted = true;
3686 }
3687 }
3688 if (deleted) {
3689 sp<CameraService> service = mService.promote();
3690 if (service != nullptr) {
3691 service->blockClientsForUid(uid);
3692 }
3693 }
3694}
3695
Emilian Peev53722fa2019-02-22 17:47:20 -08003696void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07003697 int64_t procStateSeq __unused, int32_t capability __unused) {
Emilian Peev53722fa2019-02-22 17:47:20 -08003698 bool procStateChange = false;
3699 {
3700 Mutex::Autolock _l(mUidLock);
3701 if ((mMonitoredUids.find(uid) != mMonitoredUids.end()) &&
3702 (mMonitoredUids[uid].first != procState)) {
3703 mMonitoredUids[uid].first = procState;
3704 procStateChange = true;
3705 }
3706 }
3707
3708 if (procStateChange) {
3709 sp<CameraService> service = mService.promote();
3710 if (service != nullptr) {
3711 service->notifyMonitoredUids();
3712 }
3713 }
3714}
3715
3716void CameraService::UidPolicy::registerMonitorUid(uid_t uid) {
3717 Mutex::Autolock _l(mUidLock);
3718 auto it = mMonitoredUids.find(uid);
3719 if (it != mMonitoredUids.end()) {
3720 it->second.second++;
3721 } else {
3722 mMonitoredUids.emplace(
3723 std::pair<uid_t, std::pair<int32_t, size_t>> (uid,
3724 std::pair<int32_t, size_t> (ActivityManager::PROCESS_STATE_NONEXISTENT, 1)));
3725 }
3726}
3727
3728void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid) {
3729 Mutex::Autolock _l(mUidLock);
3730 auto it = mMonitoredUids.find(uid);
3731 if (it != mMonitoredUids.end()) {
3732 it->second.second--;
3733 if (it->second.second == 0) {
3734 mMonitoredUids.erase(it);
3735 }
3736 } else {
3737 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
3738 }
3739}
3740
Svet Ganov7b4ab782018-03-25 12:48:10 -07003741bool CameraService::UidPolicy::isUidActive(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003742 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003743 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003744}
3745
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003746static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
3747static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003748
Svet Ganov7b4ab782018-03-25 12:48:10 -07003749bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003750 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003751 // If activity manager is unreachable, assume everything is active
3752 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003753 return true;
3754 }
3755 auto it = mOverrideUids.find(uid);
3756 if (it != mOverrideUids.end()) {
3757 return it->second;
3758 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003759 bool active = mActiveUids.find(uid) != mActiveUids.end();
3760 if (!active) {
3761 // We want active UIDs to always access camera with their first attempt since
3762 // there is no guarantee the app is robustly written and would retry getting
3763 // the camera on failure. The inverse case is not a problem as we would take
3764 // camera away soon once we get the callback that the uid is no longer active.
3765 ActivityManager am;
3766 // Okay to access with a lock held as UID changes are dispatched without
3767 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07003768 int64_t startTimeMillis = 0;
3769 do {
3770 // TODO: Fix this b/109950150!
3771 // Okay this is a hack. There is a race between the UID turning active and
3772 // activity being resumed. The proper fix is very risky, so we temporary add
3773 // some polling which should happen pretty rarely anyway as the race is hard
3774 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003775 active = mActiveUids.find(uid) != mActiveUids.end();
Hui Yu12c7ec72020-05-04 17:40:52 +00003776 if (!active) active = am.isUidActive(uid, callingPackage);
Svet Ganov94ec46f2018-06-08 15:03:46 -07003777 if (active) {
3778 break;
3779 }
3780 if (startTimeMillis <= 0) {
3781 startTimeMillis = uptimeMillis();
3782 }
3783 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003784 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003785 if (remainingTimeMillis <= 0) {
3786 break;
3787 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003788 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
3789
3790 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003791 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003792 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003793 } while (true);
3794
Svet Ganov7b4ab782018-03-25 12:48:10 -07003795 if (active) {
3796 // Now that we found out the UID is actually active, cache that
3797 mActiveUids.insert(uid);
3798 }
3799 }
3800 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08003801}
3802
Varun Shahb42f1eb2019-04-16 14:45:13 -07003803int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
3804 Mutex::Autolock _l(mUidLock);
3805 return getProcStateLocked(uid);
3806}
3807
3808int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
3809 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
3810 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
3811 procState = mMonitoredUids[uid].first;
3812 }
3813 return procState;
3814}
3815
Svet Ganov7b4ab782018-03-25 12:48:10 -07003816void CameraService::UidPolicy::UidPolicy::addOverrideUid(uid_t uid,
3817 String16 callingPackage, bool active) {
3818 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08003819}
3820
Svet Ganov7b4ab782018-03-25 12:48:10 -07003821void CameraService::UidPolicy::removeOverrideUid(uid_t uid, String16 callingPackage) {
3822 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08003823}
3824
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003825void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
3826 Mutex::Autolock _l(mUidLock);
3827 ALOGV("UidPolicy: ActivityManager has died");
3828 mRegistered = false;
3829 mActiveUids.clear();
3830}
3831
Svet Ganov7b4ab782018-03-25 12:48:10 -07003832void CameraService::UidPolicy::updateOverrideUid(uid_t uid, String16 callingPackage,
3833 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003834 bool wasActive = false;
3835 bool isActive = false;
3836 {
3837 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003838 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003839 mOverrideUids.erase(uid);
3840 if (insert) {
3841 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
3842 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003843 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003844 }
3845 if (wasActive != isActive && !isActive) {
3846 sp<CameraService> service = mService.promote();
3847 if (service != nullptr) {
3848 service->blockClientsForUid(uid);
3849 }
3850 }
3851}
3852
3853// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08003854// SensorPrivacyPolicy
3855// ----------------------------------------------------------------------------
3856void CameraService::SensorPrivacyPolicy::registerSelf() {
3857 Mutex::Autolock _l(mSensorPrivacyLock);
3858 if (mRegistered) {
3859 return;
3860 }
Evan Severson09ab4002021-02-10 14:15:19 -08003861 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08003862 mSpm.addSensorPrivacyListener(this);
3863 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
3864 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003865 if (res == OK) {
3866 mRegistered = true;
3867 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
3868 }
3869}
3870
3871void CameraService::SensorPrivacyPolicy::unregisterSelf() {
3872 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08003873 mSpm.removeSensorPrivacyListener(this);
3874 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003875 mRegistered = false;
3876 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
3877}
3878
3879bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
3880 Mutex::Autolock _l(mSensorPrivacyLock);
3881 return mSensorPrivacyEnabled;
3882}
3883
Evan Severson09ab4002021-02-10 14:15:19 -08003884bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled(userid_t userId) {
3885 if (!hasCameraPrivacyFeature()) {
3886 return false;
3887 }
3888 return mSpm.isIndividualSensorPrivacyEnabled(userId,
3889 SensorPrivacyManager::INDIVIDUAL_SENSOR_CAMERA);
3890}
3891
Michael Grooverd1d435a2018-12-18 17:39:42 -08003892binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
3893 {
3894 Mutex::Autolock _l(mSensorPrivacyLock);
3895 mSensorPrivacyEnabled = enabled;
3896 }
3897 // if sensor privacy is enabled then block all clients from accessing the camera
Evan Severson09ab4002021-02-10 14:15:19 -08003898 if (enabled) {
3899 sp<CameraService> service = mService.promote();
3900 if (service != nullptr) {
3901 service->blockAllClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08003902 }
3903 }
3904 return binder::Status::ok();
3905}
3906
3907void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
3908 Mutex::Autolock _l(mSensorPrivacyLock);
3909 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
3910 mRegistered = false;
3911}
3912
Evan Severson09ab4002021-02-10 14:15:19 -08003913bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Severson671806e2021-04-20 16:44:53 -07003914 return mSpm.supportsSensorToggle(SensorPrivacyManager::INDIVIDUAL_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08003915}
3916
Michael Grooverd1d435a2018-12-18 17:39:42 -08003917// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003918// CameraState
3919// ----------------------------------------------------------------------------
3920
3921CameraService::CameraState::CameraState(const String8& id, int cost,
Shuzhen Wang403af6d2021-12-21 00:08:43 +00003922 const std::set<String8>& conflicting, SystemCameraKind systemCameraKind,
3923 const std::vector<std::string>& physicalCameras) : mId(id),
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003924 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
Shuzhen Wang403af6d2021-12-21 00:08:43 +00003925 mSystemCameraKind(systemCameraKind), mPhysicalCameras(physicalCameras) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08003926
3927CameraService::CameraState::~CameraState() {}
3928
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003929CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003930 Mutex::Autolock lock(mStatusLock);
3931 return mStatus;
3932}
3933
Shuzhen Wang43858162020-01-10 13:42:15 -08003934std::vector<String8> CameraService::CameraState::getUnavailablePhysicalIds() const {
3935 Mutex::Autolock lock(mStatusLock);
3936 std::vector<String8> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
3937 return res;
3938}
3939
Ruben Brunkcc776712015-02-17 20:18:47 -08003940CameraParameters CameraService::CameraState::getShimParams() const {
3941 return mShimParams;
3942}
3943
3944void CameraService::CameraState::setShimParams(const CameraParameters& params) {
3945 mShimParams = params;
3946}
3947
3948int CameraService::CameraState::getCost() const {
3949 return mCost;
3950}
3951
3952std::set<String8> CameraService::CameraState::getConflicting() const {
3953 return mConflicting;
3954}
3955
3956String8 CameraService::CameraState::getId() const {
3957 return mId;
3958}
3959
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003960SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
3961 return mSystemCameraKind;
3962}
3963
Shuzhen Wang403af6d2021-12-21 00:08:43 +00003964bool CameraService::CameraState::containsPhysicalCamera(const std::string& physicalCameraId) const {
3965 return std::find(mPhysicalCameras.begin(), mPhysicalCameras.end(), physicalCameraId)
3966 != mPhysicalCameras.end();
3967}
3968
Shuzhen Wang43858162020-01-10 13:42:15 -08003969bool CameraService::CameraState::addUnavailablePhysicalId(const String8& physicalId) {
3970 Mutex::Autolock lock(mStatusLock);
3971 auto result = mUnavailablePhysicalIds.insert(physicalId);
3972 return result.second;
3973}
3974
3975bool CameraService::CameraState::removeUnavailablePhysicalId(const String8& physicalId) {
3976 Mutex::Autolock lock(mStatusLock);
3977 auto count = mUnavailablePhysicalIds.erase(physicalId);
3978 return count > 0;
3979}
3980
Shuzhen Wange7aa0342021-08-03 11:29:47 -07003981void CameraService::CameraState::setClientPackage(const String8& clientPackage) {
3982 Mutex::Autolock lock(mStatusLock);
3983 mClientPackage = clientPackage;
3984}
3985
3986String8 CameraService::CameraState::getClientPackage() const {
3987 Mutex::Autolock lock(mStatusLock);
3988 return mClientPackage;
3989}
3990
Ruben Brunkcc776712015-02-17 20:18:47 -08003991// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07003992// ClientEventListener
3993// ----------------------------------------------------------------------------
3994
3995void CameraService::ClientEventListener::onClientAdded(
3996 const resource_policy::ClientDescriptor<String8,
3997 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003998 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003999 if (basicClient.get() != nullptr) {
4000 BatteryNotifier& notifier(BatteryNotifier::getInstance());
4001 notifier.noteStartCamera(descriptor.getKey(),
4002 static_cast<int>(basicClient->getClientUid()));
4003 }
4004}
4005
4006void CameraService::ClientEventListener::onClientRemoved(
4007 const resource_policy::ClientDescriptor<String8,
4008 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07004009 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07004010 if (basicClient.get() != nullptr) {
4011 BatteryNotifier& notifier(BatteryNotifier::getInstance());
4012 notifier.noteStopCamera(descriptor.getKey(),
4013 static_cast<int>(basicClient->getClientUid()));
4014 }
4015}
4016
4017
4018// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08004019// CameraClientManager
4020// ----------------------------------------------------------------------------
4021
Ruben Brunk99e69712015-05-26 17:25:07 -07004022CameraService::CameraClientManager::CameraClientManager() {
4023 setListener(std::make_shared<ClientEventListener>());
4024}
4025
Ruben Brunkcc776712015-02-17 20:18:47 -08004026CameraService::CameraClientManager::~CameraClientManager() {}
4027
4028sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
4029 const String8& id) const {
4030 auto descriptor = get(id);
4031 if (descriptor == nullptr) {
4032 return sp<BasicClient>{nullptr};
4033 }
4034 return descriptor->getValue();
4035}
4036
4037String8 CameraService::CameraClientManager::toString() const {
4038 auto all = getAll();
4039 String8 ret("[");
4040 bool hasAny = false;
4041 for (auto& i : all) {
4042 hasAny = true;
4043 String8 key = i->getKey();
4044 int32_t cost = i->getCost();
4045 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00004046 int32_t score = i->getPriority().getScore();
4047 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08004048 auto conflicting = i->getConflicting();
4049 auto clientSp = i->getValue();
4050 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07004051 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08004052 if (clientSp.get() != nullptr) {
4053 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07004054 uid_t clientUid = clientSp->getClientUid();
4055 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08004056 }
Emilian Peev8131a262017-02-01 12:33:43 +00004057 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
4058 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08004059
Ruben Brunk6267b532015-04-30 17:44:07 -07004060 if (clientSp.get() != nullptr) {
4061 ret.appendFormat("User Id: %d, ", clientUserId);
4062 }
Ruben Brunkcc776712015-02-17 20:18:47 -08004063 if (packageName.size() != 0) {
4064 ret.appendFormat("Client Package Name: %s", packageName.string());
4065 }
4066
4067 ret.append(", Conflicting Client Devices: {");
4068 for (auto& j : conflicting) {
4069 ret.appendFormat("%s, ", j.string());
4070 }
4071 ret.append("})");
4072 }
4073 if (hasAny) ret.append("\n");
4074 ret.append("]\n");
4075 return ret;
4076}
4077
4078CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
4079 const String8& key, const sp<BasicClient>& value, int32_t cost,
Emilian Peev8131a262017-02-01 12:33:43 +00004080 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00004081 int32_t state, int32_t oomScoreOffset) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004082
Steven Moreland89a2c5c2020-01-31 15:02:25 -08004083 bool isVendorClient = getCurrentServingCall() == BinderCallType::HWBINDER;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07004084 int32_t score_adj = isVendorClient ? kVendorClientScore : score;
4085 int32_t state_adj = isVendorClient ? kVendorClientState: state;
4086
Ruben Brunkcc776712015-02-17 20:18:47 -08004087 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00004088 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj, isVendorClient,
4089 oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08004090}
4091
4092CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00004093 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
4094 int32_t oomScoreOffset) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004095 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00004096 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00004097 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08004098}
4099
4100// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08004101// InjectionStatusListener
4102// ----------------------------------------------------------------------------
4103
4104void CameraService::InjectionStatusListener::addListener(
4105 const sp<ICameraInjectionCallback>& callback) {
4106 Mutex::Autolock lock(mListenerLock);
4107 if (mCameraInjectionCallback) return;
4108 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
4109 if (res == OK) {
4110 mCameraInjectionCallback = callback;
4111 }
4112}
4113
4114void CameraService::InjectionStatusListener::removeListener() {
4115 Mutex::Autolock lock(mListenerLock);
4116 if (mCameraInjectionCallback == nullptr) {
4117 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
4118 return;
4119 }
4120 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
4121 mCameraInjectionCallback = nullptr;
4122}
4123
4124void CameraService::InjectionStatusListener::notifyInjectionError(
Cliff Wud3a05312021-04-26 23:07:31 +08004125 String8 injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08004126 if (mCameraInjectionCallback == nullptr) {
4127 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
4128 return;
4129 }
Cliff Wud3a05312021-04-26 23:07:31 +08004130
4131 switch (err) {
4132 case -ENODEV:
4133 mCameraInjectionCallback->onInjectionError(
4134 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4135 ALOGE("No camera device with ID \"%s\" currently available!",
4136 injectedCamId.string());
4137 break;
4138 case -EBUSY:
4139 mCameraInjectionCallback->onInjectionError(
4140 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4141 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
4142 injectedCamId.string());
4143 break;
4144 case DEAD_OBJECT:
4145 mCameraInjectionCallback->onInjectionError(
4146 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4147 ALOGE("Camera ID \"%s\" object is dead!",
4148 injectedCamId.string());
4149 break;
4150 case INVALID_OPERATION:
4151 mCameraInjectionCallback->onInjectionError(
4152 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4153 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
4154 injectedCamId.string());
4155 break;
4156 case UNKNOWN_TRANSACTION:
4157 mCameraInjectionCallback->onInjectionError(
4158 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
4159 ALOGE("Camera ID \"%s\" method doesn't support!",
4160 injectedCamId.string());
4161 break;
4162 default:
4163 mCameraInjectionCallback->onInjectionError(
4164 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
4165 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
4166 strerror(-err), err, injectedCamId.string());
4167 }
Cliff Wud8cae102021-03-11 01:37:42 +08004168}
4169
4170void CameraService::InjectionStatusListener::binderDied(
4171 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08004172 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
4173 auto parent = mParent.promote();
4174 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08004175 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
4176 if (clientDescriptor != nullptr) {
4177 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
4178 baseClientPtr->stopInjection();
4179 }
Cliff Wu3b268182021-07-06 15:44:43 +08004180 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08004181 }
4182}
4183
4184// ----------------------------------------------------------------------------
4185// CameraInjectionSession
4186// ----------------------------------------------------------------------------
4187
4188binder::Status CameraService::CameraInjectionSession::stopInjection() {
4189 Mutex::Autolock lock(mInjectionSessionLock);
4190 auto parent = mParent.promote();
4191 if (parent == nullptr) {
4192 ALOGE("CameraInjectionSession: Parent is gone");
4193 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
4194 "Camera service encountered error");
4195 }
Cliff Wud3a05312021-04-26 23:07:31 +08004196
4197 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08004198 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
4199 if (clientDescriptor != nullptr) {
4200 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
4201 res = baseClientPtr->stopInjection();
4202 if (res != OK) {
4203 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
4204 " ret != NO_ERROR: %d", res);
4205 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
4206 "Camera session encountered error");
4207 }
4208 }
Cliff Wu3b268182021-07-06 15:44:43 +08004209 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08004210 return binder::Status::ok();
4211}
4212
4213// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07004214
4215static const int kDumpLockRetries = 50;
4216static const int kDumpLockSleep = 60000;
4217
4218static bool tryLock(Mutex& mutex)
4219{
4220 bool locked = false;
4221 for (int i = 0; i < kDumpLockRetries; ++i) {
4222 if (mutex.tryLock() == NO_ERROR) {
4223 locked = true;
4224 break;
4225 }
4226 usleep(kDumpLockSleep);
4227 }
4228 return locked;
4229}
4230
Rucha Katakwardf223072021-06-15 10:21:00 -07004231void CameraService::cacheDump() {
4232 if (mMemFd != -1) {
4233 const Vector<String16> args;
4234 ATRACE_CALL();
4235 // Acquiring service lock here will avoid the deadlock since
4236 // cacheDump will not be called during the second disconnect.
4237 Mutex::Autolock lock(mServiceLock);
4238
4239 Mutex::Autolock l(mCameraStatesLock);
4240 // Start collecting the info for open sessions and store it in temp file.
4241 for (const auto& state : mCameraStates) {
4242 String8 cameraId = state.first;
4243 auto clientDescriptor = mActiveClientManager.get(cameraId);
4244 if (clientDescriptor != nullptr) {
4245 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.string());
4246 // Log the current open session info before device is disconnected.
4247 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
4248 }
4249 }
4250 }
4251}
4252
Mathias Agopian65ab4712010-07-14 17:59:35 -07004253status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004254 ATRACE_CALL();
4255
Jayant Chowdhary5216b212019-07-17 09:26:23 -07004256 if (checkCallingPermission(sDumpPermission) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004257 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07004258 CameraThreadState::getCallingPid(),
4259 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004260 return NO_ERROR;
4261 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004262 bool locked = tryLock(mServiceLock);
4263 // failed to lock - CameraService is probably deadlocked
4264 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004265 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004266 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004267
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004268 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004269 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07004270
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004271 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004272 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08004273
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004274 if (locked) mServiceLock.unlock();
4275 return NO_ERROR;
4276 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004277 dprintf(fd, "\n== Service global info: ==\n\n");
4278 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004279 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07004280 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
4281 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004282 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
4283 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
4284 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004285 String8 activeClientString = mActiveClientManager.toString();
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004286 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
4287 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004288
4289 dumpEventLog(fd);
4290
4291 bool stateLocked = tryLock(mCameraStatesLock);
4292 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004293 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004294 }
4295
Emilian Peevbd8c5032018-02-14 23:05:40 +00004296 int argSize = args.size();
4297 for (int i = 0; i < argSize; i++) {
4298 if (args[i] == TagMonitor::kMonitorOption) {
4299 if (i + 1 < argSize) {
4300 mMonitorTags = String8(args[i + 1]);
4301 }
4302 break;
4303 }
4304 }
4305
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004306 for (auto& state : mCameraStates) {
4307 String8 cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004308
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004309 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004310
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004311 CameraParameters p = state.second->getShimParams();
4312 if (!p.isEmpty()) {
4313 dprintf(fd, " Camera1 API shim is using parameters:\n ");
4314 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004315 }
4316
4317 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08004318 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07004319 // log the current open session info
4320 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08004321 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07004322 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004323 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004324
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004325 }
4326
4327 if (stateLocked) mCameraStatesLock.unlock();
4328
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004329 if (locked) mServiceLock.unlock();
4330
Emilian Peevf53f66e2017-04-11 14:29:43 +01004331 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004332
4333 dprintf(fd, "\n== Vendor tags: ==\n\n");
4334
4335 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
4336 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00004337 sp<VendorTagDescriptorCache> cache =
4338 VendorTagDescriptorCache::getGlobalVendorTagCache();
4339 if (cache == NULL) {
4340 dprintf(fd, "No vendor tags.\n");
4341 } else {
4342 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
4343 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004344 } else {
4345 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
4346 }
4347
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004348 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004349 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004350 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004351
4352 // Process dump arguments, if any
4353 int n = args.size();
4354 String16 verboseOption("-v");
4355 String16 unreachableOption("--unreachable");
4356 for (int i = 0; i < n; i++) {
4357 if (args[i] == verboseOption) {
4358 // change logging level
4359 if (i + 1 >= n) continue;
4360 String8 levelStr(args[i+1]);
4361 int level = atoi(levelStr.string());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004362 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004363 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004364 } else if (args[i] == unreachableOption) {
4365 // Dump memory analysis
4366 // TODO - should limit be an argument parameter?
4367 UnreachableMemoryInfo info;
4368 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
4369 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004370 dprintf(fd, "\n== Unable to dump unreachable memory. "
4371 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004372 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004373 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004374 std::string s = info.ToString(/*log_contents*/ true);
4375 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004376 }
4377 }
4378 }
Rucha Katakwardf223072021-06-15 10:21:00 -07004379
4380 bool serviceLocked = tryLock(mServiceLock);
4381
4382 // Dump info from previous open sessions.
4383 // Reposition the offset to beginning of the file before reading
4384
4385 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
4386 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
4387 ssize_t size_read;
4388 char buf[4096];
4389 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
4390 // Read data from file to a small buffer and write it to fd.
4391 write(fd, buf, size_read);
4392 if (size_read == -1) {
4393 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
4394 break;
4395 }
4396 }
4397 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
4398 } else {
4399 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
4400 }
4401
4402 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004403 return NO_ERROR;
4404}
4405
Rucha Katakwardf223072021-06-15 10:21:00 -07004406void CameraService::dumpOpenSessionClientLogs(int fd,
4407 const Vector<String16>& args, const String8& cameraId) {
4408 auto clientDescriptor = mActiveClientManager.get(cameraId);
4409 dprintf(fd, " Device %s is open. Client instance dump:\n",
4410 cameraId.string());
4411 dprintf(fd, " Client priority score: %d state: %d\n",
4412 clientDescriptor->getPriority().getScore(),
4413 clientDescriptor->getPriority().getState());
4414 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
4415
4416 auto client = clientDescriptor->getValue();
4417 dprintf(fd, " Client package: %s\n",
4418 String8(client->getPackageName()).string());
4419
4420 client->dumpClient(fd, args);
4421}
4422
4423void CameraService::dumpClosedSessionClientLogs(int fd, const String8& cameraId) {
4424 dprintf(fd, " Device %s is closed, no client instance\n",
4425 cameraId.string());
4426}
4427
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004428void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004429 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004430
4431 Mutex::Autolock l(mLogLock);
4432 for (const auto& msg : mEventLog) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004433 dprintf(fd, " %s\n", msg.string());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004434 }
4435
4436 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004437 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004438 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004439 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004440 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004441 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004442}
4443
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004444void CameraService::cacheClientTagDumpIfNeeded(const char *cameraId, BasicClient* client) {
4445 Mutex::Autolock lock(mLogLock);
4446 if (!isClientWatchedLocked(client)) { return; }
4447
4448 std::vector<std::string> dumpVector;
4449 client->dumpWatchedEventsToVector(dumpVector);
4450
4451 if (dumpVector.empty()) { return; }
4452
Avichal Rakesh882c08b2021-12-09 17:47:07 -08004453 std::string dumpString;
4454
4455 String8 currentTime = getFormattedCurrentTime();
4456 dumpString += "Cached @ ";
4457 dumpString += currentTime.string();
4458 dumpString += "\n"; // First line is the timestamp of when client is cached.
4459
4460
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08004461 const String16 &packageName = client->getPackageName();
4462
4463 String8 packageName8 = String8(packageName);
4464 const char *printablePackageName = packageName8.lockBuffer(packageName.size());
4465
Avichal Rakesh882c08b2021-12-09 17:47:07 -08004466
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004467 size_t i = dumpVector.size();
4468
4469 // Store the string in reverse order (latest last)
4470 while (i > 0) {
4471 i--;
4472 dumpString += cameraId;
4473 dumpString += ":";
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08004474 dumpString += printablePackageName;
4475 dumpString += " ";
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004476 dumpString += dumpVector[i]; // implicitly ends with '\n'
4477 }
4478
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08004479 packageName8.unlockBuffer();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004480 mWatchedClientsDumpCache[packageName] = dumpString;
4481}
4482
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004483void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004484 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004485 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
4486 if (mTorchClientMap[i] == who) {
4487 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004488 String8 cameraId = mTorchClientMap.keyAt(i);
4489 status_t res = mFlashlight->setTorchMode(cameraId, false);
4490 if (res) {
4491 ALOGE("%s: torch client died but couldn't turn off torch: "
4492 "%s (%d)", __FUNCTION__, strerror(-res), res);
4493 return;
4494 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004495 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004496 break;
4497 }
4498 }
4499}
4500
Ruben Brunkcc776712015-02-17 20:18:47 -08004501/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07004502
Igor Murashkin294d0ec2012-10-05 10:44:57 -07004503 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07004504 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
4505 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07004506 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08004507 // PID here is approximate and can be wrong.
Jayant Chowdhary12361932018-08-27 14:46:13 -07004508 logClientDied(CameraThreadState::getCallingPid(), String8("Binder died unexpectedly"));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004509
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004510 // check torch client
4511 handleTorchClientBinderDied(who);
4512
4513 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08004514 if(!evictClientIdByRemote(who)) {
4515 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07004516 return;
4517 }
4518
Ruben Brunkcc776712015-02-17 20:18:47 -08004519 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
4520 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07004521}
4522
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004523void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004524 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08004525}
4526
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004527void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
4528 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004529 // Do not lock mServiceLock here or can get into a deadlock from
4530 // connect() -> disconnect -> updateStatus
4531
4532 auto state = getCameraState(cameraId);
4533
4534 if (state == nullptr) {
4535 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
4536 cameraId.string());
4537 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07004538 }
4539
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004540 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
4541 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
4542 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
4543 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
4544 return;
4545 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004546
4547 // Collect the logical cameras without holding mStatusLock in updateStatus
4548 // as that can lead to a deadlock(b/162192331).
4549 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08004550 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08004551 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07004552 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004553 &logicalCameraIds]
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004554 (const String8& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004555
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004556 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004557 // Update torch status if it has a flash unit.
4558 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004559 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004560 if (getTorchStatusLocked(cameraId, &torchStatus) !=
4561 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004562 TorchModeStatus newTorchStatus =
4563 status == StatusInternal::PRESENT ?
4564 TorchModeStatus::AVAILABLE_OFF :
4565 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004566 if (torchStatus != newTorchStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07004567 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004568 }
4569 }
Ruben Brunkcc776712015-02-17 20:18:47 -08004570 }
4571
4572 Mutex::Autolock lock(mStatusListenerLock);
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004573 notifyPhysicalCameraStatusLocked(mapToInterface(status), String16(cameraId),
4574 logicalCameraIds, deviceKind);
Shuzhen Wang43858162020-01-10 13:42:15 -08004575
Ruben Brunkcc776712015-02-17 20:18:47 -08004576 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07004577 bool isVendorListener = listener->isVendorListener();
4578 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
4579 listener->getListenerPid(), listener->getListenerUid()) ||
Shuzhen Wangb8259792021-05-27 09:27:06 -07004580 isVendorListener) {
4581 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07004582 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08004583 continue;
4584 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07004585 listener->getListener()->onStatusChanged(mapToInterface(status),
Emilian Peev53722fa2019-02-22 17:47:20 -08004586 String16(cameraId));
Ruben Brunkcc776712015-02-17 20:18:47 -08004587 }
4588 });
Igor Murashkincba2c162013-03-20 15:56:31 -07004589}
4590
Shuzhen Wang695044d2020-03-06 09:02:23 -08004591void CameraService::updateOpenCloseStatus(const String8& cameraId, bool open,
4592 const String16& clientPackageName) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07004593 auto state = getCameraState(cameraId);
4594 if (state == nullptr) {
4595 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
4596 cameraId.string());
4597 return;
4598 }
4599 if (open) {
4600 state->setClientPackage(String8(clientPackageName));
4601 } else {
4602 state->setClientPackage(String8::empty());
4603 }
4604
Shuzhen Wang695044d2020-03-06 09:02:23 -08004605 Mutex::Autolock lock(mStatusListenerLock);
4606
4607 for (const auto& it : mListenerList) {
4608 if (!it->isOpenCloseCallbackAllowed()) {
4609 continue;
4610 }
4611
4612 binder::Status ret;
4613 String16 cameraId64(cameraId);
4614 if (open) {
4615 ret = it->getListener()->onCameraOpened(cameraId64, clientPackageName);
4616 } else {
4617 ret = it->getListener()->onCameraClosed(cameraId64);
4618 }
4619 if (!ret.isOk()) {
4620 ALOGE("%s: Failed to trigger onCameraOpened/onCameraClosed callback: %d", __FUNCTION__,
4621 ret.exceptionCode());
4622 }
4623 }
4624}
4625
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004626template<class Func>
4627void CameraService::CameraState::updateStatus(StatusInternal status,
4628 const String8& cameraId,
4629 std::initializer_list<StatusInternal> rejectSourceStates,
4630 Func onStatusUpdatedLocked) {
4631 Mutex::Autolock lock(mStatusLock);
4632 StatusInternal oldStatus = mStatus;
4633 mStatus = status;
4634
4635 if (oldStatus == status) {
4636 return;
4637 }
4638
4639 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
4640 cameraId.string(), oldStatus, status);
4641
4642 if (oldStatus == StatusInternal::NOT_PRESENT &&
4643 (status != StatusInternal::PRESENT &&
4644 status != StatusInternal::ENUMERATING)) {
4645
4646 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
4647 __FUNCTION__);
4648 mStatus = oldStatus;
4649 return;
4650 }
4651
4652 /**
4653 * Sometimes we want to conditionally do a transition.
4654 * For example if a client disconnects, we want to go to PRESENT
4655 * only if we weren't already in NOT_PRESENT or ENUMERATING.
4656 */
4657 for (auto& rejectStatus : rejectSourceStates) {
4658 if (oldStatus == rejectStatus) {
4659 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
4660 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
4661 mStatus = oldStatus;
4662 return;
4663 }
4664 }
4665
4666 onStatusUpdatedLocked(cameraId, status);
4667}
4668
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004669status_t CameraService::getTorchStatusLocked(
4670 const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004671 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004672 if (!status) {
4673 return BAD_VALUE;
4674 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004675 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
4676 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004677 // invalid camera ID or the camera doesn't have a flash unit
4678 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004679 }
4680
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004681 *status = mTorchStatusMap.valueAt(index);
4682 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004683}
4684
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004685status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004686 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004687 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
4688 if (index == NAME_NOT_FOUND) {
4689 return BAD_VALUE;
4690 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004691 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004692
4693 return OK;
4694}
4695
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004696std::list<String16> CameraService::getLogicalCameras(
4697 const String8& physicalCameraId) {
4698 std::list<String16> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08004699 Mutex::Autolock lock(mCameraStatesLock);
4700 for (const auto& state : mCameraStates) {
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004701 if (state.second->containsPhysicalCamera(physicalCameraId.c_str())) {
4702 retList.emplace_back(String16(state.first));
Shuzhen Wang43858162020-01-10 13:42:15 -08004703 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004704 }
4705 return retList;
4706}
4707
4708void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
4709 const String16& physicalCameraId, const std::list<String16>& logicalCameraIds,
4710 SystemCameraKind deviceKind) {
4711 // mStatusListenerLock is expected to be locked
4712 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08004713 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004714 // Note: we check only the deviceKind of the physical camera id
4715 // since, logical camera ids and their physical camera ids are
4716 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07004717 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
4718 listener->getListenerPid(), listener->getListenerUid())) {
4719 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004720 String8(physicalCameraId).c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07004721 continue;
4722 }
Shuzhen Wang43858162020-01-10 13:42:15 -08004723 listener->getListener()->onPhysicalCameraStatusChanged(status,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004724 logicalCameraId, physicalCameraId);
Shuzhen Wang43858162020-01-10 13:42:15 -08004725 }
4726 }
4727}
4728
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004729
Svet Ganova453d0d2018-01-11 15:37:58 -08004730void CameraService::blockClientsForUid(uid_t uid) {
4731 const auto clients = mActiveClientManager.getAll();
4732 for (auto& current : clients) {
4733 if (current != nullptr) {
4734 const auto basicClient = current->getValue();
4735 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
4736 basicClient->block();
4737 }
4738 }
4739 }
4740}
4741
Michael Grooverd1d435a2018-12-18 17:39:42 -08004742void CameraService::blockAllClients() {
4743 const auto clients = mActiveClientManager.getAll();
4744 for (auto& current : clients) {
4745 if (current != nullptr) {
4746 const auto basicClient = current->getValue();
4747 if (basicClient.get() != nullptr) {
4748 basicClient->block();
4749 }
4750 }
4751 }
4752}
4753
Svet Ganova453d0d2018-01-11 15:37:58 -08004754// NOTE: This is a remote API - make sure all args are validated
4755status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
4756 if (!checkCallingPermission(sManageCameraPermission, nullptr, nullptr)) {
4757 return PERMISSION_DENIED;
4758 }
4759 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
4760 return BAD_VALUE;
4761 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004762 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004763 return handleSetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07004764 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004765 return handleResetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07004766 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004767 return handleGetUidState(args, out, err);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004768 } else if (args.size() >= 2 && args[0] == String16("set-rotate-and-crop")) {
4769 return handleSetRotateAndCrop(args);
4770 } else if (args.size() >= 1 && args[0] == String16("get-rotate-and-crop")) {
4771 return handleGetRotateAndCrop(out);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004772 } else if (args.size() >= 2 && args[0] == String16("set-image-dump-mask")) {
4773 return handleSetImageDumpMask(args);
4774 } else if (args.size() >= 1 && args[0] == String16("get-image-dump-mask")) {
4775 return handleGetImageDumpMask(out);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004776 } else if (args.size() >= 2 && args[0] == String16("set-camera-mute")) {
4777 return handleSetCameraMute(args);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004778 } else if (args.size() >= 2 && args[0] == String16("watch")) {
Avichal Rakesh84147132021-11-11 17:47:11 -08004779 return handleWatchCommand(args, in, out);
Svet Ganova453d0d2018-01-11 15:37:58 -08004780 } else if (args.size() == 1 && args[0] == String16("help")) {
4781 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004782 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08004783 }
4784 printHelp(err);
4785 return BAD_VALUE;
4786}
4787
4788status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004789 String16 packageName = args[1];
4790
Svet Ganova453d0d2018-01-11 15:37:58 -08004791 bool active = false;
4792 if (args[2] == String16("active")) {
4793 active = true;
4794 } else if ((args[2] != String16("idle"))) {
4795 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
4796 return BAD_VALUE;
4797 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004798
4799 int userId = 0;
4800 if (args.size() >= 5 && args[3] == String16("--user")) {
4801 userId = atoi(String8(args[4]));
4802 }
4803
4804 uid_t uid;
4805 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
4806 return BAD_VALUE;
4807 }
4808
4809 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08004810 return NO_ERROR;
4811}
4812
4813status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004814 String16 packageName = args[1];
4815
4816 int userId = 0;
4817 if (args.size() >= 4 && args[2] == String16("--user")) {
4818 userId = atoi(String8(args[3]));
4819 }
4820
4821 uid_t uid;
4822 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004823 return BAD_VALUE;
4824 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004825
4826 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08004827 return NO_ERROR;
4828}
4829
4830status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004831 String16 packageName = args[1];
4832
4833 int userId = 0;
4834 if (args.size() >= 4 && args[2] == String16("--user")) {
4835 userId = atoi(String8(args[3]));
4836 }
4837
4838 uid_t uid;
4839 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004840 return BAD_VALUE;
4841 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004842
4843 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004844 return dprintf(out, "active\n");
4845 } else {
4846 return dprintf(out, "idle\n");
4847 }
4848}
4849
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004850status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
4851 int rotateValue = atoi(String8(args[1]));
4852 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
4853 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
4854 Mutex::Autolock lock(mServiceLock);
4855
4856 mOverrideRotateAndCropMode = rotateValue;
4857
4858 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
4859
4860 const auto clients = mActiveClientManager.getAll();
4861 for (auto& current : clients) {
4862 if (current != nullptr) {
4863 const auto basicClient = current->getValue();
4864 if (basicClient.get() != nullptr) {
4865 basicClient->setRotateAndCropOverride(rotateValue);
4866 }
4867 }
4868 }
4869
4870 return OK;
4871}
4872
4873status_t CameraService::handleGetRotateAndCrop(int out) {
4874 Mutex::Autolock lock(mServiceLock);
4875
4876 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
4877}
4878
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004879status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
4880 char *endPtr;
4881 errno = 0;
4882 String8 maskString8 = String8(args[1]);
4883 long maskValue = strtol(maskString8.c_str(), &endPtr, 10);
4884
4885 if (errno != 0) return BAD_VALUE;
4886 if (endPtr != maskString8.c_str() + maskString8.size()) return BAD_VALUE;
4887 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
4888
4889 Mutex::Autolock lock(mServiceLock);
4890
4891 mImageDumpMask = maskValue;
4892
4893 return OK;
4894}
4895
4896status_t CameraService::handleGetImageDumpMask(int out) {
4897 Mutex::Autolock lock(mServiceLock);
4898
4899 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
4900}
4901
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004902status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
4903 int muteValue = strtol(String8(args[1]), nullptr, 10);
4904 if (errno != 0) return BAD_VALUE;
4905
4906 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
4907 Mutex::Autolock lock(mServiceLock);
4908
4909 mOverrideCameraMuteMode = (muteValue == 1);
4910
4911 const auto clients = mActiveClientManager.getAll();
4912 for (auto& current : clients) {
4913 if (current != nullptr) {
4914 const auto basicClient = current->getValue();
4915 if (basicClient.get() != nullptr) {
4916 if (basicClient->supportsCameraMute()) {
4917 basicClient->setCameraMute(mOverrideCameraMuteMode);
4918 }
4919 }
4920 }
4921 }
4922
4923 return OK;
4924}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004925
Avichal Rakesh84147132021-11-11 17:47:11 -08004926status_t CameraService::handleWatchCommand(const Vector<String16>& args, int inFd, int outFd) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004927 if (args.size() >= 3 && args[1] == String16("start")) {
4928 return startWatchingTags(args, outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004929 } else if (args.size() == 2 && args[1] == String16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004930 return stopWatchingTags(outFd);
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08004931 } else if (args.size() == 2 && args[1] == String16("dump")) {
4932 return printWatchedTags(outFd);
4933 } else if (args.size() >= 2 && args[1] == String16("live")) {
4934 return printWatchedTagsUntilInterrupt(args, inFd, outFd);
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08004935 } else if (args.size() == 2 && args[1] == String16("clear")) {
4936 return clearCachedMonitoredTagDumps(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004937 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004938 dprintf(outFd, "Camera service watch commands:\n"
4939 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
4940 " starts watching the provided tags for clients with provided package\n"
4941 " recognizes tag shorthands like '3a'\n"
4942 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08004943 " dump dumps the monitoring information and exits\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004944 " stop stops watching all tags\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08004945 " live [-n <refresh_interval_ms>]\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004946 " prints the monitored information in real time\n"
Avichal Rakesh84147132021-11-11 17:47:11 -08004947 " Hit return to exit\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08004948 " clear clears all buffers storing information for watch command");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004949 return BAD_VALUE;
4950}
4951
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004952status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
4953 Mutex::Autolock lock(mLogLock);
4954 size_t tagsIdx; // index of '-m'
4955 String16 tags("");
4956 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != String16("-m"); tagsIdx++);
4957 if (tagsIdx < args.size() - 1) {
4958 tags = args[tagsIdx + 1];
4959 } else {
4960 dprintf(outFd, "No tags provided.\n");
4961 return BAD_VALUE;
4962 }
4963
4964 size_t clientsIdx; // index of '-c'
4965 String16 clients = kWatchAllClientsFlag; // watch all clients if no clients are provided
4966 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != String16("-c");
4967 clientsIdx++);
4968 if (clientsIdx < args.size() - 1) {
4969 clients = args[clientsIdx + 1];
4970 }
4971 parseClientsToWatchLocked(String8(clients));
4972
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004973 // track tags to initialize future clients with the monitoring information
4974 mMonitorTags = String8(tags);
4975
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004976 bool serviceLock = tryLock(mServiceLock);
4977 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004978 auto cameraClients = mActiveClientManager.getAll();
4979 for (const auto &clientDescriptor: cameraClients) {
4980 if (clientDescriptor == nullptr) { continue; }
4981 sp<BasicClient> client = clientDescriptor->getValue();
4982 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004983
4984 if (isClientWatchedLocked(client.get())) {
4985 client->startWatchingTags(mMonitorTags, outFd);
4986 numWatchedClients++;
4987 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004988 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004989 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
4990
4991 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004992 return OK;
4993}
4994
4995status_t CameraService::stopWatchingTags(int outFd) {
4996 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004997 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004998 mMonitorTags = String8::empty();
4999
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005000 mWatchedClientPackages.clear();
5001 mWatchedClientsDumpCache.clear();
5002
5003 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005004 auto cameraClients = mActiveClientManager.getAll();
5005 for (const auto &clientDescriptor : cameraClients) {
5006 if (clientDescriptor == nullptr) { continue; }
5007 sp<BasicClient> client = clientDescriptor->getValue();
5008 if (client.get() == nullptr) { continue; }
5009 client->stopWatchingTags(outFd);
5010 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005011 dprintf(outFd, "Stopped watching all clients.\n");
5012 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005013 return OK;
5014}
5015
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005016status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
5017 Mutex::Autolock lock(mLogLock);
5018 size_t clearedSize = mWatchedClientsDumpCache.size();
5019 mWatchedClientsDumpCache.clear();
5020 dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
5021 return OK;
5022}
5023
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005024status_t CameraService::printWatchedTags(int outFd) {
5025 Mutex::Autolock logLock(mLogLock);
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08005026 std::set<String16> connectedMonitoredClients;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005027
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005028 bool printedSomething = false; // tracks if any monitoring information was printed
5029 // (from either cached or active clients)
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005030
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005031 bool serviceLock = tryLock(mServiceLock);
5032 // get all watched clients that are currently connected
5033 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
5034 if (clientDescriptor == nullptr) { continue; }
5035
5036 sp<BasicClient> client = clientDescriptor->getValue();
5037 if (client.get() == nullptr) { continue; }
5038 if (!isClientWatchedLocked(client.get())) { continue; }
5039
5040 std::vector<std::string> dumpVector;
5041 client->dumpWatchedEventsToVector(dumpVector);
5042
5043 size_t printIdx = dumpVector.size();
5044 if (printIdx == 0) {
5045 continue;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005046 }
5047
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005048 // Print tag dumps for active client
5049 const String8 &cameraId = clientDescriptor->getKey();
5050 String8 packageName8 = String8(client->getPackageName());
5051 const char *printablePackageName = packageName8.lockBuffer(packageName8.size());
5052 dprintf(outFd, "Client: %s (active)\n", printablePackageName);
5053 while(printIdx > 0) {
5054 printIdx--;
5055 dprintf(outFd, "%s:%s %s", cameraId.string(), printablePackageName,
5056 dumpVector[printIdx].c_str());
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005057 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005058 dprintf(outFd, "\n");
5059 packageName8.unlockBuffer();
5060 printedSomething = true;
5061
5062 connectedMonitoredClients.emplace(client->getPackageName());
5063 }
5064 if (serviceLock) { mServiceLock.unlock(); }
5065
5066 // Print entries in mWatchedClientsDumpCache for clients that are not connected
5067 for (const auto &kv: mWatchedClientsDumpCache) {
5068 const String16 &package = kv.first;
5069 if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
5070 continue;
5071 }
5072
5073 dprintf(outFd, "Client: %s (cached)\n", String8(package).string());
5074 dprintf(outFd, "%s\n", kv.second.c_str());
5075 printedSomething = true;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005076 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005077
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005078 if (!printedSomething) {
5079 dprintf(outFd, "No monitoring information to print.\n");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005080 }
5081
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005082 return OK;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005083}
5084
Avichal Rakesh84147132021-11-11 17:47:11 -08005085// Print all events in vector `events' that came after lastPrintedEvent
5086void printNewWatchedEvents(int outFd,
5087 const char *cameraId,
5088 const String16 &packageName,
5089 const std::vector<std::string> &events,
5090 const std::string &lastPrintedEvent) {
5091 if (events.empty()) { return; }
5092
5093 // index of lastPrintedEvent in events.
5094 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
5095 size_t lastPrintedIdx;
5096 for (lastPrintedIdx = 0;
5097 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
5098 lastPrintedIdx++);
5099
5100 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
5101
5102 String8 packageName8(packageName);
5103 const char *printablePackageName = packageName8.lockBuffer(packageName8.size());
5104
5105 // print events in chronological order (latest event last)
5106 size_t idxToPrint = lastPrintedIdx;
5107 do {
5108 idxToPrint--;
5109 dprintf(outFd, "%s:%s %s", cameraId, printablePackageName, events[idxToPrint].c_str());
5110 } while (idxToPrint != 0);
5111
5112 packageName8.unlockBuffer();
5113}
5114
5115// Returns true if adb shell cmd watch should be interrupted based on data in inFd. The watch
5116// command should be interrupted if the user presses the return key, or if user loses any way to
5117// signal interrupt.
5118// If timeoutMs == 0, this function will always return false
5119bool shouldInterruptWatchCommand(int inFd, int outFd, long timeoutMs) {
5120 struct timeval startTime;
5121 int startTimeError = gettimeofday(&startTime, nullptr);
5122 if (startTimeError) {
5123 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
5124 return true;
5125 }
5126
5127 const nfds_t numFds = 1;
5128 struct pollfd pollFd = { .fd = inFd, .events = POLLIN, .revents = 0 };
5129
5130 struct timeval currTime;
5131 char buffer[2];
5132 while(true) {
5133 int currTimeError = gettimeofday(&currTime, nullptr);
5134 if (currTimeError) {
5135 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
5136 return true;
5137 }
5138
5139 long elapsedTimeMs = ((currTime.tv_sec - startTime.tv_sec) * 1000L)
5140 + ((currTime.tv_usec - startTime.tv_usec) / 1000L);
5141 int remainingTimeMs = (int) (timeoutMs - elapsedTimeMs);
5142
5143 if (remainingTimeMs <= 0) {
5144 // No user interrupt within timeoutMs, don't interrupt watch command
5145 return false;
5146 }
5147
5148 int numFdsUpdated = poll(&pollFd, numFds, remainingTimeMs);
5149 if (numFdsUpdated < 0) {
5150 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
5151 return true;
5152 }
5153
5154 if (numFdsUpdated == 0) {
5155 // No user input within timeoutMs, don't interrupt watch command
5156 return false;
5157 }
5158
5159 if (!(pollFd.revents & POLLIN)) {
5160 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
5161 return true;
5162 }
5163
5164 ssize_t sizeRead = read(inFd, buffer, sizeof(buffer) - 1);
5165 if (sizeRead < 0) {
5166 dprintf(outFd, "Error reading user input. Exiting.\n");
5167 return true;
5168 }
5169
5170 if (sizeRead == 0) {
5171 // Reached end of input fd (can happen if input is piped)
5172 // User has no way to signal an interrupt, so interrupt here
5173 return true;
5174 }
5175
5176 if (buffer[0] == '\n') {
5177 // User pressed return, interrupt watch command.
5178 return true;
5179 }
5180 }
5181}
5182
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005183status_t CameraService::printWatchedTagsUntilInterrupt(const Vector<String16> &args,
5184 int inFd, int outFd) {
5185 // Figure out refresh interval, if present in args
5186 long refreshTimeoutMs = 1000L; // refresh every 1s by default
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005187 if (args.size() > 2) {
5188 size_t intervalIdx; // index of '-n'
5189 for (intervalIdx = 2; intervalIdx < args.size() && String16("-n") != args[intervalIdx];
5190 intervalIdx++);
5191
5192 size_t intervalValIdx = intervalIdx + 1;
5193 if (intervalValIdx < args.size()) {
5194 refreshTimeoutMs = strtol(String8(args[intervalValIdx].string()), nullptr, 10);
5195 if (errno) { return BAD_VALUE; }
5196 }
5197 }
5198
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005199 // Set min timeout of 10ms. This prevents edge cases in polling when timeout of 0 is passed.
5200 refreshTimeoutMs = refreshTimeoutMs < 10 ? 10 : refreshTimeoutMs;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005201
Avichal Rakesh84147132021-11-11 17:47:11 -08005202 dprintf(outFd, "Press return to exit...\n\n");
Avichal Rakesha14d9832021-11-11 01:41:55 -08005203 std::map<String16, std::string> packageNameToLastEvent;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005204
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005205 while (true) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08005206 bool serviceLock = tryLock(mServiceLock);
5207 auto cameraClients = mActiveClientManager.getAll();
5208 if (serviceLock) { mServiceLock.unlock(); }
5209
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005210 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005211 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005212 if (clientDescriptor == nullptr) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005213
5214 sp<BasicClient> client = clientDescriptor->getValue();
5215 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005216 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005217
Avichal Rakesha14d9832021-11-11 01:41:55 -08005218 const String16 &packageName = client->getPackageName();
5219 // This also initializes the map entries with an empty string
5220 const std::string& lastPrintedEvent = packageNameToLastEvent[packageName];
5221
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005222 std::vector<std::string> latestEvents;
5223 client->dumpWatchedEventsToVector(latestEvents);
5224
5225 if (!latestEvents.empty()) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08005226 String8 cameraId = clientDescriptor->getKey();
5227 const char *printableCameraId = cameraId.lockBuffer(cameraId.size());
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005228 printNewWatchedEvents(outFd,
Avichal Rakesha14d9832021-11-11 01:41:55 -08005229 printableCameraId,
5230 packageName,
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005231 latestEvents,
5232 lastPrintedEvent);
Avichal Rakesha14d9832021-11-11 01:41:55 -08005233 packageNameToLastEvent[packageName] = latestEvents[0];
5234 cameraId.unlockBuffer();
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005235 }
5236 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005237 if (shouldInterruptWatchCommand(inFd, outFd, refreshTimeoutMs)) {
Avichal Rakesh84147132021-11-11 17:47:11 -08005238 break;
5239 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005240 }
5241 return OK;
5242}
5243
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005244void CameraService::parseClientsToWatchLocked(String8 clients) {
5245 mWatchedClientPackages.clear();
5246
5247 const char *allSentinel = String8(kWatchAllClientsFlag).string();
5248
5249 char *tokenized = clients.lockBuffer(clients.size());
5250 char *savePtr;
5251 char *nextClient = strtok_r(tokenized, ",", &savePtr);
5252
5253 while (nextClient != nullptr) {
5254 if (strcmp(nextClient, allSentinel) == 0) {
5255 // Don't need to track any other package if 'all' is present
5256 mWatchedClientPackages.clear();
5257 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
5258 break;
5259 }
5260
5261 // track package names
5262 mWatchedClientPackages.emplace(nextClient);
5263 nextClient = strtok_r(nullptr, ",", &savePtr);
5264 }
5265 clients.unlockBuffer();
5266}
5267
Svet Ganova453d0d2018-01-11 15:37:58 -08005268status_t CameraService::printHelp(int out) {
5269 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07005270 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
5271 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
5272 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005273 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
5274 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
5275 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005276 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
5277 " Valid values 0=OFF, 1=ON for JPEG\n"
5278 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005279 " set-camera-mute <0/1> enable or disable camera muting\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005280 " watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08005281 " help print this message\n");
5282}
5283
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005284bool CameraService::isClientWatched(const BasicClient *client) {
5285 Mutex::Autolock lock(mLogLock);
5286 return isClientWatchedLocked(client);
5287}
5288
5289bool CameraService::isClientWatchedLocked(const BasicClient *client) {
5290 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
5291 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
5292}
5293
Yin-Chia Yehdba03232019-08-19 15:54:28 -07005294int32_t CameraService::updateAudioRestriction() {
5295 Mutex::Autolock lock(mServiceLock);
5296 return updateAudioRestrictionLocked();
5297}
5298
5299int32_t CameraService::updateAudioRestrictionLocked() {
5300 int32_t mode = 0;
5301 // iterate through all active client
5302 for (const auto& i : mActiveClientManager.getAll()) {
5303 const auto clientSp = i->getValue();
5304 mode |= clientSp->getAudioRestriction();
5305 }
5306
5307 bool modeChanged = (mAudioRestriction != mode);
5308 mAudioRestriction = mode;
5309 if (modeChanged) {
5310 mAppOps.setCameraAudioRestriction(mode);
5311 }
5312 return mode;
5313}
5314
Cliff Wu646bd612021-11-23 23:21:29 +08005315status_t CameraService::checkIfInjectionCameraIsPresent(const String8& externalCamId,
5316 sp<BasicClient> clientSp) {
5317 std::unique_ptr<AutoConditionLock> lock =
5318 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
5319 status_t res = NO_ERROR;
5320 if ((res = checkIfDeviceIsUsable(externalCamId)) != NO_ERROR) {
5321 ALOGW("Device %s is not usable!", externalCamId.string());
5322 mInjectionStatusListener->notifyInjectionError(
5323 externalCamId, UNKNOWN_TRANSACTION);
5324 clientSp->notifyError(
5325 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
5326 CaptureResultExtras());
5327
5328 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
5329 // other clients from connecting in mServiceLockWrapper if held
5330 mServiceLock.unlock();
5331
5332 // Clear caller identity temporarily so client disconnect PID checks work correctly
5333 int64_t token = CameraThreadState::clearCallingIdentity();
5334 clientSp->disconnect();
5335 CameraThreadState::restoreCallingIdentity(token);
5336
5337 // Reacquire mServiceLock
5338 mServiceLock.lock();
5339 }
5340
5341 return res;
5342}
5343
Cliff Wud3a05312021-04-26 23:07:31 +08005344void CameraService::clearInjectionParameters() {
5345 {
5346 Mutex::Autolock lock(mInjectionParametersLock);
Cliff Wu646bd612021-11-23 23:21:29 +08005347 mInjectionInitPending = false;
Cliff Wud3a05312021-04-26 23:07:31 +08005348 mInjectionInternalCamId = "";
5349 }
5350 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08005351 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08005352}
5353
Mathias Agopian65ab4712010-07-14 17:59:35 -07005354}; // namespace android