blob: e65a27a46635f70fcc726cee06a17a8a1a998541 [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;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -070089using camera3::SessionConfigurationUtils;
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;
94using hardware::camera::common::V1_0::CameraDeviceStatus;
95using hardware::camera::common::V1_0::TorchModeStatus;
Cliff Wud8cae102021-03-11 01:37:42 +080096using hardware::camera2::ICameraInjectionCallback;
97using hardware::camera2::ICameraInjectionSession;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080098using hardware::camera2::utils::CameraIdAndSessionConfiguration;
99using hardware::camera2::utils::ConcurrentCameraIdCombination;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800100
Mathias Agopian65ab4712010-07-14 17:59:35 -0700101// ----------------------------------------------------------------------------
102// Logging support -- this is for debugging only
103// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700104volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700105
Steve Blockb8a80522011-12-20 16:23:08 +0000106#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
107#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700108
109static void setLogLevel(int level) {
110 android_atomic_write(level, &gLogLevel);
111}
112
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800113// Convenience methods for constructing binder::Status objects for error returns
114
115#define STATUS_ERROR(errorCode, errorString) \
116 binder::Status::fromServiceSpecificError(errorCode, \
117 String8::format("%s:%d: %s", __FUNCTION__, __LINE__, errorString))
118
119#define STATUS_ERROR_FMT(errorCode, errorString, ...) \
120 binder::Status::fromServiceSpecificError(errorCode, \
121 String8::format("%s:%d: " errorString, __FUNCTION__, __LINE__, \
122 __VA_ARGS__))
123
Mathias Agopian65ab4712010-07-14 17:59:35 -0700124// ----------------------------------------------------------------------------
125
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700126static const String16 sDumpPermission("android.permission.DUMP");
Svet Ganova453d0d2018-01-11 15:37:58 -0800127static const String16 sManageCameraPermission("android.permission.MANAGE_CAMERA");
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700128static const String16 sCameraPermission("android.permission.CAMERA");
129static const String16 sSystemCameraPermission("android.permission.SYSTEM_CAMERA");
130static const String16
131 sCameraSendSystemEventsPermission("android.permission.CAMERA_SEND_SYSTEM_EVENTS");
Shuzhen Wang695044d2020-03-06 09:02:23 -0800132static const String16 sCameraOpenCloseListenerPermission(
133 "android.permission.CAMERA_OPEN_CLOSE_LISTENER");
Cliff Wud8cae102021-03-11 01:37:42 +0800134static const String16
135 sCameraInjectExternalCameraPermission("android.permission.CAMERA_INJECT_EXTERNAL_CAMERA");
Rucha Katakwardf223072021-06-15 10:21:00 -0700136const char *sFileName = "lastOpenSessionDumpFile";
Eino-Ville Talvala7c602c32021-03-20 17:00:18 -0700137static constexpr int32_t kVendorClientScore = resource_policy::PERCEPTIBLE_APP_ADJ;
138static constexpr int32_t kVendorClientState = ActivityManager::PROCESS_STATE_PERSISTENT_UI;
139
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800140const String8 CameraService::kOfflineDevice("offline-");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -0700141const String16 CameraService::kWatchAllClientsFlag("all");
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700142
Rucha Katakward9ea6452021-05-06 11:57:16 -0700143// Set to keep track of logged service error events.
144static std::set<String8> sServiceErrorEventSet;
145
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800146CameraService::CameraService() :
147 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800148 mNumberOfCameras(0),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700149 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700150 mSoundRef(0), mInitialized(false),
151 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000152 ALOGI("CameraService started (pid=%d)", getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800153 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Rucha Katakwardf223072021-06-15 10:21:00 -0700154 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
155 if (mMemFd == -1) {
156 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
157 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700158}
159
Iliyan Malchev8951a972011-04-14 16:55:59 -0700160void CameraService::onFirstRef()
161{
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -0700162
Ruben Brunkcc776712015-02-17 20:18:47 -0800163 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800164
Iliyan Malchev8951a972011-04-14 16:55:59 -0700165 BnCameraService::onFirstRef();
166
Ruben Brunk99e69712015-05-26 17:25:07 -0700167 // Update battery life tracking if service is restarting
168 BatteryNotifier& notifier(BatteryNotifier::getInstance());
169 notifier.noteResetCamera();
170 notifier.noteResetFlashlight();
171
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800172 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800173
Emilian Peevf53f66e2017-04-11 14:29:43 +0100174 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800175 if (res == OK) {
176 mInitialized = true;
177 }
178
Svet Ganova453d0d2018-01-11 15:37:58 -0800179 mUidPolicy = new UidPolicy(this);
180 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800181 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
182 mSensorPrivacyPolicy->registerSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800183 mInjectionStatusListener = new InjectionStatusListener(this);
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700184 mAppOps.setCameraAudioRestriction(mAudioRestriction);
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700185 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
186 if (hcs->registerAsService() != android::OK) {
187 ALOGE("%s: Failed to register default android.frameworks.cameraservice.service@1.0",
188 __FUNCTION__);
189 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700190
191 // This needs to be last call in this function, so that it's as close to
192 // ServiceManager::addService() as possible.
Shuzhen Wang316781a2020-08-18 18:11:01 -0700193 CameraServiceProxyWrapper::pingCameraServiceProxy();
Shuzhen Wang24b44152019-09-20 10:38:11 -0700194 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800195}
196
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800197status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800198 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100199
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800200 std::vector<std::string> deviceIds;
201 {
202 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800203
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800204 if (nullptr == mCameraProviderManager.get()) {
205 mCameraProviderManager = new CameraProviderManager();
206 res = mCameraProviderManager->initialize(this);
207 if (res != OK) {
208 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
209 __FUNCTION__, strerror(-res), res);
Rucha Katakward9ea6452021-05-06 11:57:16 -0700210 logServiceError(String8::format("Unable to initialize camera provider manager"),
211 ERROR_DISCONNECTED);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800212 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100213 }
214 }
215
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800216
217 // Setup vendor tags before we call get_camera_info the first time
218 // because HAL might need to setup static vendor keys in get_camera_info
219 // TODO: maybe put this into CameraProviderManager::initialize()?
220 mCameraProviderManager->setUpVendorTags();
221
222 if (nullptr == mFlashlight.get()) {
223 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700224 }
225
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800226 res = mFlashlight->findFlashUnits();
227 if (res != OK) {
228 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
229 }
230
231 deviceIds = mCameraProviderManager->getCameraDeviceIds();
232 }
233
234
235 for (auto& cameraId : deviceIds) {
236 String8 id8 = String8(cameraId.c_str());
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800237 if (getCameraState(id8) == nullptr) {
238 onDeviceStatusChanged(id8, CameraDeviceStatus::PRESENT);
239 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800240 }
241
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700242 // Derive primary rear/front cameras, and filter their charactierstics.
243 // This needs to be done after all cameras are enumerated and camera ids are sorted.
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700244 if (SessionConfigurationUtils::IS_PERF_CLASS) {
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700245 // Assume internal cameras are advertised from the same
246 // provider. If multiple providers are registered at different time,
247 // and each provider contains multiple internal color cameras, the current
248 // logic may filter the characteristics of more than one front/rear color
249 // cameras.
250 Mutex::Autolock l(mServiceLock);
251 filterSPerfClassCharacteristicsLocked();
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700252 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700253
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800254 return OK;
255}
256
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700257void CameraService::broadcastTorchModeStatus(const String8& cameraId, TorchModeStatus status,
258 SystemCameraKind systemCameraKind) {
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800259 Mutex::Autolock lock(mStatusListenerLock);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800260 for (auto& i : mListenerList) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700261 if (shouldSkipStatusUpdates(systemCameraKind, i->isVendorListener(), i->getListenerPid(),
262 i->getListenerUid())) {
263 ALOGV("Skipping torch callback for system-only camera device %s",
264 cameraId.c_str());
265 continue;
266 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700267 i->getListener()->onTorchStatusChanged(mapToInterface(status), String16{cameraId});
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800268 }
269}
270
Mathias Agopian65ab4712010-07-14 17:59:35 -0700271CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800272 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800273 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800274 mSensorPrivacyPolicy->unregisterSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800275 mInjectionStatusListener->removeListener();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700276}
277
Emilian Peevaee727d2017-05-04 16:35:48 +0100278void CameraService::onNewProviderRegistered() {
279 enumerateProviders();
280}
281
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700282void CameraService::filterAPI1SystemCameraLocked(
283 const std::vector<std::string> &normalDeviceIds) {
284 mNormalDeviceIdsWithoutSystemCamera.clear();
285 for (auto &deviceId : normalDeviceIds) {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700286 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
287 if (getSystemCameraKind(String8(deviceId.c_str()), &deviceKind) != OK) {
288 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, deviceId.c_str());
289 continue;
290 }
291 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700292 // All system camera ids will necessarily come after public camera
293 // device ids as per the HAL interface contract.
294 break;
295 }
296 mNormalDeviceIdsWithoutSystemCamera.push_back(deviceId);
297 }
298 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
299 mNormalDeviceIdsWithoutSystemCamera.size());
300}
301
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700302status_t CameraService::getSystemCameraKind(const String8& cameraId, SystemCameraKind *kind) const {
303 auto state = getCameraState(cameraId);
304 if (state != nullptr) {
305 *kind = state->getSystemCameraKind();
306 return OK;
307 }
308 // Hidden physical camera ids won't have CameraState
309 return mCameraProviderManager->getSystemCameraKind(cameraId.c_str(), kind);
310}
311
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800312void CameraService::updateCameraNumAndIds() {
313 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700314 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
315 // Excludes hidden secure cameras
316 mNumberOfCameras =
317 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
318 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800319 mNormalDeviceIds =
320 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700321 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800322}
323
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700324void CameraService::filterSPerfClassCharacteristicsLocked() {
Shuzhen Wang89db2992021-05-20 13:09:48 -0700325 // To claim to be S Performance primary cameras, the cameras must be
326 // backward compatible. So performance class primary camera Ids must be API1
327 // compatible.
328 bool firstRearCameraSeen = false, firstFrontCameraSeen = false;
329 for (const auto& cameraId : mNormalDeviceIdsWithoutSystemCamera) {
330 int facing = -1;
331 int orientation = 0;
332 String8 cameraId8(cameraId.c_str());
333 getDeviceVersion(cameraId8, /*out*/&facing, /*out*/&orientation);
334 if (facing == -1) {
335 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
336 return;
337 }
338
339 if ((facing == hardware::CAMERA_FACING_BACK && !firstRearCameraSeen) ||
340 (facing == hardware::CAMERA_FACING_FRONT && !firstFrontCameraSeen)) {
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700341 status_t res = mCameraProviderManager->filterSmallJpegSizes(cameraId);
342 if (res == OK) {
343 mPerfClassPrimaryCameraIds.insert(cameraId);
344 } else {
345 ALOGE("%s: Failed to filter small JPEG sizes for performance class primary "
346 "camera %s: %s(%d)", __FUNCTION__, cameraId.c_str(), strerror(-res), res);
347 break;
348 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700349
350 if (facing == hardware::CAMERA_FACING_BACK) {
351 firstRearCameraSeen = true;
352 }
353 if (facing == hardware::CAMERA_FACING_FRONT) {
354 firstFrontCameraSeen = true;
355 }
356 }
357
358 if (firstRearCameraSeen && firstFrontCameraSeen) {
359 break;
360 }
361 }
362}
363
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100364void CameraService::addStates(const String8 id) {
365 std::string cameraId(id.c_str());
366 hardware::camera::common::V1_0::CameraResourceCost cost;
367 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700368 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100369 if (res != OK) {
370 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
371 return;
372 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700373 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
374 if (res != OK) {
375 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
376 return;
377 }
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,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700386 conflicting, deviceKind));
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) {
1885 client->setRotateAndCropOverride(CameraServiceProxyWrapper::getRotateAndCropOverride(
1886 clientPackageName, facing));
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001887 }
1888
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08001889 // Set camera muting behavior
Valentin Iftimec0b8d472021-07-23 20:21:06 +02001890 bool isCameraPrivacyEnabled =
1891 mSensorPrivacyPolicy->isCameraPrivacyEnabled(multiuser_get_user_id(clientUid));
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08001892 if (client->supportsCameraMute()) {
Valentin Iftimec0b8d472021-07-23 20:21:06 +02001893 client->setCameraMute(
1894 mOverrideCameraMuteMode || isCameraPrivacyEnabled);
1895 } else if (isCameraPrivacyEnabled) {
1896 // no camera mute supported, but privacy is on! => disconnect
1897 ALOGI("Camera mute not supported for package: %s, camera id: %s",
1898 String8(client->getPackageName()).string(), cameraId.string());
1899 // Do not hold mServiceLock while disconnecting clients, but
1900 // retain the condition blocking other clients from connecting
1901 // in mServiceLockWrapper if held.
1902 mServiceLock.unlock();
1903 // Clear caller identity temporarily so client disconnect PID
1904 // checks work correctly
1905 int64_t token = CameraThreadState::clearCallingIdentity();
1906 // Note AppOp to trigger the "Unblock" dialog
1907 client->noteAppOp();
1908 client->disconnect();
1909 CameraThreadState::restoreCallingIdentity(token);
1910 // Reacquire mServiceLock
1911 mServiceLock.lock();
1912
1913 return STATUS_ERROR_FMT(ERROR_DISABLED,
1914 "Camera \"%s\" disabled due to camera mute", cameraId.string());
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08001915 }
1916
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001917 if (shimUpdateOnly) {
1918 // If only updating legacy shim parameters, immediately disconnect client
1919 mServiceLock.unlock();
1920 client->disconnect();
1921 mServiceLock.lock();
1922 } else {
1923 // Otherwise, add client to active clients list
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001924 finishConnectLocked(client, partial, oomScoreOffset);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001925 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001926
1927 client->setImageDumpMask(mImageDumpMask);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001928 } // lock is destroyed, allow further connect calls
1929
1930 // Important: release the mutex here so the client can call back into the service from its
1931 // destructor (can be at the end of the call)
1932 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001933
1934 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
1935 CameraServiceProxyWrapper::logOpen(cameraId, facing, clientPackageName,
1936 effectiveApiLevel, isNdk, openLatencyMs);
1937
Cliff Wud3a05312021-04-26 23:07:31 +08001938 {
1939 Mutex::Autolock lock(mInjectionParametersLock);
1940 if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
1941 mInjectionInitPending = false;
1942 status_t res = NO_ERROR;
1943 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
1944 if (clientDescriptor != nullptr) {
Cliff Wu646bd612021-11-23 23:21:29 +08001945 sp<BasicClient> clientSp = clientDescriptor->getValue();
1946 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
1947 if(res != OK) {
1948 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1949 "No camera device with ID \"%s\" currently available",
1950 mInjectionExternalCamId.string());
1951 }
1952 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08001953 if (res != OK) {
1954 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
1955 }
1956 } else {
1957 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
1958 __FUNCTION__, mInjectionInternalCamId.string());
1959 res = NO_INIT;
1960 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
1961 }
1962 }
1963 }
1964
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001965 return ret;
1966}
1967
Emilian Peevb2bc5a42019-11-20 16:02:14 -08001968status_t CameraService::addOfflineClient(String8 cameraId, sp<BasicClient> offlineClient) {
1969 if (offlineClient.get() == nullptr) {
1970 return BAD_VALUE;
1971 }
1972
1973 {
1974 // Acquire mServiceLock and prevent other clients from connecting
1975 std::unique_ptr<AutoConditionLock> lock =
1976 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1977
1978 if (lock == nullptr) {
1979 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
1980 , __FUNCTION__, offlineClient->getClientPid());
1981 return TIMED_OUT;
1982 }
1983
1984 auto onlineClientDesc = mActiveClientManager.get(cameraId);
1985 if (onlineClientDesc.get() == nullptr) {
1986 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
1987 cameraId.c_str());
1988 return BAD_VALUE;
1989 }
1990
1991 // Offline clients do not evict or conflict with other online devices. Resource sharing
1992 // conflicts are handled by the camera provider which will either succeed or fail before
1993 // reaching this method.
1994 const auto& onlinePriority = onlineClientDesc->getPriority();
1995 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
1996 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
1997 /*conflictingKeys*/ std::set<String8>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001998 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
1999 /*ommScoreOffset*/ 0);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002000
2001 // Allow only one offline device per camera
2002 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
2003 if (!incompatibleClients.empty()) {
2004 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
2005 return BAD_VALUE;
2006 }
2007
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002008 String8 monitorTags = isClientWatched(offlineClient.get()) ? mMonitorTags : String8("");
2009 auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002010 if (err != OK) {
2011 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
2012 return err;
2013 }
2014
2015 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
2016 if (evicted.size() > 0) {
2017 for (auto& i : evicted) {
2018 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
2019 __FUNCTION__, i->getKey().string());
2020 }
2021
2022 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
2023 "properly", __FUNCTION__);
2024
2025 return BAD_VALUE;
2026 }
2027
2028 logConnectedOffline(offlineClientDesc->getKey(),
2029 static_cast<int>(offlineClientDesc->getOwnerId()),
2030 String8(offlineClient->getPackageName()));
2031
2032 sp<IBinder> remoteCallback = offlineClient->getRemote();
2033 if (remoteCallback != nullptr) {
2034 remoteCallback->linkToDeath(this);
2035 }
2036 } // lock is destroyed, allow further connect calls
2037
2038 return OK;
2039}
2040
Rucha Katakwar38284522021-11-10 11:25:21 -08002041Status CameraService::turnOnTorchWithStrengthLevel(const String16& cameraId, int32_t torchStrength,
2042 const sp<IBinder>& clientBinder) {
2043 Mutex::Autolock lock(mServiceLock);
2044
2045 ATRACE_CALL();
2046 if (clientBinder == nullptr) {
2047 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
2048 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2049 "Torch client binder in null.");
2050 }
2051
2052 String8 id = String8(cameraId.string());
2053 int uid = CameraThreadState::getCallingUid();
2054
2055 if (shouldRejectSystemCameraConnection(id)) {
2056 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to change the strength level"
2057 "for system only device %s: ", id.string());
2058 }
2059
2060 // verify id is valid
2061 auto state = getCameraState(id);
2062 if (state == nullptr) {
2063 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
2064 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2065 "Camera ID \"%s\" is a not valid camera ID", id.string());
2066 }
2067
2068 StatusInternal cameraStatus = state->getStatus();
2069 if (cameraStatus != StatusInternal::NOT_AVAILABLE &&
2070 cameraStatus != StatusInternal::PRESENT) {
2071 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(),
2072 (int)cameraStatus);
2073 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2074 "Camera ID \"%s\" is a not valid camera ID", id.string());
2075 }
2076
2077 {
2078 Mutex::Autolock al(mTorchStatusMutex);
2079 TorchModeStatus status;
2080 status_t err = getTorchStatusLocked(id, &status);
2081 if (err != OK) {
2082 if (err == NAME_NOT_FOUND) {
2083 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2084 "Camera \"%s\" does not have a flash unit", id.string());
2085 }
2086 ALOGE("%s: getting current torch status failed for camera %s",
2087 __FUNCTION__, id.string());
2088 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2089 "Error changing torch strength level for camera \"%s\": %s (%d)",
2090 id.string(), strerror(-err), err);
2091 }
2092
2093 if (status == TorchModeStatus::NOT_AVAILABLE) {
2094 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
2095 ALOGE("%s: torch mode of camera %s is not available because "
2096 "camera is in use.", __FUNCTION__, id.string());
2097 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2098 "Torch for camera \"%s\" is not available due to an existing camera user",
2099 id.string());
2100 } else {
2101 ALOGE("%s: torch mode of camera %s is not available due to "
2102 "insufficient resources", __FUNCTION__, id.string());
2103 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2104 "Torch for camera \"%s\" is not available due to insufficient resources",
2105 id.string());
2106 }
2107 }
2108 }
2109
2110 {
2111 Mutex::Autolock al(mTorchUidMapMutex);
2112 updateTorchUidMapLocked(cameraId, uid);
2113 }
2114 // Check if the current torch strength level is same as the new one.
2115 bool shouldSkipTorchStrengthUpdates = mCameraProviderManager->shouldSkipTorchStrengthUpdate(
2116 id.string(), torchStrength);
2117
2118 status_t err = mFlashlight->turnOnTorchWithStrengthLevel(id, torchStrength);
2119
2120 if (err != OK) {
2121 int32_t errorCode;
2122 String8 msg;
2123 switch (err) {
2124 case -ENOSYS:
2125 msg = String8::format("Camera \"%s\" has no flashlight.",
2126 id.string());
2127 errorCode = ERROR_ILLEGAL_ARGUMENT;
2128 break;
2129 case -EBUSY:
2130 msg = String8::format("Camera \"%s\" is in use",
2131 id.string());
2132 errorCode = ERROR_CAMERA_IN_USE;
2133 break;
2134 default:
2135 msg = String8::format("Changing torch strength level failed.");
2136 errorCode = ERROR_INVALID_OPERATION;
2137
2138 }
2139 ALOGE("%s: %s", __FUNCTION__, msg.string());
2140 return STATUS_ERROR(errorCode, msg.string());
2141 }
2142
2143 {
2144 // update the link to client's death
2145 // Store the last client that turns on each camera's torch mode.
2146 Mutex::Autolock al(mTorchClientMapMutex);
2147 ssize_t index = mTorchClientMap.indexOfKey(id);
2148 if (index == NAME_NOT_FOUND) {
2149 mTorchClientMap.add(id, clientBinder);
2150 } else {
2151 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
2152 mTorchClientMap.replaceValueAt(index, clientBinder);
2153 }
2154 clientBinder->linkToDeath(this);
2155 }
2156
2157 int clientPid = CameraThreadState::getCallingPid();
2158 const char *id_cstr = id.c_str();
2159 ALOGI("%s: Torch strength for camera id %s changed to %d for client PID %d",
2160 __FUNCTION__, id_cstr, torchStrength, clientPid);
2161 if (!shouldSkipTorchStrengthUpdates) {
2162 broadcastTorchStrengthLevel(id, torchStrength);
2163 }
2164 return Status::ok();
2165}
2166
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002167Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002168 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002169 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002170
2171 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07002172 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002173 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002174 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2175 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002176 }
2177
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002178 String8 id = String8(cameraId.string());
Jayant Chowdhary12361932018-08-27 14:46:13 -07002179 int uid = CameraThreadState::getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002180
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002181 if (shouldRejectSystemCameraConnection(id)) {
2182 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
2183 " for system only device %s: ", id.string());
2184 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002185 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08002186 auto state = getCameraState(id);
2187 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07002188 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002189 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2190 "Camera ID \"%s\" is a not valid camera ID", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08002191 }
2192
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002193 StatusInternal cameraStatus = state->getStatus();
2194 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002195 cameraStatus != StatusInternal::NOT_AVAILABLE) {
2196 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002197 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2198 "Camera ID \"%s\" is a not valid camera ID", id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002199 }
2200
2201 {
2202 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002203 TorchModeStatus status;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002204 status_t err = getTorchStatusLocked(id, &status);
2205 if (err != OK) {
2206 if (err == NAME_NOT_FOUND) {
2207 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2208 "Camera \"%s\" does not have a flash unit", id.string());
2209 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002210 ALOGE("%s: getting current torch status failed for camera %s",
2211 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002212 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2213 "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
2214 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002215 }
2216
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002217 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002218 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002219 ALOGE("%s: torch mode of camera %s is not available because "
2220 "camera is in use", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002221 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2222 "Torch for camera \"%s\" is not available due to an existing camera user",
2223 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002224 } else {
2225 ALOGE("%s: torch mode of camera %s is not available due to "
2226 "insufficient resources", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002227 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2228 "Torch for camera \"%s\" is not available due to insufficient resources",
2229 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002230 }
2231 }
2232 }
2233
Ruben Brunk99e69712015-05-26 17:25:07 -07002234 {
2235 // Update UID map - this is used in the torch status changed callbacks, so must be done
2236 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07002237 Mutex::Autolock al(mTorchUidMapMutex);
Rucha Katakwar38284522021-11-10 11:25:21 -08002238 updateTorchUidMapLocked(cameraId, uid);
Ruben Brunk99e69712015-05-26 17:25:07 -07002239 }
2240
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002241 status_t err = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07002242
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002243 if (err != OK) {
2244 int32_t errorCode;
2245 String8 msg;
2246 switch (err) {
2247 case -ENOSYS:
2248 msg = String8::format("Camera \"%s\" has no flashlight",
2249 id.string());
2250 errorCode = ERROR_ILLEGAL_ARGUMENT;
2251 break;
Dijack Dongc8a6f252021-09-17 16:21:16 +08002252 case -EBUSY:
2253 msg = String8::format("Camera \"%s\" is in use",
2254 id.string());
2255 errorCode = ERROR_CAMERA_IN_USE;
2256 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002257 default:
2258 msg = String8::format(
2259 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
2260 id.string(), enabled, strerror(-err), err);
2261 errorCode = ERROR_INVALID_OPERATION;
2262 }
2263 ALOGE("%s: %s", __FUNCTION__, msg.string());
Rucha Katakward9ea6452021-05-06 11:57:16 -07002264 logServiceError(msg,errorCode);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002265 return STATUS_ERROR(errorCode, msg.string());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002266 }
2267
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002268 {
2269 // update the link to client's death
2270 Mutex::Autolock al(mTorchClientMapMutex);
2271 ssize_t index = mTorchClientMap.indexOfKey(id);
2272 if (enabled) {
2273 if (index == NAME_NOT_FOUND) {
2274 mTorchClientMap.add(id, clientBinder);
2275 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07002276 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002277 mTorchClientMap.replaceValueAt(index, clientBinder);
2278 }
2279 clientBinder->linkToDeath(this);
2280 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07002281 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002282 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002283 }
2284
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002285 int clientPid = CameraThreadState::getCallingPid();
2286 const char *id_cstr = id.c_str();
2287 const char *torchState = enabled ? "on" : "off";
2288 ALOGI("Torch for camera id %s turned %s for client PID %d", id_cstr, torchState, clientPid);
2289 logTorchEvent(id_cstr, torchState , clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002290 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002291}
2292
Rucha Katakwar38284522021-11-10 11:25:21 -08002293void CameraService::updateTorchUidMapLocked(const String16& cameraId, int uid) {
2294 String8 id = String8(cameraId.string());
2295 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
2296 mTorchUidMap[id].first = uid;
2297 mTorchUidMap[id].second = uid;
2298 } else {
2299 // Set the pending UID
2300 mTorchUidMap[id].first = uid;
2301 }
2302}
2303
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002304Status CameraService::notifySystemEvent(int32_t eventId,
2305 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002306 const int pid = CameraThreadState::getCallingPid();
2307 const int selfPid = getpid();
2308
2309 // Permission checks
2310 if (pid != selfPid) {
2311 // Ensure we're being called by system_server, or similar process with
2312 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002313 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002314 const int uid = CameraThreadState::getCallingUid();
2315 ALOGE("Permission Denial: cannot send updates to camera service about system"
2316 " events from pid=%d, uid=%d", pid, uid);
2317 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09002318 "No permission to send updates to camera service about system events"
2319 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002320 }
2321 }
2322
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002323 ATRACE_CALL();
2324
Ruben Brunk36597b22015-03-20 22:15:57 -07002325 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002326 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08002327 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002328 // from a system server crash
2329 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08002330 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002331 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07002332 break;
2333 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002334 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07002335 default: {
2336 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
2337 eventId);
2338 break;
2339 }
2340 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002341 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002342}
2343
Emilian Peev53722fa2019-02-22 17:47:20 -08002344void CameraService::notifyMonitoredUids() {
2345 Mutex::Autolock lock(mStatusListenerLock);
2346
2347 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002348 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Emilian Peev53722fa2019-02-22 17:47:20 -08002349 if (!ret.isOk()) {
2350 ALOGE("%s: Failed to trigger permission callback: %d", __FUNCTION__,
2351 ret.exceptionCode());
2352 }
2353 }
2354}
2355
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002356Status CameraService::notifyDeviceStateChange(int64_t newState) {
2357 const int pid = CameraThreadState::getCallingPid();
2358 const int selfPid = getpid();
2359
2360 // Permission checks
2361 if (pid != selfPid) {
2362 // Ensure we're being called by system_server, or similar process with
2363 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002364 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002365 const int uid = CameraThreadState::getCallingUid();
2366 ALOGE("Permission Denial: cannot send updates to camera service about device"
2367 " state changes from pid=%d, uid=%d", pid, uid);
2368 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2369 "No permission to send updates to camera service about device state"
2370 " changes from pid=%d, uid=%d", pid, uid);
2371 }
2372 }
2373
2374 ATRACE_CALL();
2375
2376 using hardware::camera::provider::V2_5::DeviceState;
2377 hardware::hidl_bitfield<DeviceState> newDeviceState{};
2378 if (newState & ICameraService::DEVICE_STATE_BACK_COVERED) {
2379 newDeviceState |= DeviceState::BACK_COVERED;
2380 }
2381 if (newState & ICameraService::DEVICE_STATE_FRONT_COVERED) {
2382 newDeviceState |= DeviceState::FRONT_COVERED;
2383 }
2384 if (newState & ICameraService::DEVICE_STATE_FOLDED) {
2385 newDeviceState |= DeviceState::FOLDED;
2386 }
2387 // Only map vendor bits directly
2388 uint64_t vendorBits = static_cast<uint64_t>(newState) & 0xFFFFFFFF00000000l;
2389 newDeviceState |= vendorBits;
2390
2391 ALOGV("%s: New device state 0x%" PRIx64, __FUNCTION__, newDeviceState);
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002392 mCameraProviderManager->notifyDeviceStateChange(newDeviceState);
2393
2394 return Status::ok();
2395}
2396
Emilian Peev8b64f282021-03-25 16:49:57 -07002397Status CameraService::notifyDisplayConfigurationChange() {
2398 ATRACE_CALL();
2399 const int callingPid = CameraThreadState::getCallingPid();
2400 const int selfPid = getpid();
2401
2402 // Permission checks
2403 if (callingPid != selfPid) {
2404 // Ensure we're being called by system_server, or similar process with
2405 // permissions to notify the camera service about system events
2406 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
2407 const int uid = CameraThreadState::getCallingUid();
2408 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
2409 " changes from pid=%d, uid=%d", callingPid, uid);
2410 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2411 "No permission to send updates to camera service about orientation"
2412 " changes from pid=%d, uid=%d", callingPid, uid);
2413 }
2414 }
2415
2416 Mutex::Autolock lock(mServiceLock);
2417
2418 // Don't do anything if rotate-and-crop override via cmd is active
2419 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
2420
2421 const auto clients = mActiveClientManager.getAll();
2422 for (auto& current : clients) {
2423 if (current != nullptr) {
2424 const auto basicClient = current->getValue();
Emilian Peeve23f1d92021-09-20 14:56:01 -07002425 if (basicClient.get() != nullptr && basicClient->canCastToApiClient(API_2)) {
Emilian Peev5368ebf2021-10-08 17:52:18 -07002426 basicClient->setRotateAndCropOverride(
2427 CameraServiceProxyWrapper::getRotateAndCropOverride(
2428 basicClient->getPackageName(), basicClient->getCameraFacing()));
Emilian Peev8b64f282021-03-25 16:49:57 -07002429 }
2430 }
2431 }
2432
2433 return Status::ok();
2434}
2435
2436Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002437 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
2438 ATRACE_CALL();
2439 if (!concurrentCameraIds) {
2440 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
2441 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
2442 }
2443
2444 if (!mInitialized) {
2445 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Rucha Katakward9ea6452021-05-06 11:57:16 -07002446 logServiceError(String8::format("Camera subsystem is not available"),ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002447 return STATUS_ERROR(ERROR_DISCONNECTED,
2448 "Camera subsystem is not available");
2449 }
2450 // First call into the provider and get the set of concurrent camera
2451 // combinations
2452 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07002453 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002454 for (auto &combination : concurrentCameraCombinations) {
2455 std::vector<std::string> validCombination;
2456 for (auto &cameraId : combination) {
2457 // if the camera state is not present, skip
2458 String8 cameraIdStr(cameraId.c_str());
2459 auto state = getCameraState(cameraIdStr);
2460 if (state == nullptr) {
2461 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
2462 continue;
2463 }
2464 StatusInternal status = state->getStatus();
2465 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
2466 continue;
2467 }
2468 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
2469 continue;
2470 }
2471 validCombination.push_back(cameraId);
2472 }
2473 if (validCombination.size() != 0) {
2474 concurrentCameraIds->push_back(std::move(validCombination));
2475 }
2476 }
2477 return Status::ok();
2478}
2479
2480Status CameraService::isConcurrentSessionConfigurationSupported(
2481 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002482 int targetSdkVersion, /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002483 if (!isSupported) {
2484 ALOGE("%s: isSupported is NULL", __FUNCTION__);
2485 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
2486 }
2487
2488 if (!mInitialized) {
2489 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2490 return STATUS_ERROR(ERROR_DISCONNECTED,
2491 "Camera subsystem is not available");
2492 }
2493
2494 // Check for camera permissions
2495 int callingPid = CameraThreadState::getCallingPid();
2496 int callingUid = CameraThreadState::getCallingUid();
2497 if ((callingPid != getpid()) && !checkPermission(sCameraPermission, callingPid, callingUid)) {
2498 ALOGE("%s: pid %d doesn't have camera permissions", __FUNCTION__, callingPid);
2499 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2500 "android.permission.CAMERA needed to call"
2501 "isConcurrentSessionConfigurationSupported");
2502 }
2503
2504 status_t res =
2505 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002506 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
2507 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002508 if (res != OK) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07002509 logServiceError(String8::format("Unable to query session configuration support"),
2510 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002511 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
2512 "support %s (%d)", strerror(-res), res);
2513 }
2514 return Status::ok();
2515}
2516
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002517Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
2518 /*out*/
2519 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002520 return addListenerHelper(listener, cameraStatuses);
2521}
2522
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002523binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
2524 std::vector<hardware::CameraStatus>* cameraStatuses) {
2525 return addListenerHelper(listener, cameraStatuses, false, true);
2526}
2527
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002528Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
2529 /*out*/
2530 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002531 bool isVendorListener, bool isProcessLocalTest) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002532
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002533 ATRACE_CALL();
2534
Igor Murashkinbfc99152013-02-27 12:55:20 -08002535 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08002536
Ruben Brunk3450ba72015-06-16 11:00:37 -07002537 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002538 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002539 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002540 }
2541
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002542 auto clientUid = CameraThreadState::getCallingUid();
2543 auto clientPid = CameraThreadState::getCallingPid();
Shuzhen Wang695044d2020-03-06 09:02:23 -08002544 bool openCloseCallbackAllowed = checkPermission(sCameraOpenCloseListenerPermission,
Jayant Chowdharyc3198c32021-07-28 20:59:14 +00002545 clientPid, clientUid, /*logPermissionFailure*/false);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002546
Igor Murashkinbfc99152013-02-27 12:55:20 -08002547 Mutex::Autolock lock(mServiceLock);
2548
Ruben Brunkcc776712015-02-17 20:18:47 -08002549 {
2550 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08002551 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002552 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002553 ALOGW("%s: Tried to add listener %p which was already subscribed",
2554 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002555 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08002556 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002557 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002558
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002559 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08002560 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
2561 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002562 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08002563 if (ret != NO_ERROR) {
2564 String8 msg = String8::format("Failed to initialize service listener: %s (%d)",
2565 strerror(-ret), ret);
Rucha Katakward9ea6452021-05-06 11:57:16 -07002566 logServiceError(msg,ERROR_ILLEGAL_ARGUMENT);
Emilian Peev53722fa2019-02-22 17:47:20 -08002567 ALOGE("%s: %s", __FUNCTION__, msg.string());
2568 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
2569 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002570 // The listener still needs to be added to the list of listeners, regardless of what
2571 // permissions the listener process has / whether it is a vendor listener. Since it might be
2572 // eligible to listen to other camera ids.
2573 mListenerList.emplace_back(serviceListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08002574 mUidPolicy->registerMonitorUid(clientUid);
Igor Murashkinbfc99152013-02-27 12:55:20 -08002575 }
2576
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002577 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07002578 {
Ruben Brunkcc776712015-02-17 20:18:47 -08002579 Mutex::Autolock lock(mCameraStatesLock);
2580 for (auto& i : mCameraStates) {
Shuzhen Wang43858162020-01-10 13:42:15 -08002581 cameraStatuses->emplace_back(i.first,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07002582 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
2583 openCloseCallbackAllowed ? i.second->getClientPackage() : String8::empty());
Igor Murashkincba2c162013-03-20 15:56:31 -07002584 }
2585 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002586 // Remove the camera statuses that should be hidden from the client, we do
2587 // this after collecting the states in order to avoid holding
2588 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
2589 // the same time.
2590 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
2591 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
2592 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
2593 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
2594 ALOGE("%s: Invalid camera id %s, skipping status update",
2595 __FUNCTION__, s.cameraId.c_str());
2596 return true;
2597 }
2598 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
2599 clientUid);}), cameraStatuses->end());
2600
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002601 //cameraStatuses will have non-eligible camera ids removed.
2602 std::set<String16> idsChosenForCallback;
2603 for (const auto &s : *cameraStatuses) {
2604 idsChosenForCallback.insert(String16(s.cameraId));
2605 }
Igor Murashkincba2c162013-03-20 15:56:31 -07002606
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002607 /*
2608 * Immediately signal current torch status to this listener only
2609 * This may be a subset of all the devices, so don't include it in the response directly
2610 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002611 {
2612 Mutex::Autolock al(mTorchStatusMutex);
2613 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002614 String16 id = String16(mTorchStatusMap.keyAt(i).string());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002615 // The camera id is visible to the client. Fine to send torch
2616 // callback.
2617 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
2618 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
2619 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002620 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002621 }
2622
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002623 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08002624}
Ruben Brunkcc776712015-02-17 20:18:47 -08002625
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002626Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002627 ATRACE_CALL();
2628
Igor Murashkinbfc99152013-02-27 12:55:20 -08002629 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
2630
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002631 if (listener == 0) {
2632 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002633 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002634 }
2635
Igor Murashkinbfc99152013-02-27 12:55:20 -08002636 Mutex::Autolock lock(mServiceLock);
2637
Ruben Brunkcc776712015-02-17 20:18:47 -08002638 {
2639 Mutex::Autolock lock(mStatusListenerLock);
2640 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002641 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
2642 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid());
2643 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08002644 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002645 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002646 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002647 }
2648 }
2649
2650 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
2651 __FUNCTION__, listener.get());
2652
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002653 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08002654}
2655
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002656Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002657
2658 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002659 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
2660
2661 if (parameters == NULL) {
2662 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002663 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07002664 }
2665
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002666 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002667
2668 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002669 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07002670 // Error logged by caller
2671 return ret;
2672 }
2673
2674 String8 shimParamsString8 = shimParams.flatten();
2675 String16 shimParamsString16 = String16(shimParamsString8);
2676
2677 *parameters = shimParamsString16;
2678
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002679 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07002680}
2681
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002682Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
2683 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002684 ATRACE_CALL();
2685
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002686 const String8 id = String8(cameraId);
2687
2688 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002689
2690 switch (apiVersion) {
2691 case API_VERSION_1:
2692 case API_VERSION_2:
2693 break;
2694 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002695 String8 msg = String8::format("Unknown API version %d", apiVersion);
2696 ALOGE("%s: %s", __FUNCTION__, msg.string());
2697 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002698 }
2699
Emilian Peev28ad2ea2017-02-07 16:14:32 +00002700 int deviceVersion = getDeviceVersion(id);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002701 switch (deviceVersion) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002702 case CAMERA_DEVICE_API_VERSION_1_0:
2703 case CAMERA_DEVICE_API_VERSION_3_0:
2704 case CAMERA_DEVICE_API_VERSION_3_1:
2705 if (apiVersion == API_VERSION_2) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002706 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without shim",
2707 __FUNCTION__, id.string(), deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002708 *isSupported = false;
2709 } else { // if (apiVersion == API_VERSION_1) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002710 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always supported",
2711 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002712 *isSupported = true;
2713 }
2714 break;
2715 case CAMERA_DEVICE_API_VERSION_3_2:
2716 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -07002717 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002718 case CAMERA_DEVICE_API_VERSION_3_5:
Yin-Chia Yeh56d98ba2020-01-16 16:57:14 -08002719 case CAMERA_DEVICE_API_VERSION_3_6:
Shuzhen Wang83bff122020-11-20 15:51:39 -08002720 case CAMERA_DEVICE_API_VERSION_3_7:
Shuzhen Wang90708ea2021-11-04 11:40:49 -07002721 case CAMERA_DEVICE_API_VERSION_3_8:
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002722 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
2723 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002724 *isSupported = true;
2725 break;
2726 case -1: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002727 String8 msg = String8::format("Unknown camera ID %s", id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002728 ALOGE("%s: %s", __FUNCTION__, msg.string());
2729 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002730 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002731 default: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002732 String8 msg = String8::format("Unknown device version %x for device %s",
2733 deviceVersion, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002734 ALOGE("%s: %s", __FUNCTION__, msg.string());
2735 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
2736 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07002737 }
2738
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002739 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002740}
2741
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002742Status CameraService::isHiddenPhysicalCamera(const String16& cameraId,
2743 /*out*/ bool *isSupported) {
2744 ATRACE_CALL();
2745
2746 const String8 id = String8(cameraId);
2747
2748 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
2749 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(id.string());
2750
2751 return Status::ok();
2752}
2753
Cliff Wud8cae102021-03-11 01:37:42 +08002754Status CameraService::injectCamera(
2755 const String16& packageName, const String16& internalCamId,
2756 const String16& externalCamId,
2757 const sp<ICameraInjectionCallback>& callback,
2758 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08002759 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08002760 ATRACE_CALL();
2761
2762 if (!checkCallingPermission(sCameraInjectExternalCameraPermission)) {
2763 const int pid = CameraThreadState::getCallingPid();
2764 const int uid = CameraThreadState::getCallingUid();
2765 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
2766 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2767 "Permission Denial: no permission to inject camera");
2768 }
2769
2770 ALOGV(
2771 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
2772 "%s",
2773 __FUNCTION__, String8(packageName).string(),
2774 String8(internalCamId).string(), String8(externalCamId).string());
2775
Cliff Wud3a05312021-04-26 23:07:31 +08002776 {
2777 Mutex::Autolock lock(mInjectionParametersLock);
2778 mInjectionInternalCamId = String8(internalCamId);
2779 mInjectionExternalCamId = String8(externalCamId);
Cliff Wu646bd612021-11-23 23:21:29 +08002780 mInjectionStatusListener->addListener(callback);
2781 *cameraInjectionSession = new CameraInjectionSession(this);
Cliff Wud3a05312021-04-26 23:07:31 +08002782 status_t res = NO_ERROR;
2783 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2784 // If the client already exists, we can directly connect to the camera device through the
2785 // client's injectCamera(), otherwise we need to wait until the client is established
2786 // (execute connectHelper()) before injecting the camera to the camera device.
2787 if (clientDescriptor != nullptr) {
2788 mInjectionInitPending = false;
Cliff Wu646bd612021-11-23 23:21:29 +08002789 sp<BasicClient> clientSp = clientDescriptor->getValue();
2790 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2791 if(res != OK) {
2792 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2793 "No camera device with ID \"%s\" currently available",
2794 mInjectionExternalCamId.string());
2795 }
2796 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08002797 if(res != OK) {
2798 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2799 }
2800 } else {
2801 mInjectionInitPending = true;
2802 }
2803 }
Cliff Wud8cae102021-03-11 01:37:42 +08002804
Cliff Wud3a05312021-04-26 23:07:31 +08002805 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08002806}
2807
Ruben Brunkcc776712015-02-17 20:18:47 -08002808void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002809 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002810 for (auto& i : mActiveClientManager.getAll()) {
2811 auto clientSp = i->getValue();
2812 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002813 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08002814 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08002815 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07002816 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002817 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08002818}
2819
Ruben Brunkcc776712015-02-17 20:18:47 -08002820bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002821 bool ret = false;
2822 {
2823 // Acquire mServiceLock and prevent other clients from connecting
2824 std::unique_ptr<AutoConditionLock> lock =
2825 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08002826
Igor Murashkin634a5152013-02-20 17:15:11 -08002827
Ruben Brunkcc776712015-02-17 20:18:47 -08002828 std::vector<sp<BasicClient>> evicted;
2829 for (auto& i : mActiveClientManager.getAll()) {
2830 auto clientSp = i->getValue();
2831 if (clientSp.get() == nullptr) {
2832 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2833 mActiveClientManager.remove(i);
2834 continue;
2835 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08002836 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002837 mActiveClientManager.remove(i);
2838 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08002839
Ruben Brunkcc776712015-02-17 20:18:47 -08002840 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002841 clientSp->notifyError(
2842 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002843 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08002844 }
2845 }
2846
Ruben Brunkcc776712015-02-17 20:18:47 -08002847 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2848 // other clients from connecting in mServiceLockWrapper if held
2849 mServiceLock.unlock();
2850
Ruben Brunk36597b22015-03-20 22:15:57 -07002851 // Do not clear caller identity, remote caller should be client proccess
2852
Ruben Brunkcc776712015-02-17 20:18:47 -08002853 for (auto& i : evicted) {
2854 if (i.get() != nullptr) {
2855 i->disconnect();
2856 ret = true;
2857 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002858 }
2859
Ruben Brunkcc776712015-02-17 20:18:47 -08002860 // Reacquire mServiceLock
2861 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08002862
Ruben Brunkcc776712015-02-17 20:18:47 -08002863 } // lock is destroyed, allow further connect calls
2864
2865 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07002866}
2867
Ruben Brunkcc776712015-02-17 20:18:47 -08002868std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
2869 const String8& cameraId) const {
2870 std::shared_ptr<CameraState> state;
2871 {
2872 Mutex::Autolock lock(mCameraStatesLock);
2873 auto iter = mCameraStates.find(cameraId);
2874 if (iter != mCameraStates.end()) {
2875 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002876 }
2877 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002878 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002879}
2880
Ruben Brunkcc776712015-02-17 20:18:47 -08002881sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
2882 // Remove from active clients list
2883 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
2884 if (clientDescriptorPtr == nullptr) {
2885 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
2886 cameraId.string());
2887 return sp<BasicClient>{nullptr};
2888 }
2889
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002890 sp<BasicClient> client = clientDescriptorPtr->getValue();
2891 if (client.get() != nullptr) {
2892 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
2893 }
2894 return client;
Keun young Parkd8973a72012-03-28 14:13:09 -07002895}
2896
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002897void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07002898 // Acquire mServiceLock and prevent other clients from connecting
2899 std::unique_ptr<AutoConditionLock> lock =
2900 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
2901
Ruben Brunk6267b532015-04-30 17:44:07 -07002902 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002903 for (size_t i = 0; i < newUserIds.size(); i++) {
2904 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07002905 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002906 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07002907 return;
2908 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002909 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07002910 }
2911
Ruben Brunka8ca9152015-04-07 14:23:40 -07002912
Ruben Brunk6267b532015-04-30 17:44:07 -07002913 if (newAllowedUsers == mAllowedUsers) {
2914 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
2915 return;
2916 }
2917
2918 logUserSwitch(mAllowedUsers, newAllowedUsers);
2919
2920 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07002921
2922 // Current user has switched, evict all current clients.
2923 std::vector<sp<BasicClient>> evicted;
2924 for (auto& i : mActiveClientManager.getAll()) {
2925 auto clientSp = i->getValue();
2926
2927 if (clientSp.get() == nullptr) {
2928 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2929 continue;
2930 }
2931
Ruben Brunk6267b532015-04-30 17:44:07 -07002932 // Don't evict clients that are still allowed.
2933 uid_t clientUid = clientSp->getClientUid();
2934 userid_t clientUserId = multiuser_get_user_id(clientUid);
2935 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
2936 continue;
2937 }
2938
Ruben Brunk36597b22015-03-20 22:15:57 -07002939 evicted.push_back(clientSp);
2940
2941 String8 curTime = getFormattedCurrentTime();
2942
2943 ALOGE("Evicting conflicting client for camera ID %s due to user change",
2944 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07002945
Ruben Brunk36597b22015-03-20 22:15:57 -07002946 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002947 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00002948 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
2949 " to user switch.", i->getKey().string(),
2950 String8{clientSp->getPackageName()}.string(),
2951 i->getOwnerId(), i->getPriority().getScore(),
2952 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07002953
2954 }
2955
2956 // Do not hold mServiceLock while disconnecting clients, but retain the condition
2957 // blocking other clients from connecting in mServiceLockWrapper if held.
2958 mServiceLock.unlock();
2959
2960 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07002961 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07002962
2963 for (auto& i : evicted) {
2964 i->disconnect();
2965 }
2966
Jayant Chowdhary12361932018-08-27 14:46:13 -07002967 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07002968
2969 // Reacquire mServiceLock
2970 mServiceLock.lock();
2971}
Ruben Brunkcc776712015-02-17 20:18:47 -08002972
Ruben Brunka8ca9152015-04-07 14:23:40 -07002973void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002974 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07002975 Mutex::Autolock l(mLogLock);
Rucha Katakward9ea6452021-05-06 11:57:16 -07002976 String8 msg = String8::format("%s : %s", curTime.string(), event);
2977 // For service error events, print the msg only once.
2978 if(!msg.contains("SERVICE ERROR")) {
2979 mEventLog.add(msg);
2980 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
2981 // Error event not added to the dumpsys log before
2982 mEventLog.add(msg);
2983 sServiceErrorEventSet.insert(msg);
2984 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002985}
2986
Ruben Brunka8ca9152015-04-07 14:23:40 -07002987void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002988 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002989 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002990 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002991 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002992}
2993
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002994void CameraService::logDisconnectedOffline(const char* cameraId, int clientPid,
2995 const char* clientPackage) {
2996 // Log the clients evicted
2997 logEvent(String8::format("DISCONNECT offline device %s client for package %s (PID %d)",
2998 cameraId, clientPackage, clientPid));
2999}
3000
Ruben Brunka8ca9152015-04-07 14:23:40 -07003001void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003002 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003003 // Log the clients evicted
3004 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003005 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003006}
3007
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003008void CameraService::logConnectedOffline(const char* cameraId, int clientPid,
3009 const char* clientPackage) {
3010 // Log the clients evicted
3011 logEvent(String8::format("CONNECT offline device %s client for package %s (PID %d)", cameraId,
3012 clientPackage, clientPid));
3013}
3014
Ruben Brunka8ca9152015-04-07 14:23:40 -07003015void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003016 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003017 // Log the client rejected
3018 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003019 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003020}
3021
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003022void CameraService::logTorchEvent(const char* cameraId, const char *torchState, int clientPid) {
3023 // Log torch event
3024 logEvent(String8::format("Torch for camera id %s turned %s for client PID %d", cameraId,
3025 torchState, clientPid));
3026}
3027
Ruben Brunk6267b532015-04-30 17:44:07 -07003028void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
3029 const std::set<userid_t>& newUserIds) {
3030 String8 newUsers = toString(newUserIds);
3031 String8 oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003032 if (oldUsers.size() == 0) {
3033 oldUsers = "<None>";
3034 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07003035 // Log the new and old users
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003036 logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
Ruben Brunk6267b532015-04-30 17:44:07 -07003037 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003038}
3039
3040void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
3041 // Log the device removal
3042 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
3043}
3044
3045void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
3046 // Log the device removal
3047 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
3048}
3049
3050void CameraService::logClientDied(int clientPid, const char* reason) {
3051 // Log the device removal
3052 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07003053}
3054
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003055void CameraService::logServiceError(const char* msg, int errorCode) {
3056 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08003057 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003058}
3059
Ruben Brunk36597b22015-03-20 22:15:57 -07003060status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
3061 uint32_t flags) {
3062
Mathias Agopian65ab4712010-07-14 17:59:35 -07003063 // Permission checks
3064 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003065 case SHELL_COMMAND_TRANSACTION: {
3066 int in = data.readFileDescriptor();
3067 int out = data.readFileDescriptor();
3068 int err = data.readFileDescriptor();
3069 int argc = data.readInt32();
3070 Vector<String16> args;
3071 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
3072 args.add(data.readString16());
3073 }
3074 sp<IBinder> unusedCallback;
3075 sp<IResultReceiver> resultReceiver;
3076 status_t status;
3077 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
3078 return status;
3079 }
3080 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
3081 return status;
3082 }
3083 status = shellCommand(in, out, err, args);
3084 if (resultReceiver != nullptr) {
3085 resultReceiver->send(status);
3086 }
3087 return NO_ERROR;
3088 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003089 }
3090
3091 return BnCameraService::onTransact(code, data, reply, flags);
3092}
3093
Mathias Agopian65ab4712010-07-14 17:59:35 -07003094// We share the media players for shutter and recording sound for all clients.
3095// A reference count is kept to determine when we will actually release the
3096// media players.
3097
Jaekyun Seokef498052018-03-23 13:09:44 +09003098sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
3099 sp<MediaPlayer> mp = new MediaPlayer();
3100 status_t error;
3101 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08003102 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09003103 error = mp->prepare();
3104 }
3105 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00003106 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09003107 mp->disconnect();
3108 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003109 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003110 }
3111 return mp;
3112}
3113
username5755fea2018-12-27 09:48:08 +08003114void CameraService::increaseSoundRef() {
3115 Mutex::Autolock lock(mSoundLock);
3116 mSoundRef++;
3117}
3118
3119void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003120 ATRACE_CALL();
3121
username5755fea2018-12-27 09:48:08 +08003122 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
3123 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
3124 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
3125 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
3126 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
3127 }
3128 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
3129 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
3130 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
3131 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003132 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08003133 }
3134 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
3135 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
3136 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
3137 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
3138 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003139 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003140}
3141
username5755fea2018-12-27 09:48:08 +08003142void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003143 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08003144 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003145 if (--mSoundRef) return;
3146
3147 for (int i = 0; i < NUM_SOUNDS; i++) {
3148 if (mSoundPlayer[i] != 0) {
3149 mSoundPlayer[i]->disconnect();
3150 mSoundPlayer[i].clear();
3151 }
3152 }
3153}
3154
3155void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003156 ATRACE_CALL();
3157
Mathias Agopian65ab4712010-07-14 17:59:35 -07003158 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07003159 if (kind < 0 || kind >= NUM_SOUNDS) {
3160 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
3161 return;
3162 }
3163
Mathias Agopian65ab4712010-07-14 17:59:35 -07003164 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08003165 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003166 sp<MediaPlayer> player = mSoundPlayer[kind];
3167 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08003168 player->seekTo(0);
3169 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003170 }
3171}
3172
3173// ----------------------------------------------------------------------------
3174
3175CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07003176 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003177 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09003178 const std::optional<String16>& clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003179 const String8& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07003180 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003181 int clientPid, uid_t clientUid,
3182 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08003183 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08003184 IInterface::asBinder(cameraClient),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08003185 clientPackageName, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07003186 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003187 clientPid, clientUid,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003188 servicePid),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003189 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08003190{
Jayant Chowdhary12361932018-08-27 14:46:13 -07003191 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003192 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003193
Igor Murashkin44cfcf02013-03-01 16:22:28 -08003194 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003195
username5755fea2018-12-27 09:48:08 +08003196 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003197
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003198 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003199}
3200
Mathias Agopian65ab4712010-07-14 17:59:35 -07003201// tear down the client
3202CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003203 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08003204 mDestructionStarted = true;
3205
username5755fea2018-12-27 09:48:08 +08003206 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003207 // unconditionally disconnect. function is idempotent
3208 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003209}
3210
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003211sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
3212
Igor Murashkin634a5152013-02-20 17:15:11 -08003213CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003214 const sp<IBinder>& remoteCallback,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09003215 const String16& clientPackageName, const std::optional<String16>& clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07003216 const String8& cameraIdStr, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003217 int clientPid, uid_t clientUid,
3218 int servicePid):
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003219 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07003220 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09003221 mClientPackageName(clientPackageName), mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08003222 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003223 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07003224 mDisconnected(false), mUidIsTrusted(false),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003225 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003226 mRemoteBinder(remoteCallback),
3227 mOpsActive(false),
3228 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08003229{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003230 if (sCameraService == nullptr) {
3231 sCameraService = cameraService;
3232 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08003233
3234 // In some cases the calling code has no access to the package it runs under.
3235 // For example, NDK camera API.
3236 // In this case we will get the packages for the calling UID and pick the first one
3237 // for attributing the app op. This will work correctly for runtime permissions
3238 // as for legacy apps we will toggle the app op for all packages in the UID.
3239 // The caveat is that the operation may be attributed to the wrong package and
3240 // stats based on app ops may be slightly off.
3241 if (mClientPackageName.size() <= 0) {
3242 sp<IServiceManager> sm = defaultServiceManager();
3243 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
3244 if (binder == 0) {
3245 ALOGE("Cannot get permission service");
3246 // Leave mClientPackageName unchanged (empty) and the further interaction
3247 // with camera will fail in BasicClient::startCameraOps
3248 return;
3249 }
3250
3251 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
3252 Vector<String16> packages;
3253
3254 permCtrl->getPackagesForUid(mClientUid, packages);
3255
3256 if (packages.isEmpty()) {
3257 ALOGE("No packages for calling UID");
3258 // Leave mClientPackageName unchanged (empty) and the further interaction
3259 // with camera will fail in BasicClient::startCameraOps
3260 return;
3261 }
3262 mClientPackageName = packages[0];
3263 }
Steven Moreland89a2c5c2020-01-31 15:02:25 -08003264 if (getCurrentServingCall() != BinderCallType::HWBINDER) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003265 mAppOpsManager = std::make_unique<AppOpsManager>();
3266 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07003267
3268 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08003269}
3270
3271CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003272 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08003273 mDestructionStarted = true;
3274}
3275
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003276binder::Status CameraService::BasicClient::disconnect() {
3277 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003278 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003279 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07003280 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07003281 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08003282
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003283 sCameraService->removeByClient(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003284 sCameraService->logDisconnected(mCameraIdStr, mClientPid, String8(mClientPackageName));
Peter Kalauskasa29c1352018-10-10 12:05:42 -07003285 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
3286 mCameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003287
3288 sp<IBinder> remote = getRemote();
3289 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003290 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08003291 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003292
3293 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07003294 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003295 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
3296 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
3297 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003298
Igor Murashkincba2c162013-03-20 15:56:31 -07003299 // client shouldn't be able to call into us anymore
3300 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003301
3302 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08003303}
3304
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08003305status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
3306 // No dumping of clients directly over Binder,
3307 // must go through CameraService::dump
3308 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07003309 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08003310 return OK;
3311}
3312
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07003313status_t CameraService::BasicClient::startWatchingTags(const String8&, int) {
3314 // Can't watch tags directly, must go through CameraService::startWatchingTags
3315 return OK;
3316}
3317
3318status_t CameraService::BasicClient::stopWatchingTags(int) {
3319 // Can't watch tags directly, must go through CameraService::stopWatchingTags
3320 return OK;
3321}
3322
3323status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
3324 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
3325 return OK;
3326}
3327
Ruben Brunkcc776712015-02-17 20:18:47 -08003328String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003329 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08003330}
3331
Emilian Peev8b64f282021-03-25 16:49:57 -07003332int CameraService::BasicClient::getCameraFacing() const {
3333 return mCameraFacing;
3334}
3335
3336int CameraService::BasicClient::getCameraOrientation() const {
3337 return mOrientation;
3338}
Ruben Brunkcc776712015-02-17 20:18:47 -08003339
3340int CameraService::BasicClient::getClientPid() const {
3341 return mClientPid;
3342}
3343
Ruben Brunk6267b532015-04-30 17:44:07 -07003344uid_t CameraService::BasicClient::getClientUid() const {
3345 return mClientUid;
3346}
3347
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003348bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
3349 // Defaults to API2.
3350 return level == API_2;
3351}
3352
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07003353status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003354 {
3355 Mutex::Autolock l(mAudioRestrictionLock);
3356 mAudioRestriction = mode;
3357 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07003358 sCameraService->updateAudioRestriction();
3359 return OK;
3360}
3361
3362int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003363 return sCameraService->updateAudioRestriction();
3364}
3365
3366int32_t CameraService::BasicClient::getAudioRestriction() const {
3367 Mutex::Autolock l(mAudioRestrictionLock);
3368 return mAudioRestriction;
3369}
3370
3371bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
3372 switch (mode) {
3373 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
3374 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
3375 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
3376 return true;
3377 default:
3378 return false;
3379 }
3380}
3381
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003382status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
3383 if (mode == AppOpsManager::MODE_ERRORED) {
3384 ALOGI("Camera %s: Access for \"%s\" has been revoked",
3385 mCameraIdStr.string(), String8(mClientPackageName).string());
3386 return PERMISSION_DENIED;
3387 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
3388 // If the calling Uid is trusted (a native service), the AppOpsManager could
3389 // return MODE_IGNORED. Do not treat such case as error.
3390 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
3391 mClientPackageName);
3392 bool isCameraPrivacyEnabled =
3393 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled(
3394 multiuser_get_user_id(mClientUid));
3395 if (!isUidActive || !isCameraPrivacyEnabled) {
3396 ALOGI("Camera %s: Access for \"%s\" has been restricted",
3397 mCameraIdStr.string(), String8(mClientPackageName).string());
3398 // Return the same error as for device policy manager rejection
3399 return -EACCES;
3400 }
3401 }
3402 return OK;
3403}
3404
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003405status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003406 ATRACE_CALL();
3407
Igor Murashkine6800ce2013-03-04 17:25:57 -08003408 {
3409 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003410 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08003411 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003412 if (mAppOpsManager != nullptr) {
3413 // Notify app ops that the camera is not available
3414 mOpsCallback = new OpsCallback(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003415 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
3416 mClientPackageName, mOpsCallback);
Igor Murashkine6800ce2013-03-04 17:25:57 -08003417
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003418 // Just check for camera acccess here on open - delay startOp until
3419 // camera frames start streaming in startCameraStreamingOps
3420 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
3421 mClientPackageName);
3422 status_t res = handleAppOpMode(mode);
3423 if (res != OK) {
3424 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003425 }
Svetoslav28e8ef72015-05-11 19:21:31 -07003426 }
3427
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003428 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003429
3430 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003431 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003432
Emilian Peev53722fa2019-02-22 17:47:20 -08003433 sCameraService->mUidPolicy->registerMonitorUid(mClientUid);
3434
Shuzhen Wang695044d2020-03-06 09:02:23 -08003435 // Notify listeners of camera open/close status
3436 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
3437
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003438 return OK;
3439}
3440
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003441status_t CameraService::BasicClient::startCameraStreamingOps() {
3442 ATRACE_CALL();
3443
3444 if (!mOpsActive) {
3445 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
3446 return INVALID_OPERATION;
3447 }
3448 if (mOpsStreaming) {
3449 ALOGV("%s: Streaming already active!", __FUNCTION__);
3450 return OK;
3451 }
3452
3453 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
3454 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
3455
3456 if (mAppOpsManager != nullptr) {
3457 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
3458 mClientPackageName, /*startIfModeDefault*/ false, mClientFeatureId,
3459 String16("start camera ") + String16(mCameraIdStr));
3460 status_t res = handleAppOpMode(mode);
3461 if (res != OK) {
3462 return res;
3463 }
3464 }
3465
3466 mOpsStreaming = true;
3467
3468 return OK;
3469}
3470
Valentin Iftimec0b8d472021-07-23 20:21:06 +02003471status_t CameraService::BasicClient::noteAppOp() {
3472 ATRACE_CALL();
3473
3474 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d",
3475 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
3476
3477 // noteAppOp is only used for when camera mute is not supported, in order
3478 // to trigger the sensor privacy "Unblock" dialog
3479 if (mAppOpsManager != nullptr) {
3480 int32_t mode = mAppOpsManager->noteOp(AppOpsManager::OP_CAMERA, mClientUid,
3481 mClientPackageName, mClientFeatureId,
3482 String16("start camera ") + String16(mCameraIdStr));
3483 status_t res = handleAppOpMode(mode);
3484 if (res != OK) {
3485 return res;
3486 }
3487 }
3488
3489 return OK;
3490}
3491
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003492status_t CameraService::BasicClient::finishCameraStreamingOps() {
3493 ATRACE_CALL();
3494
3495 if (!mOpsActive) {
3496 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
3497 return INVALID_OPERATION;
3498 }
3499 if (!mOpsStreaming) {
3500 ALOGV("%s: Streaming not active!", __FUNCTION__);
3501 return OK;
3502 }
3503
3504 if (mAppOpsManager != nullptr) {
3505 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
3506 mClientPackageName, mClientFeatureId);
3507 mOpsStreaming = false;
3508 }
3509
3510 return OK;
3511}
3512
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003513status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003514 ATRACE_CALL();
3515
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003516 if (mOpsStreaming) {
3517 // Make sure we've notified everyone about camera stopping
3518 finishCameraStreamingOps();
3519 }
3520
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003521 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003522 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003523 mOpsActive = false;
3524
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01003525 // This function is called when a client disconnects. This should
3526 // release the camera, but actually only if it was in a proper
3527 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003528 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01003529 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003530
Ruben Brunkcc776712015-02-17 20:18:47 -08003531 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003532 sCameraService->updateStatus(StatusInternal::PRESENT,
3533 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003534 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003535 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003536 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
3537 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08003538 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003539 mOpsCallback.clear();
3540
Emilian Peev53722fa2019-02-22 17:47:20 -08003541 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid);
3542
Shuzhen Wang695044d2020-03-06 09:02:23 -08003543 // Notify listeners of camera open/close status
3544 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
3545
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003546 return OK;
3547}
3548
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003549void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003550 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003551 if (mAppOpsManager == nullptr) {
3552 return;
3553 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003554 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003555 if (op != AppOpsManager::OP_CAMERA) {
3556 ALOGW("Unexpected app ops notification received: %d", op);
3557 return;
3558 }
3559
3560 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003561 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003562 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003563 ALOGV("checkOp returns: %d, %s ", res,
3564 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
3565 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
3566 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
3567 "UNKNOWN");
3568
Shuzhen Wang64900852021-02-05 09:03:29 -08003569 if (res == AppOpsManager::MODE_ERRORED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003570 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003571 String8(mClientPackageName).string());
Svet Ganova453d0d2018-01-11 15:37:58 -08003572 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08003573 } else if (res == AppOpsManager::MODE_IGNORED) {
3574 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Evan Severson09ab4002021-02-10 14:15:19 -08003575 bool isCameraPrivacyEnabled =
3576 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled(
3577 multiuser_get_user_id(mClientUid));
Shuzhen Wang64900852021-02-05 09:03:29 -08003578 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d",
3579 mCameraIdStr.string(), String8(mClientPackageName).string(),
3580 mUidIsTrusted, isUidActive);
3581 // If the calling Uid is trusted (a native service), or the client Uid is active (WAR for
3582 // b/175320666), the AppOpsManager could return MODE_IGNORED. Do not treat such cases as
3583 // error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02003584 if (!mUidIsTrusted) {
3585 if (isUidActive && isCameraPrivacyEnabled && supportsCameraMute()) {
3586 setCameraMute(true);
3587 } else if (!isUidActive
3588 || (isCameraPrivacyEnabled && !supportsCameraMute())) {
3589 block();
3590 }
Shuzhen Wang64900852021-02-05 09:03:29 -08003591 }
Evan Severson09ab4002021-02-10 14:15:19 -08003592 } else if (res == AppOpsManager::MODE_ALLOWED) {
3593 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003594 }
3595}
3596
Svet Ganova453d0d2018-01-11 15:37:58 -08003597void CameraService::BasicClient::block() {
3598 ATRACE_CALL();
3599
3600 // Reset the client PID to allow server-initiated disconnect,
3601 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003602 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08003603 CaptureResultExtras resultExtras; // a dummy result (invalid)
3604 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
3605 disconnect();
3606}
3607
Mathias Agopian65ab4712010-07-14 17:59:35 -07003608// ----------------------------------------------------------------------------
3609
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003610void CameraService::Client::notifyError(int32_t errorCode,
Jianing Weicb0652e2014-03-12 18:29:36 -07003611 const CaptureResultExtras& resultExtras) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08003612 (void) resultExtras;
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003613 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07003614 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
3615 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
3616 api1ErrorCode = CAMERA_ERROR_DISABLED;
3617 }
3618 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003619 } else {
3620 ALOGE("mRemoteCallback is NULL!!");
3621 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003622}
3623
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003624// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003625binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003626 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003627 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08003628}
3629
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003630bool CameraService::Client::canCastToApiClient(apiLevel level) const {
3631 return level == API_1;
3632}
3633
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003634CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
3635 mClient(client) {
3636}
3637
3638void CameraService::Client::OpsCallback::opChanged(int32_t op,
3639 const String16& packageName) {
3640 sp<BasicClient> client = mClient.promote();
3641 if (client != NULL) {
3642 client->opChanged(op, packageName);
3643 }
3644}
3645
Mathias Agopian65ab4712010-07-14 17:59:35 -07003646// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08003647// UidPolicy
3648// ----------------------------------------------------------------------------
3649
3650void CameraService::UidPolicy::registerSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003651 Mutex::Autolock _l(mUidLock);
3652
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003653 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07003654 status_t res = mAm.linkToDeath(this);
3655 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08003656 | ActivityManager::UID_OBSERVER_IDLE
Emilian Peev53722fa2019-02-22 17:47:20 -08003657 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganova453d0d2018-01-11 15:37:58 -08003658 ActivityManager::PROCESS_STATE_UNKNOWN,
3659 String16("cameraserver"));
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003660 if (res == OK) {
3661 mRegistered = true;
3662 ALOGV("UidPolicy: Registered with ActivityManager");
3663 }
Svet Ganova453d0d2018-01-11 15:37:58 -08003664}
3665
3666void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003667 Mutex::Autolock _l(mUidLock);
3668
Steven Moreland2f348142019-07-02 15:59:07 -07003669 mAm.unregisterUidObserver(this);
3670 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003671 mRegistered = false;
3672 mActiveUids.clear();
3673 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08003674}
3675
3676void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
3677 onUidIdle(uid, disabled);
3678}
3679
3680void CameraService::UidPolicy::onUidActive(uid_t uid) {
3681 Mutex::Autolock _l(mUidLock);
3682 mActiveUids.insert(uid);
3683}
3684
3685void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
3686 bool deleted = false;
3687 {
3688 Mutex::Autolock _l(mUidLock);
3689 if (mActiveUids.erase(uid) > 0) {
3690 deleted = true;
3691 }
3692 }
3693 if (deleted) {
3694 sp<CameraService> service = mService.promote();
3695 if (service != nullptr) {
3696 service->blockClientsForUid(uid);
3697 }
3698 }
3699}
3700
Emilian Peev53722fa2019-02-22 17:47:20 -08003701void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07003702 int64_t procStateSeq __unused, int32_t capability __unused) {
Emilian Peev53722fa2019-02-22 17:47:20 -08003703 bool procStateChange = false;
3704 {
3705 Mutex::Autolock _l(mUidLock);
3706 if ((mMonitoredUids.find(uid) != mMonitoredUids.end()) &&
3707 (mMonitoredUids[uid].first != procState)) {
3708 mMonitoredUids[uid].first = procState;
3709 procStateChange = true;
3710 }
3711 }
3712
3713 if (procStateChange) {
3714 sp<CameraService> service = mService.promote();
3715 if (service != nullptr) {
3716 service->notifyMonitoredUids();
3717 }
3718 }
3719}
3720
3721void CameraService::UidPolicy::registerMonitorUid(uid_t uid) {
3722 Mutex::Autolock _l(mUidLock);
3723 auto it = mMonitoredUids.find(uid);
3724 if (it != mMonitoredUids.end()) {
3725 it->second.second++;
3726 } else {
3727 mMonitoredUids.emplace(
3728 std::pair<uid_t, std::pair<int32_t, size_t>> (uid,
3729 std::pair<int32_t, size_t> (ActivityManager::PROCESS_STATE_NONEXISTENT, 1)));
3730 }
3731}
3732
3733void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid) {
3734 Mutex::Autolock _l(mUidLock);
3735 auto it = mMonitoredUids.find(uid);
3736 if (it != mMonitoredUids.end()) {
3737 it->second.second--;
3738 if (it->second.second == 0) {
3739 mMonitoredUids.erase(it);
3740 }
3741 } else {
3742 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
3743 }
3744}
3745
Svet Ganov7b4ab782018-03-25 12:48:10 -07003746bool CameraService::UidPolicy::isUidActive(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003747 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003748 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003749}
3750
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003751static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
3752static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003753
Svet Ganov7b4ab782018-03-25 12:48:10 -07003754bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003755 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003756 // If activity manager is unreachable, assume everything is active
3757 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003758 return true;
3759 }
3760 auto it = mOverrideUids.find(uid);
3761 if (it != mOverrideUids.end()) {
3762 return it->second;
3763 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003764 bool active = mActiveUids.find(uid) != mActiveUids.end();
3765 if (!active) {
3766 // We want active UIDs to always access camera with their first attempt since
3767 // there is no guarantee the app is robustly written and would retry getting
3768 // the camera on failure. The inverse case is not a problem as we would take
3769 // camera away soon once we get the callback that the uid is no longer active.
3770 ActivityManager am;
3771 // Okay to access with a lock held as UID changes are dispatched without
3772 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07003773 int64_t startTimeMillis = 0;
3774 do {
3775 // TODO: Fix this b/109950150!
3776 // Okay this is a hack. There is a race between the UID turning active and
3777 // activity being resumed. The proper fix is very risky, so we temporary add
3778 // some polling which should happen pretty rarely anyway as the race is hard
3779 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003780 active = mActiveUids.find(uid) != mActiveUids.end();
Hui Yu12c7ec72020-05-04 17:40:52 +00003781 if (!active) active = am.isUidActive(uid, callingPackage);
Svet Ganov94ec46f2018-06-08 15:03:46 -07003782 if (active) {
3783 break;
3784 }
3785 if (startTimeMillis <= 0) {
3786 startTimeMillis = uptimeMillis();
3787 }
3788 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003789 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003790 if (remainingTimeMillis <= 0) {
3791 break;
3792 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003793 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
3794
3795 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003796 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003797 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003798 } while (true);
3799
Svet Ganov7b4ab782018-03-25 12:48:10 -07003800 if (active) {
3801 // Now that we found out the UID is actually active, cache that
3802 mActiveUids.insert(uid);
3803 }
3804 }
3805 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08003806}
3807
Varun Shahb42f1eb2019-04-16 14:45:13 -07003808int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
3809 Mutex::Autolock _l(mUidLock);
3810 return getProcStateLocked(uid);
3811}
3812
3813int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
3814 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
3815 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
3816 procState = mMonitoredUids[uid].first;
3817 }
3818 return procState;
3819}
3820
Svet Ganov7b4ab782018-03-25 12:48:10 -07003821void CameraService::UidPolicy::UidPolicy::addOverrideUid(uid_t uid,
3822 String16 callingPackage, bool active) {
3823 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08003824}
3825
Svet Ganov7b4ab782018-03-25 12:48:10 -07003826void CameraService::UidPolicy::removeOverrideUid(uid_t uid, String16 callingPackage) {
3827 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08003828}
3829
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003830void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
3831 Mutex::Autolock _l(mUidLock);
3832 ALOGV("UidPolicy: ActivityManager has died");
3833 mRegistered = false;
3834 mActiveUids.clear();
3835}
3836
Svet Ganov7b4ab782018-03-25 12:48:10 -07003837void CameraService::UidPolicy::updateOverrideUid(uid_t uid, String16 callingPackage,
3838 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003839 bool wasActive = false;
3840 bool isActive = false;
3841 {
3842 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003843 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003844 mOverrideUids.erase(uid);
3845 if (insert) {
3846 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
3847 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003848 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003849 }
3850 if (wasActive != isActive && !isActive) {
3851 sp<CameraService> service = mService.promote();
3852 if (service != nullptr) {
3853 service->blockClientsForUid(uid);
3854 }
3855 }
3856}
3857
3858// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08003859// SensorPrivacyPolicy
3860// ----------------------------------------------------------------------------
3861void CameraService::SensorPrivacyPolicy::registerSelf() {
3862 Mutex::Autolock _l(mSensorPrivacyLock);
3863 if (mRegistered) {
3864 return;
3865 }
Evan Severson09ab4002021-02-10 14:15:19 -08003866 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08003867 mSpm.addSensorPrivacyListener(this);
3868 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
3869 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003870 if (res == OK) {
3871 mRegistered = true;
3872 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
3873 }
3874}
3875
3876void CameraService::SensorPrivacyPolicy::unregisterSelf() {
3877 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08003878 mSpm.removeSensorPrivacyListener(this);
3879 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003880 mRegistered = false;
3881 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
3882}
3883
3884bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
3885 Mutex::Autolock _l(mSensorPrivacyLock);
3886 return mSensorPrivacyEnabled;
3887}
3888
Evan Severson09ab4002021-02-10 14:15:19 -08003889bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled(userid_t userId) {
3890 if (!hasCameraPrivacyFeature()) {
3891 return false;
3892 }
3893 return mSpm.isIndividualSensorPrivacyEnabled(userId,
3894 SensorPrivacyManager::INDIVIDUAL_SENSOR_CAMERA);
3895}
3896
Michael Grooverd1d435a2018-12-18 17:39:42 -08003897binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
3898 {
3899 Mutex::Autolock _l(mSensorPrivacyLock);
3900 mSensorPrivacyEnabled = enabled;
3901 }
3902 // if sensor privacy is enabled then block all clients from accessing the camera
Evan Severson09ab4002021-02-10 14:15:19 -08003903 if (enabled) {
3904 sp<CameraService> service = mService.promote();
3905 if (service != nullptr) {
3906 service->blockAllClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08003907 }
3908 }
3909 return binder::Status::ok();
3910}
3911
3912void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
3913 Mutex::Autolock _l(mSensorPrivacyLock);
3914 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
3915 mRegistered = false;
3916}
3917
Evan Severson09ab4002021-02-10 14:15:19 -08003918bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Severson671806e2021-04-20 16:44:53 -07003919 return mSpm.supportsSensorToggle(SensorPrivacyManager::INDIVIDUAL_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08003920}
3921
Michael Grooverd1d435a2018-12-18 17:39:42 -08003922// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003923// CameraState
3924// ----------------------------------------------------------------------------
3925
3926CameraService::CameraState::CameraState(const String8& id, int cost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003927 const std::set<String8>& conflicting, SystemCameraKind systemCameraKind) : mId(id),
3928 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
3929 mSystemCameraKind(systemCameraKind) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08003930
3931CameraService::CameraState::~CameraState() {}
3932
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003933CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003934 Mutex::Autolock lock(mStatusLock);
3935 return mStatus;
3936}
3937
Shuzhen Wang43858162020-01-10 13:42:15 -08003938std::vector<String8> CameraService::CameraState::getUnavailablePhysicalIds() const {
3939 Mutex::Autolock lock(mStatusLock);
3940 std::vector<String8> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
3941 return res;
3942}
3943
Ruben Brunkcc776712015-02-17 20:18:47 -08003944CameraParameters CameraService::CameraState::getShimParams() const {
3945 return mShimParams;
3946}
3947
3948void CameraService::CameraState::setShimParams(const CameraParameters& params) {
3949 mShimParams = params;
3950}
3951
3952int CameraService::CameraState::getCost() const {
3953 return mCost;
3954}
3955
3956std::set<String8> CameraService::CameraState::getConflicting() const {
3957 return mConflicting;
3958}
3959
3960String8 CameraService::CameraState::getId() const {
3961 return mId;
3962}
3963
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003964SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
3965 return mSystemCameraKind;
3966}
3967
Shuzhen Wang43858162020-01-10 13:42:15 -08003968bool CameraService::CameraState::addUnavailablePhysicalId(const String8& physicalId) {
3969 Mutex::Autolock lock(mStatusLock);
3970 auto result = mUnavailablePhysicalIds.insert(physicalId);
3971 return result.second;
3972}
3973
3974bool CameraService::CameraState::removeUnavailablePhysicalId(const String8& physicalId) {
3975 Mutex::Autolock lock(mStatusLock);
3976 auto count = mUnavailablePhysicalIds.erase(physicalId);
3977 return count > 0;
3978}
3979
Shuzhen Wange7aa0342021-08-03 11:29:47 -07003980void CameraService::CameraState::setClientPackage(const String8& clientPackage) {
3981 Mutex::Autolock lock(mStatusLock);
3982 mClientPackage = clientPackage;
3983}
3984
3985String8 CameraService::CameraState::getClientPackage() const {
3986 Mutex::Autolock lock(mStatusLock);
3987 return mClientPackage;
3988}
3989
Ruben Brunkcc776712015-02-17 20:18:47 -08003990// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07003991// ClientEventListener
3992// ----------------------------------------------------------------------------
3993
3994void CameraService::ClientEventListener::onClientAdded(
3995 const resource_policy::ClientDescriptor<String8,
3996 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003997 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003998 if (basicClient.get() != nullptr) {
3999 BatteryNotifier& notifier(BatteryNotifier::getInstance());
4000 notifier.noteStartCamera(descriptor.getKey(),
4001 static_cast<int>(basicClient->getClientUid()));
4002 }
4003}
4004
4005void CameraService::ClientEventListener::onClientRemoved(
4006 const resource_policy::ClientDescriptor<String8,
4007 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07004008 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07004009 if (basicClient.get() != nullptr) {
4010 BatteryNotifier& notifier(BatteryNotifier::getInstance());
4011 notifier.noteStopCamera(descriptor.getKey(),
4012 static_cast<int>(basicClient->getClientUid()));
4013 }
4014}
4015
4016
4017// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08004018// CameraClientManager
4019// ----------------------------------------------------------------------------
4020
Ruben Brunk99e69712015-05-26 17:25:07 -07004021CameraService::CameraClientManager::CameraClientManager() {
4022 setListener(std::make_shared<ClientEventListener>());
4023}
4024
Ruben Brunkcc776712015-02-17 20:18:47 -08004025CameraService::CameraClientManager::~CameraClientManager() {}
4026
4027sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
4028 const String8& id) const {
4029 auto descriptor = get(id);
4030 if (descriptor == nullptr) {
4031 return sp<BasicClient>{nullptr};
4032 }
4033 return descriptor->getValue();
4034}
4035
4036String8 CameraService::CameraClientManager::toString() const {
4037 auto all = getAll();
4038 String8 ret("[");
4039 bool hasAny = false;
4040 for (auto& i : all) {
4041 hasAny = true;
4042 String8 key = i->getKey();
4043 int32_t cost = i->getCost();
4044 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00004045 int32_t score = i->getPriority().getScore();
4046 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08004047 auto conflicting = i->getConflicting();
4048 auto clientSp = i->getValue();
4049 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07004050 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08004051 if (clientSp.get() != nullptr) {
4052 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07004053 uid_t clientUid = clientSp->getClientUid();
4054 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08004055 }
Emilian Peev8131a262017-02-01 12:33:43 +00004056 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
4057 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08004058
Ruben Brunk6267b532015-04-30 17:44:07 -07004059 if (clientSp.get() != nullptr) {
4060 ret.appendFormat("User Id: %d, ", clientUserId);
4061 }
Ruben Brunkcc776712015-02-17 20:18:47 -08004062 if (packageName.size() != 0) {
4063 ret.appendFormat("Client Package Name: %s", packageName.string());
4064 }
4065
4066 ret.append(", Conflicting Client Devices: {");
4067 for (auto& j : conflicting) {
4068 ret.appendFormat("%s, ", j.string());
4069 }
4070 ret.append("})");
4071 }
4072 if (hasAny) ret.append("\n");
4073 ret.append("]\n");
4074 return ret;
4075}
4076
4077CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
4078 const String8& key, const sp<BasicClient>& value, int32_t cost,
Emilian Peev8131a262017-02-01 12:33:43 +00004079 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00004080 int32_t state, int32_t oomScoreOffset) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004081
Steven Moreland89a2c5c2020-01-31 15:02:25 -08004082 bool isVendorClient = getCurrentServingCall() == BinderCallType::HWBINDER;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07004083 int32_t score_adj = isVendorClient ? kVendorClientScore : score;
4084 int32_t state_adj = isVendorClient ? kVendorClientState: state;
4085
Ruben Brunkcc776712015-02-17 20:18:47 -08004086 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00004087 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj, isVendorClient,
4088 oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08004089}
4090
4091CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00004092 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
4093 int32_t oomScoreOffset) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004094 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00004095 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00004096 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08004097}
4098
4099// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08004100// InjectionStatusListener
4101// ----------------------------------------------------------------------------
4102
4103void CameraService::InjectionStatusListener::addListener(
4104 const sp<ICameraInjectionCallback>& callback) {
4105 Mutex::Autolock lock(mListenerLock);
4106 if (mCameraInjectionCallback) return;
4107 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
4108 if (res == OK) {
4109 mCameraInjectionCallback = callback;
4110 }
4111}
4112
4113void CameraService::InjectionStatusListener::removeListener() {
4114 Mutex::Autolock lock(mListenerLock);
4115 if (mCameraInjectionCallback == nullptr) {
4116 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
4117 return;
4118 }
4119 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
4120 mCameraInjectionCallback = nullptr;
4121}
4122
4123void CameraService::InjectionStatusListener::notifyInjectionError(
Cliff Wud3a05312021-04-26 23:07:31 +08004124 String8 injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08004125 if (mCameraInjectionCallback == nullptr) {
4126 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
4127 return;
4128 }
Cliff Wud3a05312021-04-26 23:07:31 +08004129
4130 switch (err) {
4131 case -ENODEV:
4132 mCameraInjectionCallback->onInjectionError(
4133 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4134 ALOGE("No camera device with ID \"%s\" currently available!",
4135 injectedCamId.string());
4136 break;
4137 case -EBUSY:
4138 mCameraInjectionCallback->onInjectionError(
4139 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4140 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
4141 injectedCamId.string());
4142 break;
4143 case DEAD_OBJECT:
4144 mCameraInjectionCallback->onInjectionError(
4145 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4146 ALOGE("Camera ID \"%s\" object is dead!",
4147 injectedCamId.string());
4148 break;
4149 case INVALID_OPERATION:
4150 mCameraInjectionCallback->onInjectionError(
4151 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4152 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
4153 injectedCamId.string());
4154 break;
4155 case UNKNOWN_TRANSACTION:
4156 mCameraInjectionCallback->onInjectionError(
4157 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
4158 ALOGE("Camera ID \"%s\" method doesn't support!",
4159 injectedCamId.string());
4160 break;
4161 default:
4162 mCameraInjectionCallback->onInjectionError(
4163 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
4164 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
4165 strerror(-err), err, injectedCamId.string());
4166 }
Cliff Wud8cae102021-03-11 01:37:42 +08004167}
4168
4169void CameraService::InjectionStatusListener::binderDied(
4170 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08004171 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
4172 auto parent = mParent.promote();
4173 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08004174 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
4175 if (clientDescriptor != nullptr) {
4176 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
4177 baseClientPtr->stopInjection();
4178 }
Cliff Wu3b268182021-07-06 15:44:43 +08004179 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08004180 }
4181}
4182
4183// ----------------------------------------------------------------------------
4184// CameraInjectionSession
4185// ----------------------------------------------------------------------------
4186
4187binder::Status CameraService::CameraInjectionSession::stopInjection() {
4188 Mutex::Autolock lock(mInjectionSessionLock);
4189 auto parent = mParent.promote();
4190 if (parent == nullptr) {
4191 ALOGE("CameraInjectionSession: Parent is gone");
4192 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
4193 "Camera service encountered error");
4194 }
Cliff Wud3a05312021-04-26 23:07:31 +08004195
4196 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08004197 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
4198 if (clientDescriptor != nullptr) {
4199 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
4200 res = baseClientPtr->stopInjection();
4201 if (res != OK) {
4202 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
4203 " ret != NO_ERROR: %d", res);
4204 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
4205 "Camera session encountered error");
4206 }
4207 }
Cliff Wu3b268182021-07-06 15:44:43 +08004208 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08004209 return binder::Status::ok();
4210}
4211
4212// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07004213
4214static const int kDumpLockRetries = 50;
4215static const int kDumpLockSleep = 60000;
4216
4217static bool tryLock(Mutex& mutex)
4218{
4219 bool locked = false;
4220 for (int i = 0; i < kDumpLockRetries; ++i) {
4221 if (mutex.tryLock() == NO_ERROR) {
4222 locked = true;
4223 break;
4224 }
4225 usleep(kDumpLockSleep);
4226 }
4227 return locked;
4228}
4229
Rucha Katakwardf223072021-06-15 10:21:00 -07004230void CameraService::cacheDump() {
4231 if (mMemFd != -1) {
4232 const Vector<String16> args;
4233 ATRACE_CALL();
4234 // Acquiring service lock here will avoid the deadlock since
4235 // cacheDump will not be called during the second disconnect.
4236 Mutex::Autolock lock(mServiceLock);
4237
4238 Mutex::Autolock l(mCameraStatesLock);
4239 // Start collecting the info for open sessions and store it in temp file.
4240 for (const auto& state : mCameraStates) {
4241 String8 cameraId = state.first;
4242 auto clientDescriptor = mActiveClientManager.get(cameraId);
4243 if (clientDescriptor != nullptr) {
4244 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.string());
4245 // Log the current open session info before device is disconnected.
4246 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
4247 }
4248 }
4249 }
4250}
4251
Mathias Agopian65ab4712010-07-14 17:59:35 -07004252status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004253 ATRACE_CALL();
4254
Jayant Chowdhary5216b212019-07-17 09:26:23 -07004255 if (checkCallingPermission(sDumpPermission) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004256 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07004257 CameraThreadState::getCallingPid(),
4258 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004259 return NO_ERROR;
4260 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004261 bool locked = tryLock(mServiceLock);
4262 // failed to lock - CameraService is probably deadlocked
4263 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004264 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004265 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004266
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004267 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004268 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07004269
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004270 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004271 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08004272
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004273 if (locked) mServiceLock.unlock();
4274 return NO_ERROR;
4275 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004276 dprintf(fd, "\n== Service global info: ==\n\n");
4277 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004278 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07004279 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
4280 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004281 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
4282 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
4283 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004284 String8 activeClientString = mActiveClientManager.toString();
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004285 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
4286 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004287
4288 dumpEventLog(fd);
4289
4290 bool stateLocked = tryLock(mCameraStatesLock);
4291 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004292 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004293 }
4294
Emilian Peevbd8c5032018-02-14 23:05:40 +00004295 int argSize = args.size();
4296 for (int i = 0; i < argSize; i++) {
4297 if (args[i] == TagMonitor::kMonitorOption) {
4298 if (i + 1 < argSize) {
4299 mMonitorTags = String8(args[i + 1]);
4300 }
4301 break;
4302 }
4303 }
4304
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004305 for (auto& state : mCameraStates) {
4306 String8 cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004307
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004308 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004309
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004310 CameraParameters p = state.second->getShimParams();
4311 if (!p.isEmpty()) {
4312 dprintf(fd, " Camera1 API shim is using parameters:\n ");
4313 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004314 }
4315
4316 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08004317 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07004318 // log the current open session info
4319 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08004320 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07004321 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004322 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004323
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004324 }
4325
4326 if (stateLocked) mCameraStatesLock.unlock();
4327
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004328 if (locked) mServiceLock.unlock();
4329
Emilian Peevf53f66e2017-04-11 14:29:43 +01004330 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004331
4332 dprintf(fd, "\n== Vendor tags: ==\n\n");
4333
4334 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
4335 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00004336 sp<VendorTagDescriptorCache> cache =
4337 VendorTagDescriptorCache::getGlobalVendorTagCache();
4338 if (cache == NULL) {
4339 dprintf(fd, "No vendor tags.\n");
4340 } else {
4341 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
4342 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004343 } else {
4344 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
4345 }
4346
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004347 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004348 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004349 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004350
4351 // Process dump arguments, if any
4352 int n = args.size();
4353 String16 verboseOption("-v");
4354 String16 unreachableOption("--unreachable");
4355 for (int i = 0; i < n; i++) {
4356 if (args[i] == verboseOption) {
4357 // change logging level
4358 if (i + 1 >= n) continue;
4359 String8 levelStr(args[i+1]);
4360 int level = atoi(levelStr.string());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004361 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004362 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004363 } else if (args[i] == unreachableOption) {
4364 // Dump memory analysis
4365 // TODO - should limit be an argument parameter?
4366 UnreachableMemoryInfo info;
4367 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
4368 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004369 dprintf(fd, "\n== Unable to dump unreachable memory. "
4370 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004371 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004372 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004373 std::string s = info.ToString(/*log_contents*/ true);
4374 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004375 }
4376 }
4377 }
Rucha Katakwardf223072021-06-15 10:21:00 -07004378
4379 bool serviceLocked = tryLock(mServiceLock);
4380
4381 // Dump info from previous open sessions.
4382 // Reposition the offset to beginning of the file before reading
4383
4384 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
4385 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
4386 ssize_t size_read;
4387 char buf[4096];
4388 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
4389 // Read data from file to a small buffer and write it to fd.
4390 write(fd, buf, size_read);
4391 if (size_read == -1) {
4392 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
4393 break;
4394 }
4395 }
4396 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
4397 } else {
4398 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
4399 }
4400
4401 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004402 return NO_ERROR;
4403}
4404
Rucha Katakwardf223072021-06-15 10:21:00 -07004405void CameraService::dumpOpenSessionClientLogs(int fd,
4406 const Vector<String16>& args, const String8& cameraId) {
4407 auto clientDescriptor = mActiveClientManager.get(cameraId);
4408 dprintf(fd, " Device %s is open. Client instance dump:\n",
4409 cameraId.string());
4410 dprintf(fd, " Client priority score: %d state: %d\n",
4411 clientDescriptor->getPriority().getScore(),
4412 clientDescriptor->getPriority().getState());
4413 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
4414
4415 auto client = clientDescriptor->getValue();
4416 dprintf(fd, " Client package: %s\n",
4417 String8(client->getPackageName()).string());
4418
4419 client->dumpClient(fd, args);
4420}
4421
4422void CameraService::dumpClosedSessionClientLogs(int fd, const String8& cameraId) {
4423 dprintf(fd, " Device %s is closed, no client instance\n",
4424 cameraId.string());
4425}
4426
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004427void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004428 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004429
4430 Mutex::Autolock l(mLogLock);
4431 for (const auto& msg : mEventLog) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004432 dprintf(fd, " %s\n", msg.string());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004433 }
4434
4435 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004436 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004437 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004438 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004439 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004440 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004441}
4442
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004443void CameraService::cacheClientTagDumpIfNeeded(const char *cameraId, BasicClient* client) {
4444 Mutex::Autolock lock(mLogLock);
4445 if (!isClientWatchedLocked(client)) { return; }
4446
4447 std::vector<std::string> dumpVector;
4448 client->dumpWatchedEventsToVector(dumpVector);
4449
4450 if (dumpVector.empty()) { return; }
4451
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08004452 const String16 &packageName = client->getPackageName();
4453
4454 String8 packageName8 = String8(packageName);
4455 const char *printablePackageName = packageName8.lockBuffer(packageName.size());
4456
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004457 std::string dumpString;
4458 size_t i = dumpVector.size();
4459
4460 // Store the string in reverse order (latest last)
4461 while (i > 0) {
4462 i--;
4463 dumpString += cameraId;
4464 dumpString += ":";
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08004465 dumpString += printablePackageName;
4466 dumpString += " ";
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004467 dumpString += dumpVector[i]; // implicitly ends with '\n'
4468 }
4469
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08004470 packageName8.unlockBuffer();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004471 mWatchedClientsDumpCache[packageName] = dumpString;
4472}
4473
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004474void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004475 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004476 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
4477 if (mTorchClientMap[i] == who) {
4478 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004479 String8 cameraId = mTorchClientMap.keyAt(i);
4480 status_t res = mFlashlight->setTorchMode(cameraId, false);
4481 if (res) {
4482 ALOGE("%s: torch client died but couldn't turn off torch: "
4483 "%s (%d)", __FUNCTION__, strerror(-res), res);
4484 return;
4485 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004486 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004487 break;
4488 }
4489 }
4490}
4491
Ruben Brunkcc776712015-02-17 20:18:47 -08004492/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07004493
Igor Murashkin294d0ec2012-10-05 10:44:57 -07004494 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07004495 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
4496 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07004497 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08004498 // PID here is approximate and can be wrong.
Jayant Chowdhary12361932018-08-27 14:46:13 -07004499 logClientDied(CameraThreadState::getCallingPid(), String8("Binder died unexpectedly"));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004500
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004501 // check torch client
4502 handleTorchClientBinderDied(who);
4503
4504 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08004505 if(!evictClientIdByRemote(who)) {
4506 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07004507 return;
4508 }
4509
Ruben Brunkcc776712015-02-17 20:18:47 -08004510 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
4511 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07004512}
4513
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004514void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004515 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08004516}
4517
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004518void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
4519 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004520 // Do not lock mServiceLock here or can get into a deadlock from
4521 // connect() -> disconnect -> updateStatus
4522
4523 auto state = getCameraState(cameraId);
4524
4525 if (state == nullptr) {
4526 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
4527 cameraId.string());
4528 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07004529 }
4530
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004531 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
4532 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
4533 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
4534 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
4535 return;
4536 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004537
4538 // Collect the logical cameras without holding mStatusLock in updateStatus
4539 // as that can lead to a deadlock(b/162192331).
4540 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08004541 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08004542 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07004543 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004544 &logicalCameraIds]
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004545 (const String8& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004546
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004547 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004548 // Update torch status if it has a flash unit.
4549 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004550 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004551 if (getTorchStatusLocked(cameraId, &torchStatus) !=
4552 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004553 TorchModeStatus newTorchStatus =
4554 status == StatusInternal::PRESENT ?
4555 TorchModeStatus::AVAILABLE_OFF :
4556 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004557 if (torchStatus != newTorchStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07004558 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004559 }
4560 }
Ruben Brunkcc776712015-02-17 20:18:47 -08004561 }
4562
4563 Mutex::Autolock lock(mStatusListenerLock);
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004564 notifyPhysicalCameraStatusLocked(mapToInterface(status), String16(cameraId),
4565 logicalCameraIds, deviceKind);
Shuzhen Wang43858162020-01-10 13:42:15 -08004566
Ruben Brunkcc776712015-02-17 20:18:47 -08004567 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07004568 bool isVendorListener = listener->isVendorListener();
4569 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
4570 listener->getListenerPid(), listener->getListenerUid()) ||
Shuzhen Wangb8259792021-05-27 09:27:06 -07004571 isVendorListener) {
4572 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07004573 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08004574 continue;
4575 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07004576 listener->getListener()->onStatusChanged(mapToInterface(status),
Emilian Peev53722fa2019-02-22 17:47:20 -08004577 String16(cameraId));
Ruben Brunkcc776712015-02-17 20:18:47 -08004578 }
4579 });
Igor Murashkincba2c162013-03-20 15:56:31 -07004580}
4581
Shuzhen Wang695044d2020-03-06 09:02:23 -08004582void CameraService::updateOpenCloseStatus(const String8& cameraId, bool open,
4583 const String16& clientPackageName) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07004584 auto state = getCameraState(cameraId);
4585 if (state == nullptr) {
4586 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
4587 cameraId.string());
4588 return;
4589 }
4590 if (open) {
4591 state->setClientPackage(String8(clientPackageName));
4592 } else {
4593 state->setClientPackage(String8::empty());
4594 }
4595
Shuzhen Wang695044d2020-03-06 09:02:23 -08004596 Mutex::Autolock lock(mStatusListenerLock);
4597
4598 for (const auto& it : mListenerList) {
4599 if (!it->isOpenCloseCallbackAllowed()) {
4600 continue;
4601 }
4602
4603 binder::Status ret;
4604 String16 cameraId64(cameraId);
4605 if (open) {
4606 ret = it->getListener()->onCameraOpened(cameraId64, clientPackageName);
4607 } else {
4608 ret = it->getListener()->onCameraClosed(cameraId64);
4609 }
4610 if (!ret.isOk()) {
4611 ALOGE("%s: Failed to trigger onCameraOpened/onCameraClosed callback: %d", __FUNCTION__,
4612 ret.exceptionCode());
4613 }
4614 }
4615}
4616
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004617template<class Func>
4618void CameraService::CameraState::updateStatus(StatusInternal status,
4619 const String8& cameraId,
4620 std::initializer_list<StatusInternal> rejectSourceStates,
4621 Func onStatusUpdatedLocked) {
4622 Mutex::Autolock lock(mStatusLock);
4623 StatusInternal oldStatus = mStatus;
4624 mStatus = status;
4625
4626 if (oldStatus == status) {
4627 return;
4628 }
4629
4630 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
4631 cameraId.string(), oldStatus, status);
4632
4633 if (oldStatus == StatusInternal::NOT_PRESENT &&
4634 (status != StatusInternal::PRESENT &&
4635 status != StatusInternal::ENUMERATING)) {
4636
4637 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
4638 __FUNCTION__);
4639 mStatus = oldStatus;
4640 return;
4641 }
4642
4643 /**
4644 * Sometimes we want to conditionally do a transition.
4645 * For example if a client disconnects, we want to go to PRESENT
4646 * only if we weren't already in NOT_PRESENT or ENUMERATING.
4647 */
4648 for (auto& rejectStatus : rejectSourceStates) {
4649 if (oldStatus == rejectStatus) {
4650 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
4651 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
4652 mStatus = oldStatus;
4653 return;
4654 }
4655 }
4656
4657 onStatusUpdatedLocked(cameraId, status);
4658}
4659
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004660status_t CameraService::getTorchStatusLocked(
4661 const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004662 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004663 if (!status) {
4664 return BAD_VALUE;
4665 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004666 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
4667 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004668 // invalid camera ID or the camera doesn't have a flash unit
4669 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004670 }
4671
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004672 *status = mTorchStatusMap.valueAt(index);
4673 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004674}
4675
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004676status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004677 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004678 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
4679 if (index == NAME_NOT_FOUND) {
4680 return BAD_VALUE;
4681 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004682 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004683
4684 return OK;
4685}
4686
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004687std::list<String16> CameraService::getLogicalCameras(
4688 const String8& physicalCameraId) {
4689 std::list<String16> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08004690 Mutex::Autolock lock(mCameraStatesLock);
4691 for (const auto& state : mCameraStates) {
4692 std::vector<std::string> physicalCameraIds;
4693 if (!mCameraProviderManager->isLogicalCamera(state.first.c_str(), &physicalCameraIds)) {
4694 // This is not a logical multi-camera.
4695 continue;
4696 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004697 if (std::find(physicalCameraIds.begin(), physicalCameraIds.end(), physicalCameraId.c_str())
Shuzhen Wang43858162020-01-10 13:42:15 -08004698 == physicalCameraIds.end()) {
4699 // cameraId is not a physical camera of this logical multi-camera.
4700 continue;
4701 }
4702
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004703 retList.emplace_back(String16(state.first));
4704 }
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