blob: 97ec5d1106dc7e3da946f412edb15b4b0dee2c0e [file] [log] [blame]
Mathias Agopian65ab4712010-07-14 17:59:35 -07001/*
Ruben Brunkd1176ef2014-02-21 10:51:38 -08002 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Mathias Agopian65ab4712010-07-14 17:59:35 -070016
17#define LOG_TAG "CameraService"
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -070018#define ATRACE_TAG ATRACE_TAG_CAMERA
Iliyan Malchev8951a972011-04-14 16:55:59 -070019//#define LOG_NDEBUG 0
Mathias Agopian65ab4712010-07-14 17:59:35 -070020
Ruben Brunkcc776712015-02-17 20:18:47 -080021#include <algorithm>
22#include <climits>
Mathias Agopian65ab4712010-07-14 17:59:35 -070023#include <stdio.h>
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -080024#include <cstdlib>
Ruben Brunkcc776712015-02-17 20:18:47 -080025#include <cstring>
26#include <ctime>
27#include <string>
Mathias Agopian65ab4712010-07-14 17:59:35 -070028#include <sys/types.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080029#include <inttypes.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070030#include <pthread.h>
Avichal Rakesh84147132021-11-11 17:47:11 -080031#include <poll.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070032
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080033#include <android/hardware/ICamera.h>
34#include <android/hardware/ICameraClient.h>
35
Alex Deymo9c2a2c22016-08-25 11:59:14 -070036#include <android-base/macros.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080037#include <android-base/parseint.h>
Jayant Chowdharyb61526c2019-05-13 19:37:42 -070038#include <android-base/stringprintf.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080039#include <binder/ActivityManager.h>
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -080040#include <binder/AppOpsManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070041#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070042#include <binder/MemoryBase.h>
43#include <binder/MemoryHeapBase.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080044#include <binder/PermissionController.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080045#include <binder/IResultReceiver.h>
Steven Moreland89a2c5c2020-01-31 15:02:25 -080046#include <binderthreadstate/CallerUtils.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070047#include <cutils/atomic.h>
Nipun Kwatrab5ca4612010-09-11 19:31:10 -070048#include <cutils/properties.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080049#include <cutils/misc.h>
Mathias Agopiandf712ea2012-02-25 18:48:35 -080050#include <gui/Surface.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070051#include <hardware/hardware.h>
Jayant Chowdharybe543d42018-08-15 13:16:14 -070052#include "hidl/HidlCameraService.h"
53#include <hidl/HidlTransportSupport.h>
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -080054#include <hwbinder/IPCThreadState.h>
Eino-Ville Talvalad89821e2016-04-20 11:23:50 -070055#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070056#include <media/AudioSystem.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080057#include <media/IMediaHTTPService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070058#include <media/mediaplayer.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070059#include <mediautils/BatteryNotifier.h>
Steven Moreland886d7322021-04-02 04:19:45 +000060#include <processinfo/ProcessInfoService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070061#include <utils/Errors.h>
62#include <utils/Log.h>
63#include <utils/String16.h>
Svet Ganov94ec46f2018-06-08 15:03:46 -070064#include <utils/SystemClock.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080065#include <utils/Trace.h>
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080066#include <utils/CallStack.h>
Chien-Yu Chen98a668f2015-12-18 14:10:33 -080067#include <private/android_filesystem_config.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080068#include <system/camera_vendor_tags.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070069#include <system/camera_metadata.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080070
Ruben Brunkb2119af2014-05-09 19:57:56 -070071#include <system/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070072
73#include "CameraService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070074#include "api1/Camera2Client.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070075#include "api2/CameraDeviceClient.h"
Igor Murashkinff3e31d2013-10-23 16:40:06 -070076#include "utils/CameraTraces.h"
Emilian Peevbd8c5032018-02-14 23:05:40 +000077#include "utils/TagMonitor.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070078#include "utils/CameraThreadState.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070079#include "utils/CameraServiceProxyWrapper.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070080
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080081namespace {
82 const char* kPermissionServiceName = "permission";
83}; // namespace anonymous
84
Mathias Agopian65ab4712010-07-14 17:59:35 -070085namespace android {
86
Jayant Chowdharyb61526c2019-05-13 19:37:42 -070087using base::StringPrintf;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080088using binder::Status;
Austin Borgerea931242021-12-13 23:10:41 +000089using namespace camera3;
Jayant Chowdharybe543d42018-08-15 13:16:14 -070090using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -080091using hardware::ICamera;
92using hardware::ICameraClient;
93using hardware::ICameraServiceListener;
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);
368 if (res != OK) {
369 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
370 return;
371 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000372 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
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 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000378 std::vector<std::string> physicalCameraIds;
379 mCameraProviderManager->isLogicalCamera(cameraId, &physicalCameraIds);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100380 std::set<String8> conflicting;
381 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
382 conflicting.emplace(String8(cost.conflictingDevices[i].c_str()));
383 }
384
385 {
386 Mutex::Autolock lock(mCameraStatesLock);
387 mCameraStates.emplace(id, std::make_shared<CameraState>(id, cost.resourceCost,
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000388 conflicting, deviceKind, physicalCameraIds));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100389 }
390
391 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100392 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100393 mTorchStatusMap.add(id, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800394
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700395 broadcastTorchModeStatus(id, TorchModeStatus::AVAILABLE_OFF, deviceKind);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100396 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800397
398 updateCameraNumAndIds();
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100399 logDeviceAdded(id, "Device added");
400}
401
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100402void CameraService::removeStates(const String8 id) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800403 updateCameraNumAndIds();
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100404 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100405 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100406 mTorchStatusMap.removeItem(id);
407 }
408
409 {
410 Mutex::Autolock lock(mCameraStatesLock);
411 mCameraStates.erase(id);
412 }
413}
414
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800415void CameraService::onDeviceStatusChanged(const String8& id,
416 CameraDeviceStatus newHalStatus) {
417 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
418 id.string(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700419
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800420 StatusInternal newStatus = mapToInternal(newHalStatus);
421
Ruben Brunkcc776712015-02-17 20:18:47 -0800422 std::shared_ptr<CameraState> state = getCameraState(id);
423
424 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700425 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100426 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700427 __FUNCTION__, id.string());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100428
429 // First add as absent to make sure clients are notified below
430 addStates(id);
431
432 updateStatus(newStatus, id);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700433 } else {
434 ALOGE("%s: Bad camera ID %s", __FUNCTION__, id.string());
435 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700436 return;
437 }
438
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800439 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800440
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800441 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800442 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700443 return;
444 }
445
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800446 if (newStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700447 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
448 newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800449
450 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
451 // to this device until the status changes
452 updateStatus(StatusInternal::NOT_PRESENT, id);
453
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800454 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700455 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800456 // Don't do this in updateStatus to avoid deadlock over mServiceLock
457 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700458
Ruben Brunkcc776712015-02-17 20:18:47 -0800459 // Remove cached shim parameters
460 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700461
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800462 // Remove online as well as offline client from the list of active clients,
463 // if they are present
464 clientToDisconnectOnline = removeClientLocked(id);
465 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + id);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700466 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800467
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800468 disconnectClient(id, clientToDisconnectOnline);
469 disconnectClient(kOfflineDevice + id, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700470
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100471 removeStates(id);
Ruben Brunkcc776712015-02-17 20:18:47 -0800472 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800473 if (oldStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700474 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
475 newStatus));
476 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800477 updateStatus(newStatus, id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700478 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800479}
Igor Murashkincba2c162013-03-20 15:56:31 -0700480
Shuzhen Wang43858162020-01-10 13:42:15 -0800481void CameraService::onDeviceStatusChanged(const String8& id,
482 const String8& physicalId,
483 CameraDeviceStatus newHalStatus) {
484 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
485 __FUNCTION__, id.string(), physicalId.string(), newHalStatus);
486
487 StatusInternal newStatus = mapToInternal(newHalStatus);
488
489 std::shared_ptr<CameraState> state = getCameraState(id);
490
491 if (state == nullptr) {
492 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
493 __FUNCTION__, id.string(), physicalId.string());
494 return;
495 }
496
497 StatusInternal logicalCameraStatus = state->getStatus();
498 if (logicalCameraStatus != StatusInternal::PRESENT &&
499 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
500 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
501 __FUNCTION__, physicalId.string(), newHalStatus, logicalCameraStatus);
502 return;
503 }
504
505 bool updated = false;
506 if (newStatus == StatusInternal::PRESENT) {
507 updated = state->removeUnavailablePhysicalId(physicalId);
508 } else {
509 updated = state->addUnavailablePhysicalId(physicalId);
510 }
511
512 if (updated) {
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800513 String8 idCombo = id + " : " + physicalId;
514 if (newStatus == StatusInternal::PRESENT) {
515 logDeviceAdded(idCombo,
516 String8::format("Device status changed to %d", newStatus));
517 } else {
518 logDeviceRemoved(idCombo,
519 String8::format("Device status changed to %d", newStatus));
520 }
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700521 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
522 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
523 if (getSystemCameraKind(id, &deviceKind) != OK) {
524 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.string());
525 return;
526 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800527 String16 id16(id), physicalId16(physicalId);
528 Mutex::Autolock lock(mStatusListenerLock);
529 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700530 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
531 listener->getListenerPid(), listener->getListenerUid())) {
532 ALOGV("Skipping discovery callback for system-only camera device %s",
533 id.c_str());
534 continue;
535 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800536 listener->getListener()->onPhysicalCameraStatusChanged(mapToInterface(newStatus),
537 id16, physicalId16);
538 }
539 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700540}
541
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800542void CameraService::disconnectClient(const String8& id, sp<BasicClient> clientToDisconnect) {
543 if (clientToDisconnect.get() != nullptr) {
544 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
545 __FUNCTION__, id.string());
546 // Notify the client of disconnection
547 clientToDisconnect->notifyError(
548 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
549 CaptureResultExtras{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800550 clientToDisconnect->disconnect();
551 }
552}
553
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800554void CameraService::onTorchStatusChanged(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800555 TorchModeStatus newStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700556 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
557 status_t res = getSystemCameraKind(cameraId, &systemCameraKind);
558 if (res != OK) {
559 ALOGE("%s: Could not get system camera kind for camera id %s", __FUNCTION__,
560 cameraId.string());
561 return;
562 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800563 Mutex::Autolock al(mTorchStatusMutex);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700564 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800565}
566
Jayant Chowdhary46ef0f52021-10-05 14:36:13 -0700567
568void CameraService::onTorchStatusChanged(const String8& cameraId,
569 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
570 Mutex::Autolock al(mTorchStatusMutex);
571 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
572}
573
Rucha Katakwar38284522021-11-10 11:25:21 -0800574void CameraService::broadcastTorchStrengthLevel(const String8& cameraId,
575 int32_t newStrengthLevel) {
576 Mutex::Autolock lock(mStatusListenerLock);
577 for (auto& i : mListenerList) {
578 i->getListener()->onTorchStrengthLevelChanged(String16{cameraId},
579 newStrengthLevel);
580 }
581}
582
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800583void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700584 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800585 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
586 __FUNCTION__, cameraId.string(), newStatus);
587
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800588 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800589 status_t res = getTorchStatusLocked(cameraId, &status);
590 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700591 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
592 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800593 return;
594 }
595 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800596 return;
597 }
598
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800599 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800600 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800601 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
602 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800603 return;
604 }
605
Ruben Brunkcc776712015-02-17 20:18:47 -0800606 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700607 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700608 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700609 auto iter = mTorchUidMap.find(cameraId);
610 if (iter != mTorchUidMap.end()) {
611 int oldUid = iter->second.second;
612 int newUid = iter->second.first;
613 BatteryNotifier& notifier(BatteryNotifier::getInstance());
614 if (oldUid != newUid) {
615 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800616 if (status == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700617 notifier.noteFlashlightOff(cameraId, oldUid);
618 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800619 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700620 notifier.noteFlashlightOn(cameraId, newUid);
621 }
622 iter->second.second = newUid;
623 } else {
624 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800625 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700626 notifier.noteFlashlightOn(cameraId, oldUid);
627 } else {
628 notifier.noteFlashlightOff(cameraId, oldUid);
629 }
630 }
631 }
632 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700633 broadcastTorchModeStatus(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800634}
635
Jayant Chowdharyc3198c32021-07-28 20:59:14 +0000636static bool hasPermissionsForSystemCamera(int callingPid, int callingUid,
637 bool logPermissionFailure = false) {
638 return checkPermission(sSystemCameraPermission, callingPid, callingUid,
639 logPermissionFailure) &&
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700640 checkPermission(sCameraPermission, callingPid, callingUid);
641}
642
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800643Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700644 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100645 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700646 bool hasSystemCameraPermissions =
647 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
648 CameraThreadState::getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700649 switch (type) {
650 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700651 if (hasSystemCameraPermissions) {
652 *numCameras = static_cast<int>(mNormalDeviceIds.size());
653 } else {
654 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
655 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800656 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700657 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700658 if (hasSystemCameraPermissions) {
659 *numCameras = mNumberOfCameras;
660 } else {
661 *numCameras = mNumberOfCamerasWithoutSystemCamera;
662 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800663 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700664 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800665 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700666 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800667 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
668 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700669 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800670 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700671}
672
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800673Status CameraService::getCameraInfo(int cameraId,
674 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700675 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100676 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700677 std::string cameraIdStr = cameraIdIntToStrLocked(cameraId);
678 if (shouldRejectSystemCameraConnection(String8(cameraIdStr.c_str()))) {
679 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
680 "characteristics for system only device %s: ", cameraIdStr.c_str());
681 }
Emilian Peevaee727d2017-05-04 16:35:48 +0100682
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800683 if (!mInitialized) {
Rucha Katakward9ea6452021-05-06 11:57:16 -0700684 logServiceError(String8::format("Camera subsystem is not available"),ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800685 return STATUS_ERROR(ERROR_DISCONNECTED,
686 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -0700687 }
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700688 bool hasSystemCameraPermissions =
689 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
690 CameraThreadState::getCallingUid());
691 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
692 if (hasSystemCameraPermissions) {
693 cameraIdBound = mNumberOfCameras;
694 }
695 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800696 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
697 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700698 }
699
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800700 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800701 status_t err = mCameraProviderManager->getCameraInfo(
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700702 cameraIdStr.c_str(), cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100703 if (err != OK) {
704 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
705 "Error retrieving camera info from device %d: %s (%d)", cameraId,
706 strerror(-err), err);
Rucha Katakward9ea6452021-05-06 11:57:16 -0700707 logServiceError(String8::format("Error retrieving camera info from device %d",cameraId),
708 ERROR_INVALID_OPERATION);
Ruben Brunkcc776712015-02-17 20:18:47 -0800709 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100710
Ruben Brunkcc776712015-02-17 20:18:47 -0800711 return ret;
712}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700713
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800714std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700715 const std::vector<std::string> *deviceIds = &mNormalDeviceIdsWithoutSystemCamera;
716 auto callingPid = CameraThreadState::getCallingPid();
717 auto callingUid = CameraThreadState::getCallingUid();
Jayant Chowdharyc3198c32021-07-28 20:59:14 +0000718 if (checkPermission(sSystemCameraPermission, callingPid, callingUid,
719 /*logPermissionFailure*/false) || getpid() == callingPid) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700720 deviceIds = &mNormalDeviceIds;
721 }
722 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(deviceIds->size())) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800723 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700724 __FUNCTION__, cameraIdInt, deviceIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800725 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800726 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800727
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700728 return (*deviceIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800729}
730
731String8 CameraService::cameraIdIntToStr(int cameraIdInt) {
732 Mutex::Autolock lock(mServiceLock);
733 return String8(cameraIdIntToStrLocked(cameraIdInt).c_str());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800734}
735
736Status CameraService::getCameraCharacteristics(const String16& cameraId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700737 int targetSdkVersion, CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700738 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700739 if (!cameraInfo) {
740 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800741 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -0700742 }
743
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800744 if (!mInitialized) {
745 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Rucha Katakward9ea6452021-05-06 11:57:16 -0700746 logServiceError(String8::format("Camera subsystem is not available"),ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800747 return STATUS_ERROR(ERROR_DISCONNECTED,
748 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -0700749 }
750
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700751 if (shouldRejectSystemCameraConnection(String8(cameraId))) {
752 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
753 "characteristics for system only device %s: ", String8(cameraId).string());
754 }
755
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800756 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800757
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700758
759 std::string cameraIdStr = String8(cameraId).string();
760 bool overrideForPerfClass =
761 SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
762 cameraIdStr, targetSdkVersion);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100763 status_t res = mCameraProviderManager->getCameraCharacteristics(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700764 cameraIdStr, overrideForPerfClass, cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100765 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700766 if (res == NAME_NOT_FOUND) {
767 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
768 "characteristics for unknown device %s: %s (%d)", String8(cameraId).string(),
769 strerror(-res), res);
770 } else {
Rucha Katakward9ea6452021-05-06 11:57:16 -0700771 logServiceError(String8::format("Unable to retrieve camera characteristics for "
772 "device %s.", String8(cameraId).string()),ERROR_INVALID_OPERATION);
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700773 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
774 "characteristics for device %s: %s (%d)", String8(cameraId).string(),
775 strerror(-res), res);
776 }
Ruben Brunkb2119af2014-05-09 19:57:56 -0700777 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700778 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
779 if (getSystemCameraKind(String8(cameraId), &deviceKind) != OK) {
780 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, String8(cameraId).string());
781 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera kind "
782 "for device %s", String8(cameraId).string());
783 }
Jayant Chowdhary12361932018-08-27 14:46:13 -0700784 int callingPid = CameraThreadState::getCallingPid();
785 int callingUid = CameraThreadState::getCallingUid();
Emilian Peeve20c6372018-08-14 18:45:53 +0100786 std::vector<int32_t> tagsRemoved;
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700787 // If it's not calling from cameraserver, check the permission only if
788 // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
789 // it would've already been checked in shouldRejectSystemCameraConnection.
Emilian Peeve20c6372018-08-14 18:45:53 +0100790 if ((callingPid != getpid()) &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700791 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700792 !checkPermission(sCameraPermission, callingPid, callingUid)) {
Emilian Peeve20c6372018-08-14 18:45:53 +0100793 res = cameraInfo->removePermissionEntries(
794 mCameraProviderManager->getProviderTagIdLocked(String8(cameraId).string()),
795 &tagsRemoved);
796 if (res != OK) {
797 cameraInfo->clear();
798 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
799 " characteristics needing camera permission for device %s: %s (%d)",
800 String8(cameraId).string(), strerror(-res), res);
801 }
802 }
803
804 if (!tagsRemoved.empty()) {
805 res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
806 tagsRemoved.data(), tagsRemoved.size());
807 if (res != OK) {
808 cameraInfo->clear();
809 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
810 "keys needing permission for device %s: %s (%d)", String8(cameraId).string(),
811 strerror(-res), res);
812 }
813 }
814
Zhijun He2b59be82013-09-25 10:14:30 -0700815 return ret;
816}
817
Rucha Katakwar38284522021-11-10 11:25:21 -0800818Status CameraService::getTorchStrengthLevel(const String16& cameraId,
819 int32_t* torchStrength) {
820 ATRACE_CALL();
821 Mutex::Autolock l(mServiceLock);
822 if (!mInitialized) {
823 ALOGE("%s: Camera HAL couldn't be initialized.", __FUNCTION__);
824 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera HAL couldn't be initialized.");
825 }
826
827 if(torchStrength == NULL) {
828 ALOGE("%s: strength level must not be null.", __FUNCTION__);
829 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Strength level should not be null.");
830 }
831
832 status_t res = mCameraProviderManager->getTorchStrengthLevel(String8(cameraId).string(),
833 torchStrength);
834 if (res != OK) {
835 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve torch "
836 "strength level for device %s: %s (%d)", String8(cameraId).string(),
837 strerror(-res), res);
838 }
839 ALOGI("%s: Torch strength level is: %d", __FUNCTION__, *torchStrength);
840 return Status::ok();
841}
842
Ruben Brunkcc776712015-02-17 20:18:47 -0800843String8 CameraService::getFormattedCurrentTime() {
844 time_t now = time(nullptr);
845 char formattedTime[64];
846 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
847 return String8(formattedTime);
848}
849
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800850Status CameraService::getCameraVendorTagDescriptor(
851 /*out*/
852 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700853 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800854 if (!mInitialized) {
855 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800856 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800857 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -0800858 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
859 if (globalDescriptor != nullptr) {
860 *desc = *(globalDescriptor.get());
861 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800862 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800863}
864
Emilian Peev71c73a22017-03-21 16:35:51 +0000865Status CameraService::getCameraVendorTagCache(
866 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
867 ATRACE_CALL();
868 if (!mInitialized) {
869 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
870 return STATUS_ERROR(ERROR_DISCONNECTED,
871 "Camera subsystem not available");
872 }
873 sp<VendorTagDescriptorCache> globalCache =
874 VendorTagDescriptorCache::getGlobalVendorTagCache();
875 if (globalCache != nullptr) {
876 *cache = *(globalCache.get());
877 }
878 return Status::ok();
879}
880
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -0700881void CameraService::clearCachedVariables() {
882 BasicClient::BasicClient::sCameraService = nullptr;
883}
884
Emilian Peevb91f1802021-03-23 14:50:28 -0700885int CameraService::getDeviceVersion(const String8& cameraId, int* facing, int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700886 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800887
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800888 int deviceVersion = 0;
889
Emilian Peevf53f66e2017-04-11 14:29:43 +0100890 status_t res;
891 hardware::hidl_version maxVersion{0,0};
892 res = mCameraProviderManager->getHighestSupportedVersion(cameraId.string(),
893 &maxVersion);
894 if (res != OK) return -1;
895 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800896
Emilian Peevf53f66e2017-04-11 14:29:43 +0100897 hardware::CameraInfo info;
898 if (facing) {
899 res = mCameraProviderManager->getCameraInfo(cameraId.string(), &info);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -0800900 if (res != OK) return -1;
Emilian Peevf53f66e2017-04-11 14:29:43 +0100901 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -0700902 if (orientation) {
903 *orientation = info.orientation;
904 }
Igor Murashkin634a5152013-02-20 17:15:11 -0800905 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100906
Igor Murashkin634a5152013-02-20 17:15:11 -0800907 return deviceVersion;
908}
909
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800910Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700911 switch(err) {
912 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800913 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800914 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800915 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
916 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800917 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800918 return STATUS_ERROR(ERROR_DISCONNECTED,
919 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700920 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800921 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
922 "Camera HAL encountered error %d: %s",
923 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700924 }
Igor Murashkinbfc99152013-02-27 12:55:20 -0800925}
926
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800927Status CameraService::makeClient(const sp<CameraService>& cameraService,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800928 const sp<IInterface>& cameraCb, const String16& packageName,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700929 const std::optional<String16>& featureId, const String8& cameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -0700930 int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700931 int servicePid, int deviceVersion, apiLevel effectiveApiLevel, bool overrideForPerfClass,
Ruben Brunkcc776712015-02-17 20:18:47 -0800932 /*out*/sp<BasicClient>* client) {
933
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700934 // Create CameraClient based on device version reported by the HAL.
935 switch(deviceVersion) {
936 case CAMERA_DEVICE_API_VERSION_1_0:
937 ALOGE("Camera using old HAL version: %d", deviceVersion);
938 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
939 "Camera device \"%s\" HAL version %d no longer supported",
940 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800941 break;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700942 case CAMERA_DEVICE_API_VERSION_3_0:
943 case CAMERA_DEVICE_API_VERSION_3_1:
944 case CAMERA_DEVICE_API_VERSION_3_2:
945 case CAMERA_DEVICE_API_VERSION_3_3:
946 case CAMERA_DEVICE_API_VERSION_3_4:
947 case CAMERA_DEVICE_API_VERSION_3_5:
948 case CAMERA_DEVICE_API_VERSION_3_6:
Shuzhen Wang83bff122020-11-20 15:51:39 -0800949 case CAMERA_DEVICE_API_VERSION_3_7:
Shuzhen Wang90708ea2021-11-04 11:40:49 -0700950 case CAMERA_DEVICE_API_VERSION_3_8:
Ruben Brunkcc776712015-02-17 20:18:47 -0800951 if (effectiveApiLevel == API_1) { // Camera1 API route
952 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800953 *client = new Camera2Client(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800954 cameraId, api1CameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -0700955 facing, sensorOrientation, clientPid, clientUid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700956 servicePid, overrideForPerfClass);
Ruben Brunkcc776712015-02-17 20:18:47 -0800957 } else { // Camera2 API route
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800958 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
959 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800960 *client = new CameraDeviceClient(cameraService, tmp, packageName, featureId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700961 cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid,
962 overrideForPerfClass);
Ruben Brunkcc776712015-02-17 20:18:47 -0800963 }
964 break;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700965 default:
Ruben Brunkcc776712015-02-17 20:18:47 -0800966 // Should not be reachable
967 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800968 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800969 "Camera device \"%s\" has unknown HAL version %d",
970 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800971 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800972 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800973}
974
Ruben Brunk6267b532015-04-30 17:44:07 -0700975String8 CameraService::toString(std::set<userid_t> intSet) {
976 String8 s("");
977 bool first = true;
978 for (userid_t i : intSet) {
979 if (first) {
980 s.appendFormat("%d", i);
981 first = false;
982 } else {
983 s.appendFormat(", %d", i);
984 }
985 }
986 return s;
987}
988
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800989int32_t CameraService::mapToInterface(TorchModeStatus status) {
990 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
991 switch (status) {
992 case TorchModeStatus::NOT_AVAILABLE:
993 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
994 break;
995 case TorchModeStatus::AVAILABLE_OFF:
996 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
997 break;
998 case TorchModeStatus::AVAILABLE_ON:
999 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
1000 break;
1001 default:
1002 ALOGW("Unknown new flash status: %d", status);
1003 }
1004 return serviceStatus;
1005}
1006
1007CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
1008 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
1009 switch (status) {
1010 case CameraDeviceStatus::NOT_PRESENT:
1011 serviceStatus = StatusInternal::NOT_PRESENT;
1012 break;
1013 case CameraDeviceStatus::PRESENT:
1014 serviceStatus = StatusInternal::PRESENT;
1015 break;
1016 case CameraDeviceStatus::ENUMERATING:
1017 serviceStatus = StatusInternal::ENUMERATING;
1018 break;
1019 default:
1020 ALOGW("Unknown new HAL device status: %d", status);
1021 }
1022 return serviceStatus;
1023}
1024
1025int32_t CameraService::mapToInterface(StatusInternal status) {
1026 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1027 switch (status) {
1028 case StatusInternal::NOT_PRESENT:
1029 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1030 break;
1031 case StatusInternal::PRESENT:
1032 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
1033 break;
1034 case StatusInternal::ENUMERATING:
1035 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
1036 break;
1037 case StatusInternal::NOT_AVAILABLE:
1038 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
1039 break;
1040 case StatusInternal::UNKNOWN:
1041 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
1042 break;
1043 default:
1044 ALOGW("Unknown new internal device status: %d", status);
1045 }
1046 return serviceStatus;
1047}
1048
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001049Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001050 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -07001051
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001052 String16 internalPackageName("cameraserver");
Ruben Brunkcc776712015-02-17 20:18:47 -08001053 String8 id = String8::format("%d", cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001054 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001055 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001056 if (!(ret = connectHelper<ICameraClient,Client>(
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001057 sp<ICameraClient>{nullptr}, id, cameraId,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001058 internalPackageName, {}, uid, USE_CALLING_PID,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001059 API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0,
1060 /*targetSdkVersion*/ __ANDROID_API_FUTURE__, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001061 ).isOk()) {
1062 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
Ruben Brunkb2119af2014-05-09 19:57:56 -07001063 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001064 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001065}
1066
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001067Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -07001068 /*out*/
1069 CameraParameters* parameters) {
1070
1071 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1072
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001073 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001074
1075 if (parameters == NULL) {
1076 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001077 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001078 }
1079
Ruben Brunkcc776712015-02-17 20:18:47 -08001080 String8 id = String8::format("%d", cameraId);
1081
1082 // Check if we already have parameters
1083 {
1084 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001085 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001086 auto cameraState = getCameraState(id);
1087 if (cameraState == nullptr) {
1088 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001089 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1090 "Invalid camera ID: %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001091 }
1092 CameraParameters p = cameraState->getShimParams();
1093 if (!p.isEmpty()) {
1094 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001095 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001096 }
1097 }
1098
Jayant Chowdhary12361932018-08-27 14:46:13 -07001099 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001100 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001101 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001102 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001103 // Error already logged by callee
1104 return ret;
1105 }
1106
1107 // Check for parameters again
1108 {
1109 // Scope for service lock
1110 Mutex::Autolock lock(mServiceLock);
1111 auto cameraState = getCameraState(id);
1112 if (cameraState == nullptr) {
1113 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001114 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1115 "Invalid camera ID: %s", id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001116 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001117 CameraParameters p = cameraState->getShimParams();
1118 if (!p.isEmpty()) {
1119 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001120 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001121 }
1122 }
1123
Ruben Brunkcc776712015-02-17 20:18:47 -08001124 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1125 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001126 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001127}
1128
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001129// Can camera service trust the caller based on the calling UID?
1130static bool isTrustedCallingUid(uid_t uid) {
1131 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001132 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001133 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001134 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001135 return true;
1136 default:
1137 return false;
1138 }
1139}
1140
Nicholas Sauera3620332019-04-03 14:05:17 -07001141static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1142 PermissionController pc;
1143 uid = pc.getPackageUid(packageName, 0);
1144 if (uid <= 0) {
1145 ALOGE("Unknown package: '%s'", String8(packageName).string());
1146 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
1147 return BAD_VALUE;
1148 }
1149
1150 if (userId < 0) {
1151 ALOGE("Invalid user: %d", userId);
1152 dprintf(err, "Invalid user: %d\n", userId);
1153 return BAD_VALUE;
1154 }
1155
1156 uid = multiuser_get_uid(userId, uid);
1157 return NO_ERROR;
1158}
1159
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001160Status CameraService::validateConnectLocked(const String8& cameraId,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001161 const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
1162 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001163
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001164#ifdef __BRILLO__
1165 UNUSED(clientName8);
1166 UNUSED(clientUid);
1167 UNUSED(clientPid);
1168 UNUSED(originalClientPid);
1169#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001170 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1171 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001172 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001173 return allowed;
1174 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001175#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001176
Jayant Chowdhary12361932018-08-27 14:46:13 -07001177 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001178
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001179 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001180 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1181 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001182 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1183 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001184 }
1185
Ruben Brunkcc776712015-02-17 20:18:47 -08001186 if (getCameraState(cameraId) == nullptr) {
1187 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1188 cameraId.string());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001189 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1190 "No camera device with ID \"%s\" available", cameraId.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001191 }
1192
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001193 status_t err = checkIfDeviceIsUsable(cameraId);
1194 if (err != NO_ERROR) {
1195 switch(err) {
1196 case -ENODEV:
1197 case -EBUSY:
1198 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1199 "No camera device with ID \"%s\" currently available", cameraId.string());
1200 default:
1201 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1202 "Unknown error connecting to ID \"%s\"", cameraId.string());
1203 }
1204 }
1205 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001206}
1207
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001208Status CameraService::validateClientPermissionsLocked(const String8& cameraId,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001209 const String8& clientName8, int& clientUid, int& clientPid,
1210 /*out*/int& originalClientPid) const {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001211 int callingPid = CameraThreadState::getCallingPid();
1212 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001213
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001214 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001215 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001216 clientUid = callingUid;
1217 } else if (!isTrustedCallingUid(callingUid)) {
1218 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1219 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001220 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1221 "Untrusted caller (calling PID %d, UID %d) trying to "
1222 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1223 callingPid, callingUid, cameraId.string(),
1224 clientName8.string(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001225 }
1226
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001227 // Check if we can trust clientPid
1228 if (clientPid == USE_CALLING_PID) {
1229 clientPid = callingPid;
1230 } else if (!isTrustedCallingUid(callingUid)) {
1231 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1232 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001233 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1234 "Untrusted caller (calling PID %d, UID %d) trying to "
1235 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1236 callingPid, callingUid, cameraId.string(),
1237 clientName8.string(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001238 }
1239
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001240 if (shouldRejectSystemCameraConnection(cameraId)) {
1241 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1242 cameraId.c_str());
1243 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
1244 "available", cameraId.string());
1245 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001246 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1247 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1248 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
1249 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
1250 "found while trying to query device kind", cameraId.string());
1251
1252 }
1253
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001254 // If it's not calling from cameraserver, check the permission if the
1255 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1256 // android.permission.SYSTEM_CAMERA for system only camera devices).
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001257 if (callingPid != getpid() &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001258 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001259 !checkPermission(sCameraPermission, clientPid, clientUid)) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001260 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001261 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1262 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
1263 clientName8.string(), clientUid, clientPid, cameraId.string());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001264 }
1265
Svet Ganova453d0d2018-01-11 15:37:58 -08001266 // Make sure the UID is in an active state to use the camera
Svet Ganov7b4ab782018-03-25 12:48:10 -07001267 if (!mUidPolicy->isUidActive(callingUid, String16(clientName8))) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001268 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001269 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1270 clientPid, clientUid);
1271 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001272 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1273 "calling UID %d proc state %" PRId32 ")",
1274 clientName8.string(), clientUid, clientPid, cameraId.string(),
1275 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001276 }
1277
Michael Grooverd1d435a2018-12-18 17:39:42 -08001278 // If sensor privacy is enabled then prevent access to the camera
1279 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1280 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1281 return STATUS_ERROR_FMT(ERROR_DISABLED,
1282 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
1283 "is enabled", clientName8.string(), clientUid, clientPid, cameraId.string());
1284 }
1285
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001286 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1287 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001288 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001289 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001290
Ruben Brunk6267b532015-04-30 17:44:07 -07001291 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001292
Ruben Brunka8ca9152015-04-07 14:23:40 -07001293 // Only allow clients who are being used by the current foreground device user, unless calling
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001294 // from our own process OR the caller is using the cameraserver's HIDL interface.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001295 if (getCurrentServingCall() != BinderCallType::HWBINDER && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001296 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001297 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1298 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
1299 toString(mAllowedUsers).string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001300 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1301 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
1302 clientUserId, cameraId.string());
Ruben Brunk36597b22015-03-20 22:15:57 -07001303 }
1304
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001305 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001306}
1307
1308status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
1309 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001310 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001311 if (cameraState == nullptr) {
1312 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1313 cameraId.string());
1314 return -ENODEV;
1315 }
1316
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001317 StatusInternal currentStatus = cameraState->getStatus();
1318 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001319 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
1320 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001321 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001322 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001323 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
1324 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001325 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001326 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001327
Ruben Brunkcc776712015-02-17 20:18:47 -08001328 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001329}
1330
Ruben Brunkcc776712015-02-17 20:18:47 -08001331void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001332 const CameraService::DescriptorPtr& desc, int oomScoreOffset) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001333
Ruben Brunkcc776712015-02-17 20:18:47 -08001334 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001335 auto clientDescriptor =
1336 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
1337 oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08001338 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1339
1340 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
1341 String8(client->getPackageName()));
1342
1343 if (evicted.size() > 0) {
1344 // This should never happen - clients should already have been removed in disconnect
1345 for (auto& i : evicted) {
1346 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
1347 __FUNCTION__, i->getKey().string());
1348 }
1349
1350 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1351 __FUNCTION__);
1352 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001353
1354 // And register a death notification for the client callback. Do
1355 // this last to avoid Binder policy where a nested Binder
1356 // transaction might be pre-empted to service the client death
1357 // notification if the client process dies before linkToDeath is
1358 // invoked.
1359 sp<IBinder> remoteCallback = client->getRemote();
1360 if (remoteCallback != nullptr) {
1361 remoteCallback->linkToDeath(this);
1362 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001363}
1364
1365status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
1366 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001367 int oomScoreOffset,
Ruben Brunkcc776712015-02-17 20:18:47 -08001368 /*out*/
1369 sp<BasicClient>* client,
1370 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001371 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001372 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001373 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001374 DescriptorPtr clientDescriptor;
1375 {
1376 if (effectiveApiLevel == API_1) {
1377 // If we are using API1, any existing client for this camera ID with the same remote
1378 // should be returned rather than evicted to allow MediaRecorder to work properly.
1379
1380 auto current = mActiveClientManager.get(cameraId);
1381 if (current != nullptr) {
1382 auto clientSp = current->getValue();
1383 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001384 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
Shuzhen Wangb2d43f62021-08-25 14:01:11 -07001385 ALOGW("CameraService connect called with a different"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001386 " API level, evicting prior client...");
1387 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001388 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001389 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001390 *client = clientSp;
1391 return NO_ERROR;
1392 }
1393 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001394 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001395 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001396
Ruben Brunkcc776712015-02-17 20:18:47 -08001397 // Get current active client PIDs
1398 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1399 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001400
Emilian Peev8131a262017-02-01 12:33:43 +00001401 std::vector<int> priorityScores(ownerPids.size());
1402 std::vector<int> states(ownerPids.size());
Igor Murashkine6800ce2013-03-04 17:25:57 -08001403
Emilian Peev8131a262017-02-01 12:33:43 +00001404 // Get priority scores of all active PIDs
1405 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1406 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1407 /*out*/&priorityScores[0]);
1408 if (err != OK) {
1409 ALOGE("%s: Priority score query failed: %d",
1410 __FUNCTION__, err);
1411 return err;
1412 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001413
Ruben Brunkcc776712015-02-17 20:18:47 -08001414 // Update all active clients' priorities
Emilian Peev8131a262017-02-01 12:33:43 +00001415 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
Ruben Brunkcc776712015-02-17 20:18:47 -08001416 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
Emilian Peev8131a262017-02-01 12:33:43 +00001417 pidToPriorityMap.emplace(ownerPids[i],
Jayant Chowdharyc578a502019-05-08 10:57:54 -07001418 resource_policy::ClientPriority(priorityScores[i], states[i],
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001419 /* isVendorClient won't get copied over*/ false,
1420 /* oomScoreOffset won't get copied over*/ 0));
Ruben Brunkcc776712015-02-17 20:18:47 -08001421 }
1422 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001423
Ruben Brunkcc776712015-02-17 20:18:47 -08001424 // Get state for the given cameraId
1425 auto state = getCameraState(cameraId);
1426 if (state == nullptr) {
1427 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1428 clientPid, cameraId.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001429 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001430 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001431 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001432
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001433 int32_t actualScore = priorityScores[priorityScores.size() - 1];
1434 int32_t actualState = states[states.size() - 1];
1435
1436 // Make descriptor for incoming client. We store the oomScoreOffset
1437 // since we might need it later on new handleEvictionsLocked and
1438 // ProcessInfoService would not take that into account.
Shuzhen Wang2db86ff2018-04-25 01:11:17 +00001439 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001440 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001441 state->getConflicting(), actualScore, clientPid, actualState,
1442 oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08001443
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001444 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1445
Ruben Brunkcc776712015-02-17 20:18:47 -08001446 // Find clients that would be evicted
1447 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1448
1449 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1450 // background, so we cannot do evictions
1451 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1452 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1453 " priority).", clientPid);
1454
1455 sp<BasicClient> clientSp = clientDescriptor->getValue();
1456 String8 curTime = getFormattedCurrentTime();
1457 auto incompatibleClients =
1458 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1459
1460 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Emilian Peev8131a262017-02-01 12:33:43 +00001461 "(PID %d, score %d state %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001462 cameraId.string(), packageName.string(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001463 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001464
1465 for (auto& i : incompatibleClients) {
1466 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001467 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
1468 i->getKey().string(),
1469 String8{i->getValue()->getPackageName()}.string(),
1470 i->getOwnerId(), i->getPriority().getScore(),
1471 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001472 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00001473 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(),
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001474 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001475 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001476 }
1477
1478 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001479 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001480 mEventLog.add(msg);
1481
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001482 auto current = mActiveClientManager.get(cameraId);
1483 if (current != nullptr) {
1484 return -EBUSY; // CAMERA_IN_USE
1485 } else {
1486 return -EUSERS; // MAX_CAMERAS_IN_USE
1487 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001488 }
1489
1490 for (auto& i : evicted) {
1491 sp<BasicClient> clientSp = i->getValue();
1492 if (clientSp.get() == nullptr) {
1493 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1494
1495 // TODO: Remove this
1496 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1497 __FUNCTION__);
1498 mActiveClientManager.remove(i);
1499 continue;
1500 }
1501
1502 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1503 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001504 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001505
Ruben Brunkcc776712015-02-17 20:18:47 -08001506 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001507 logEvent(String8::format("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00001508 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1509 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001510 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
Emilian Peev8131a262017-02-01 12:33:43 +00001511 i->getOwnerId(), i->getPriority().getScore(),
1512 i->getPriority().getState(), cameraId.string(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001513 packageName.string(), clientPid, clientPriority.getScore(),
1514 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08001515
1516 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001517 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001518 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001519 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001520 }
1521
Ruben Brunkcc776712015-02-17 20:18:47 -08001522 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1523 // other clients from connecting in mServiceLockWrapper if held
1524 mServiceLock.unlock();
1525
1526 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07001527 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001528
1529 // Destroy evicted clients
1530 for (auto& i : evictedClients) {
1531 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001532 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001533 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001534
Jayant Chowdhary12361932018-08-27 14:46:13 -07001535 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08001536
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001537 for (const auto& i : evictedClients) {
1538 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1539 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1540 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1541 if (ret == TIMED_OUT) {
1542 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1543 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1544 mActiveClientManager.toString().string());
1545 return -EBUSY;
1546 }
1547 if (ret != NO_ERROR) {
1548 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1549 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1550 ret, mActiveClientManager.toString().string());
1551 return ret;
1552 }
1553 }
1554
1555 evictedClients.clear();
1556
Ruben Brunkcc776712015-02-17 20:18:47 -08001557 // Once clients have been disconnected, relock
1558 mServiceLock.lock();
1559
1560 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1561 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1562 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001563 }
1564
Ruben Brunkcc776712015-02-17 20:18:47 -08001565 *partial = clientDescriptor;
1566 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001567}
1568
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001569Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001570 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001571 int api1CameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001572 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001573 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001574 int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001575 int targetSdkVersion,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001576 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001577 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001578
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001579 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001580 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001581
1582 String8 id = cameraIdIntToStr(api1CameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001583 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001584 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001585 clientPackageName, {}, clientUid, clientPid, API_1,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001586 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001587
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001588 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001589 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001590 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001591 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001592 }
1593
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001594 *device = client;
1595 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001596}
1597
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001598bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
1599 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001600 // If the client is not a vendor client, don't add listener if
1601 // a) the camera is a publicly hidden secure camera OR
1602 // b) the camera is a system only camera and the client doesn't
1603 // have android.permission.SYSTEM_CAMERA permissions.
1604 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
1605 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1606 !hasPermissionsForSystemCamera(clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001607 return true;
1608 }
1609 return false;
1610}
1611
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001612bool CameraService::shouldRejectSystemCameraConnection(const String8& cameraId) const {
1613 // Rules for rejection:
1614 // 1) If cameraserver tries to access this camera device, accept the
1615 // connection.
1616 // 2) The camera device is a publicly hidden secure camera device AND some
1617 // component is trying to access it on a non-hwbinder thread (generally a non HAL client),
1618 // reject it.
1619 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
1620 // and the serving thread is a non hwbinder thread, the client must have
1621 // android.permission.SYSTEM_CAMERA permissions to connect.
1622
1623 int cPid = CameraThreadState::getCallingPid();
1624 int cUid = CameraThreadState::getCallingUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001625 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
1626 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001627 // This isn't a known camera ID, so it's not a system camera
1628 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
1629 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001630 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001631
1632 // (1) Cameraserver trying to connect, accept.
1633 if (CameraThreadState::getCallingPid() == getpid()) {
1634 return false;
1635 }
1636 // (2)
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001637 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001638 systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
1639 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
1640 return true;
1641 }
1642 // (3) Here we only check for permissions if it is a system only camera device. This is since
1643 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
1644 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
1645 // same behavior for system camera devices.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001646 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001647 systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Jayant Chowdharyc3198c32021-07-28 20:59:14 +00001648 !hasPermissionsForSystemCamera(cPid, cUid, /*logPermissionFailure*/true)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001649 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
1650 cameraId.c_str());
1651 return true;
1652 }
1653
1654 return false;
1655}
1656
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001657Status CameraService::connectDevice(
1658 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001659 const String16& cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001660 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001661 const std::optional<String16>& clientFeatureId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001662 int clientUid, int oomScoreOffset, int targetSdkVersion,
Ruben Brunkcc776712015-02-17 20:18:47 -08001663 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001664 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001665
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001666 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001667 Status ret = Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001668 String8 id = String8(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001669 sp<CameraDeviceClient> client = nullptr;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001670 String16 clientPackageNameAdj = clientPackageName;
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001671 int callingPid = CameraThreadState::getCallingPid();
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001672
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001673 if (getCurrentServingCall() == BinderCallType::HWBINDER) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001674 std::string vendorClient =
1675 StringPrintf("vendor.client.pid<%d>", CameraThreadState::getCallingPid());
1676 clientPackageNameAdj = String16(vendorClient.c_str());
1677 }
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001678
1679 if (oomScoreOffset < 0) {
1680 String8 msg =
1681 String8::format("Cannot increase the priority of a client %s pid %d for "
1682 "camera id %s", String8(clientPackageNameAdj).string(), callingPid,
1683 id.string());
1684 ALOGE("%s: %s", __FUNCTION__, msg.string());
1685 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
1686 }
1687
1688 // enforce system camera permissions
1689 if (oomScoreOffset > 0 &&
1690 !hasPermissionsForSystemCamera(callingPid, CameraThreadState::getCallingUid())) {
1691 String8 msg =
1692 String8::format("Cannot change the priority of a client %s pid %d for "
1693 "camera id %s without SYSTEM_CAMERA permissions",
1694 String8(clientPackageNameAdj).string(), callingPid, id.string());
1695 ALOGE("%s: %s", __FUNCTION__, msg.string());
1696 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.string());
1697 }
1698
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001699 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001700 /*api1CameraId*/-1, clientPackageNameAdj, clientFeatureId,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001701 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, oomScoreOffset,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001702 targetSdkVersion, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08001703
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001704 if(!ret.isOk()) {
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001705 logRejected(id, callingPid, String8(clientPackageNameAdj), ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001706 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001707 }
1708
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001709 *device = client;
Rucha Katakwardf223072021-06-15 10:21:00 -07001710 Mutex::Autolock lock(mServiceLock);
1711
1712 // Clear the previous cached logs and reposition the
1713 // file offset to beginning of the file to log new data.
1714 // If either truncate or lseek fails, close the previous file and create a new one.
1715 if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
1716 ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
1717 // Close the previous memfd.
1718 close(mMemFd);
1719 // If failure to wipe the data, then create a new file and
1720 // assign the new value to mMemFd.
1721 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
1722 if (mMemFd == -1) {
1723 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
1724 }
1725 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001726 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001727}
1728
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001729template<class CALLBACK, class CLIENT>
1730Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001731 int api1CameraId, const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001732 const std::optional<String16>& clientFeatureId, int clientUid, int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001733 apiLevel effectiveApiLevel, bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001734 /*out*/sp<CLIENT>& device) {
1735 binder::Status ret = binder::Status::ok();
1736
1737 String8 clientName8(clientPackageName);
1738
1739 int originalClientPid = 0;
1740
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001741 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001742 "Camera API version %d", clientPid, clientName8.string(), cameraId.string(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001743 static_cast<int>(effectiveApiLevel));
1744
Shuzhen Wang316781a2020-08-18 18:11:01 -07001745 nsecs_t openTimeNs = systemTime();
1746
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001747 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001748 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07001749 int orientation = 0;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001750 bool isNdk = (clientPackageName.size() == 0);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001751 {
1752 // Acquire mServiceLock and prevent other clients from connecting
1753 std::unique_ptr<AutoConditionLock> lock =
1754 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1755
1756 if (lock == nullptr) {
1757 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
1758 , clientPid);
1759 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1760 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
1761 cameraId.string(), clientName8.string(), clientPid);
1762 }
1763
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07001764 // Enforce client permissions and do basic validity checks
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001765 if(!(ret = validateConnectLocked(cameraId, clientName8,
1766 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
1767 return ret;
1768 }
1769
1770 // Check the shim parameters after acquiring lock, if they have already been updated and
1771 // we were doing a shim update, return immediately
1772 if (shimUpdateOnly) {
1773 auto cameraState = getCameraState(cameraId);
1774 if (cameraState != nullptr) {
1775 if (!cameraState->getShimParams().isEmpty()) return ret;
1776 }
1777 }
1778
1779 status_t err;
1780
1781 sp<BasicClient> clientTmp = nullptr;
1782 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
1783 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001784 IInterface::asBinder(cameraCb), clientName8, oomScoreOffset, /*out*/&clientTmp,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001785 /*out*/&partial)) != NO_ERROR) {
1786 switch (err) {
1787 case -ENODEV:
1788 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1789 "No camera device with ID \"%s\" currently available",
1790 cameraId.string());
1791 case -EBUSY:
1792 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1793 "Higher-priority client using camera, ID \"%s\" currently unavailable",
1794 cameraId.string());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001795 case -EUSERS:
1796 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1797 "Too many cameras already open, cannot open camera \"%s\"",
1798 cameraId.string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001799 default:
1800 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1801 "Unexpected error %s (%d) opening camera \"%s\"",
1802 strerror(-err), err, cameraId.string());
1803 }
1804 }
1805
1806 if (clientTmp.get() != nullptr) {
1807 // Handle special case for API1 MediaRecorder where the existing client is returned
1808 device = static_cast<CLIENT*>(clientTmp.get());
1809 return ret;
1810 }
1811
1812 // give flashlight a chance to close devices if necessary.
1813 mFlashlight->prepareDeviceOpen(cameraId);
1814
Emilian Peevb91f1802021-03-23 14:50:28 -07001815 int deviceVersion = getDeviceVersion(cameraId, /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08001816 if (facing == -1) {
1817 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.string());
1818 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1819 "Unable to get camera device \"%s\" facing", cameraId.string());
1820 }
1821
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001822 sp<BasicClient> tmp = nullptr;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001823 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
1824 mPerfClassPrimaryCameraIds, cameraId.string(), targetSdkVersion);
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001825 if(!(ret = makeClient(this, cameraCb, clientPackageName, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07001826 cameraId, api1CameraId, facing, orientation,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001827 clientPid, clientUid, getpid(),
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001828 deviceVersion, effectiveApiLevel, overrideForPerfClass,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001829 /*out*/&tmp)).isOk()) {
1830 return ret;
1831 }
1832 client = static_cast<CLIENT*>(tmp.get());
1833
1834 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
1835 __FUNCTION__);
1836
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07001837 String8 monitorTags = isClientWatched(client.get()) ? mMonitorTags : String8("");
1838 err = client->initialize(mCameraProviderManager, monitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001839 if (err != OK) {
1840 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001841 // Errors could be from the HAL module open call or from AppOpsManager
1842 switch(err) {
1843 case BAD_VALUE:
1844 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1845 "Illegal argument to HAL module for camera \"%s\"", cameraId.string());
1846 case -EBUSY:
1847 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1848 "Camera \"%s\" is already open", cameraId.string());
1849 case -EUSERS:
1850 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1851 "Too many cameras already open, cannot open camera \"%s\"",
1852 cameraId.string());
1853 case PERMISSION_DENIED:
1854 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1855 "No permission to open camera \"%s\"", cameraId.string());
1856 case -EACCES:
1857 return STATUS_ERROR_FMT(ERROR_DISABLED,
1858 "Camera \"%s\" disabled by policy", cameraId.string());
1859 case -ENODEV:
1860 default:
1861 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1862 "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
1863 strerror(-err), err);
1864 }
1865 }
1866
1867 // Update shim paremeters for legacy clients
1868 if (effectiveApiLevel == API_1) {
1869 // Assume we have always received a Client subclass for API1
1870 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
1871 String8 rawParams = shimClient->getParameters();
1872 CameraParameters params(rawParams);
1873
1874 auto cameraState = getCameraState(cameraId);
1875 if (cameraState != nullptr) {
1876 cameraState->setShimParams(params);
1877 } else {
1878 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
1879 __FUNCTION__, cameraId.string());
1880 }
1881 }
1882
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001883 // Set rotate-and-crop override behavior
1884 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
1885 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
Emilian Peev5368ebf2021-10-08 17:52:18 -07001886 } else if (effectiveApiLevel == API_2) {
Emilian Peev065b2c12021-11-23 13:12:57 -08001887
1888 client->setRotateAndCropOverride(
1889 CameraServiceProxyWrapper::getRotateAndCropOverride(
1890 clientPackageName, facing, multiuser_get_user_id(clientUid)));
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001891 }
1892
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08001893 // Set camera muting behavior
Valentin Iftimec0b8d472021-07-23 20:21:06 +02001894 bool isCameraPrivacyEnabled =
1895 mSensorPrivacyPolicy->isCameraPrivacyEnabled(multiuser_get_user_id(clientUid));
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08001896 if (client->supportsCameraMute()) {
Valentin Iftimec0b8d472021-07-23 20:21:06 +02001897 client->setCameraMute(
1898 mOverrideCameraMuteMode || isCameraPrivacyEnabled);
1899 } else if (isCameraPrivacyEnabled) {
1900 // no camera mute supported, but privacy is on! => disconnect
1901 ALOGI("Camera mute not supported for package: %s, camera id: %s",
1902 String8(client->getPackageName()).string(), cameraId.string());
1903 // Do not hold mServiceLock while disconnecting clients, but
1904 // retain the condition blocking other clients from connecting
1905 // in mServiceLockWrapper if held.
1906 mServiceLock.unlock();
1907 // Clear caller identity temporarily so client disconnect PID
1908 // checks work correctly
1909 int64_t token = CameraThreadState::clearCallingIdentity();
1910 // Note AppOp to trigger the "Unblock" dialog
1911 client->noteAppOp();
1912 client->disconnect();
1913 CameraThreadState::restoreCallingIdentity(token);
1914 // Reacquire mServiceLock
1915 mServiceLock.lock();
1916
1917 return STATUS_ERROR_FMT(ERROR_DISABLED,
1918 "Camera \"%s\" disabled due to camera mute", cameraId.string());
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08001919 }
1920
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001921 if (shimUpdateOnly) {
1922 // If only updating legacy shim parameters, immediately disconnect client
1923 mServiceLock.unlock();
1924 client->disconnect();
1925 mServiceLock.lock();
1926 } else {
1927 // Otherwise, add client to active clients list
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001928 finishConnectLocked(client, partial, oomScoreOffset);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001929 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001930
1931 client->setImageDumpMask(mImageDumpMask);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001932 } // lock is destroyed, allow further connect calls
1933
1934 // Important: release the mutex here so the client can call back into the service from its
1935 // destructor (can be at the end of the call)
1936 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001937
1938 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
1939 CameraServiceProxyWrapper::logOpen(cameraId, facing, clientPackageName,
1940 effectiveApiLevel, isNdk, openLatencyMs);
1941
Cliff Wud3a05312021-04-26 23:07:31 +08001942 {
1943 Mutex::Autolock lock(mInjectionParametersLock);
1944 if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
1945 mInjectionInitPending = false;
1946 status_t res = NO_ERROR;
1947 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
1948 if (clientDescriptor != nullptr) {
Cliff Wu646bd612021-11-23 23:21:29 +08001949 sp<BasicClient> clientSp = clientDescriptor->getValue();
1950 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
1951 if(res != OK) {
1952 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1953 "No camera device with ID \"%s\" currently available",
1954 mInjectionExternalCamId.string());
1955 }
1956 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08001957 if (res != OK) {
1958 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
1959 }
1960 } else {
1961 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
1962 __FUNCTION__, mInjectionInternalCamId.string());
1963 res = NO_INIT;
1964 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
1965 }
1966 }
1967 }
1968
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001969 return ret;
1970}
1971
Emilian Peevb2bc5a42019-11-20 16:02:14 -08001972status_t CameraService::addOfflineClient(String8 cameraId, sp<BasicClient> offlineClient) {
1973 if (offlineClient.get() == nullptr) {
1974 return BAD_VALUE;
1975 }
1976
1977 {
1978 // Acquire mServiceLock and prevent other clients from connecting
1979 std::unique_ptr<AutoConditionLock> lock =
1980 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1981
1982 if (lock == nullptr) {
1983 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
1984 , __FUNCTION__, offlineClient->getClientPid());
1985 return TIMED_OUT;
1986 }
1987
1988 auto onlineClientDesc = mActiveClientManager.get(cameraId);
1989 if (onlineClientDesc.get() == nullptr) {
1990 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
1991 cameraId.c_str());
1992 return BAD_VALUE;
1993 }
1994
1995 // Offline clients do not evict or conflict with other online devices. Resource sharing
1996 // conflicts are handled by the camera provider which will either succeed or fail before
1997 // reaching this method.
1998 const auto& onlinePriority = onlineClientDesc->getPriority();
1999 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
2000 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
2001 /*conflictingKeys*/ std::set<String8>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002002 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
2003 /*ommScoreOffset*/ 0);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002004
2005 // Allow only one offline device per camera
2006 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
2007 if (!incompatibleClients.empty()) {
2008 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
2009 return BAD_VALUE;
2010 }
2011
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002012 String8 monitorTags = isClientWatched(offlineClient.get()) ? mMonitorTags : String8("");
2013 auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002014 if (err != OK) {
2015 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
2016 return err;
2017 }
2018
2019 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
2020 if (evicted.size() > 0) {
2021 for (auto& i : evicted) {
2022 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
2023 __FUNCTION__, i->getKey().string());
2024 }
2025
2026 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
2027 "properly", __FUNCTION__);
2028
2029 return BAD_VALUE;
2030 }
2031
2032 logConnectedOffline(offlineClientDesc->getKey(),
2033 static_cast<int>(offlineClientDesc->getOwnerId()),
2034 String8(offlineClient->getPackageName()));
2035
2036 sp<IBinder> remoteCallback = offlineClient->getRemote();
2037 if (remoteCallback != nullptr) {
2038 remoteCallback->linkToDeath(this);
2039 }
2040 } // lock is destroyed, allow further connect calls
2041
2042 return OK;
2043}
2044
Rucha Katakwar38284522021-11-10 11:25:21 -08002045Status CameraService::turnOnTorchWithStrengthLevel(const String16& cameraId, int32_t torchStrength,
2046 const sp<IBinder>& clientBinder) {
2047 Mutex::Autolock lock(mServiceLock);
2048
2049 ATRACE_CALL();
2050 if (clientBinder == nullptr) {
2051 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
2052 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2053 "Torch client binder in null.");
2054 }
2055
2056 String8 id = String8(cameraId.string());
2057 int uid = CameraThreadState::getCallingUid();
2058
2059 if (shouldRejectSystemCameraConnection(id)) {
2060 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to change the strength level"
2061 "for system only device %s: ", id.string());
2062 }
2063
2064 // verify id is valid
2065 auto state = getCameraState(id);
2066 if (state == nullptr) {
2067 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
2068 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2069 "Camera ID \"%s\" is a not valid camera ID", id.string());
2070 }
2071
2072 StatusInternal cameraStatus = state->getStatus();
2073 if (cameraStatus != StatusInternal::NOT_AVAILABLE &&
2074 cameraStatus != StatusInternal::PRESENT) {
2075 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(),
2076 (int)cameraStatus);
2077 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2078 "Camera ID \"%s\" is a not valid camera ID", id.string());
2079 }
2080
2081 {
2082 Mutex::Autolock al(mTorchStatusMutex);
2083 TorchModeStatus status;
2084 status_t err = getTorchStatusLocked(id, &status);
2085 if (err != OK) {
2086 if (err == NAME_NOT_FOUND) {
2087 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2088 "Camera \"%s\" does not have a flash unit", id.string());
2089 }
2090 ALOGE("%s: getting current torch status failed for camera %s",
2091 __FUNCTION__, id.string());
2092 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2093 "Error changing torch strength level for camera \"%s\": %s (%d)",
2094 id.string(), strerror(-err), err);
2095 }
2096
2097 if (status == TorchModeStatus::NOT_AVAILABLE) {
2098 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
2099 ALOGE("%s: torch mode of camera %s is not available because "
2100 "camera is in use.", __FUNCTION__, id.string());
2101 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2102 "Torch for camera \"%s\" is not available due to an existing camera user",
2103 id.string());
2104 } else {
2105 ALOGE("%s: torch mode of camera %s is not available due to "
2106 "insufficient resources", __FUNCTION__, id.string());
2107 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2108 "Torch for camera \"%s\" is not available due to insufficient resources",
2109 id.string());
2110 }
2111 }
2112 }
2113
2114 {
2115 Mutex::Autolock al(mTorchUidMapMutex);
2116 updateTorchUidMapLocked(cameraId, uid);
2117 }
2118 // Check if the current torch strength level is same as the new one.
2119 bool shouldSkipTorchStrengthUpdates = mCameraProviderManager->shouldSkipTorchStrengthUpdate(
2120 id.string(), torchStrength);
2121
2122 status_t err = mFlashlight->turnOnTorchWithStrengthLevel(id, torchStrength);
2123
2124 if (err != OK) {
2125 int32_t errorCode;
2126 String8 msg;
2127 switch (err) {
2128 case -ENOSYS:
2129 msg = String8::format("Camera \"%s\" has no flashlight.",
2130 id.string());
2131 errorCode = ERROR_ILLEGAL_ARGUMENT;
2132 break;
2133 case -EBUSY:
2134 msg = String8::format("Camera \"%s\" is in use",
2135 id.string());
2136 errorCode = ERROR_CAMERA_IN_USE;
2137 break;
2138 default:
2139 msg = String8::format("Changing torch strength level failed.");
2140 errorCode = ERROR_INVALID_OPERATION;
2141
2142 }
2143 ALOGE("%s: %s", __FUNCTION__, msg.string());
2144 return STATUS_ERROR(errorCode, msg.string());
2145 }
2146
2147 {
2148 // update the link to client's death
2149 // Store the last client that turns on each camera's torch mode.
2150 Mutex::Autolock al(mTorchClientMapMutex);
2151 ssize_t index = mTorchClientMap.indexOfKey(id);
2152 if (index == NAME_NOT_FOUND) {
2153 mTorchClientMap.add(id, clientBinder);
2154 } else {
2155 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
2156 mTorchClientMap.replaceValueAt(index, clientBinder);
2157 }
2158 clientBinder->linkToDeath(this);
2159 }
2160
2161 int clientPid = CameraThreadState::getCallingPid();
2162 const char *id_cstr = id.c_str();
2163 ALOGI("%s: Torch strength for camera id %s changed to %d for client PID %d",
2164 __FUNCTION__, id_cstr, torchStrength, clientPid);
2165 if (!shouldSkipTorchStrengthUpdates) {
2166 broadcastTorchStrengthLevel(id, torchStrength);
2167 }
2168 return Status::ok();
2169}
2170
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002171Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002172 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002173 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002174
2175 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07002176 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002177 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002178 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2179 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002180 }
2181
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002182 String8 id = String8(cameraId.string());
Jayant Chowdhary12361932018-08-27 14:46:13 -07002183 int uid = CameraThreadState::getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002184
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002185 if (shouldRejectSystemCameraConnection(id)) {
2186 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
2187 " for system only device %s: ", id.string());
2188 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002189 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08002190 auto state = getCameraState(id);
2191 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07002192 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002193 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2194 "Camera ID \"%s\" is a not valid camera ID", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08002195 }
2196
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002197 StatusInternal cameraStatus = state->getStatus();
2198 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002199 cameraStatus != StatusInternal::NOT_AVAILABLE) {
2200 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002201 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2202 "Camera ID \"%s\" is a not valid camera ID", id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002203 }
2204
2205 {
2206 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002207 TorchModeStatus status;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002208 status_t err = getTorchStatusLocked(id, &status);
2209 if (err != OK) {
2210 if (err == NAME_NOT_FOUND) {
2211 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2212 "Camera \"%s\" does not have a flash unit", id.string());
2213 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002214 ALOGE("%s: getting current torch status failed for camera %s",
2215 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002216 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2217 "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
2218 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002219 }
2220
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002221 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002222 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002223 ALOGE("%s: torch mode of camera %s is not available because "
2224 "camera is in use", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002225 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2226 "Torch for camera \"%s\" is not available due to an existing camera user",
2227 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002228 } else {
2229 ALOGE("%s: torch mode of camera %s is not available due to "
2230 "insufficient resources", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002231 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2232 "Torch for camera \"%s\" is not available due to insufficient resources",
2233 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002234 }
2235 }
2236 }
2237
Ruben Brunk99e69712015-05-26 17:25:07 -07002238 {
2239 // Update UID map - this is used in the torch status changed callbacks, so must be done
2240 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07002241 Mutex::Autolock al(mTorchUidMapMutex);
Rucha Katakwar38284522021-11-10 11:25:21 -08002242 updateTorchUidMapLocked(cameraId, uid);
Ruben Brunk99e69712015-05-26 17:25:07 -07002243 }
2244
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002245 status_t err = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07002246
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002247 if (err != OK) {
2248 int32_t errorCode;
2249 String8 msg;
2250 switch (err) {
2251 case -ENOSYS:
2252 msg = String8::format("Camera \"%s\" has no flashlight",
2253 id.string());
2254 errorCode = ERROR_ILLEGAL_ARGUMENT;
2255 break;
Dijack Dongc8a6f252021-09-17 16:21:16 +08002256 case -EBUSY:
2257 msg = String8::format("Camera \"%s\" is in use",
2258 id.string());
2259 errorCode = ERROR_CAMERA_IN_USE;
2260 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002261 default:
2262 msg = String8::format(
2263 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
2264 id.string(), enabled, strerror(-err), err);
2265 errorCode = ERROR_INVALID_OPERATION;
2266 }
2267 ALOGE("%s: %s", __FUNCTION__, msg.string());
Rucha Katakward9ea6452021-05-06 11:57:16 -07002268 logServiceError(msg,errorCode);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002269 return STATUS_ERROR(errorCode, msg.string());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002270 }
2271
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002272 {
2273 // update the link to client's death
2274 Mutex::Autolock al(mTorchClientMapMutex);
2275 ssize_t index = mTorchClientMap.indexOfKey(id);
2276 if (enabled) {
2277 if (index == NAME_NOT_FOUND) {
2278 mTorchClientMap.add(id, clientBinder);
2279 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07002280 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002281 mTorchClientMap.replaceValueAt(index, clientBinder);
2282 }
2283 clientBinder->linkToDeath(this);
2284 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07002285 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002286 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002287 }
2288
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002289 int clientPid = CameraThreadState::getCallingPid();
2290 const char *id_cstr = id.c_str();
2291 const char *torchState = enabled ? "on" : "off";
2292 ALOGI("Torch for camera id %s turned %s for client PID %d", id_cstr, torchState, clientPid);
2293 logTorchEvent(id_cstr, torchState , clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002294 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002295}
2296
Rucha Katakwar38284522021-11-10 11:25:21 -08002297void CameraService::updateTorchUidMapLocked(const String16& cameraId, int uid) {
2298 String8 id = String8(cameraId.string());
2299 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
2300 mTorchUidMap[id].first = uid;
2301 mTorchUidMap[id].second = uid;
2302 } else {
2303 // Set the pending UID
2304 mTorchUidMap[id].first = uid;
2305 }
2306}
2307
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002308Status CameraService::notifySystemEvent(int32_t eventId,
2309 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002310 const int pid = CameraThreadState::getCallingPid();
2311 const int selfPid = getpid();
2312
2313 // Permission checks
2314 if (pid != selfPid) {
2315 // Ensure we're being called by system_server, or similar process with
2316 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002317 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002318 const int uid = CameraThreadState::getCallingUid();
2319 ALOGE("Permission Denial: cannot send updates to camera service about system"
2320 " events from pid=%d, uid=%d", pid, uid);
2321 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09002322 "No permission to send updates to camera service about system events"
2323 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002324 }
2325 }
2326
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002327 ATRACE_CALL();
2328
Ruben Brunk36597b22015-03-20 22:15:57 -07002329 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002330 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08002331 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002332 // from a system server crash
2333 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08002334 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002335 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07002336 break;
2337 }
Valentin Iftime29e2e152021-08-13 15:17:33 +02002338 case ICameraService::EVENT_USB_DEVICE_ATTACHED:
2339 case ICameraService::EVENT_USB_DEVICE_DETACHED: {
2340 // Notify CameraProviderManager for lazy HALs
2341 mCameraProviderManager->notifyUsbDeviceEvent(eventId,
2342 std::to_string(args[0]));
2343 break;
2344 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002345 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07002346 default: {
2347 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
2348 eventId);
2349 break;
2350 }
2351 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002352 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002353}
2354
Emilian Peev53722fa2019-02-22 17:47:20 -08002355void CameraService::notifyMonitoredUids() {
2356 Mutex::Autolock lock(mStatusListenerLock);
2357
2358 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002359 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Emilian Peev53722fa2019-02-22 17:47:20 -08002360 if (!ret.isOk()) {
2361 ALOGE("%s: Failed to trigger permission callback: %d", __FUNCTION__,
2362 ret.exceptionCode());
2363 }
2364 }
2365}
2366
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002367Status CameraService::notifyDeviceStateChange(int64_t newState) {
2368 const int pid = CameraThreadState::getCallingPid();
2369 const int selfPid = getpid();
2370
2371 // Permission checks
2372 if (pid != selfPid) {
2373 // Ensure we're being called by system_server, or similar process with
2374 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002375 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002376 const int uid = CameraThreadState::getCallingUid();
2377 ALOGE("Permission Denial: cannot send updates to camera service about device"
2378 " state changes from pid=%d, uid=%d", pid, uid);
2379 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2380 "No permission to send updates to camera service about device state"
2381 " changes from pid=%d, uid=%d", pid, uid);
2382 }
2383 }
2384
2385 ATRACE_CALL();
2386
2387 using hardware::camera::provider::V2_5::DeviceState;
2388 hardware::hidl_bitfield<DeviceState> newDeviceState{};
2389 if (newState & ICameraService::DEVICE_STATE_BACK_COVERED) {
2390 newDeviceState |= DeviceState::BACK_COVERED;
2391 }
2392 if (newState & ICameraService::DEVICE_STATE_FRONT_COVERED) {
2393 newDeviceState |= DeviceState::FRONT_COVERED;
2394 }
2395 if (newState & ICameraService::DEVICE_STATE_FOLDED) {
2396 newDeviceState |= DeviceState::FOLDED;
2397 }
2398 // Only map vendor bits directly
2399 uint64_t vendorBits = static_cast<uint64_t>(newState) & 0xFFFFFFFF00000000l;
2400 newDeviceState |= vendorBits;
2401
2402 ALOGV("%s: New device state 0x%" PRIx64, __FUNCTION__, newDeviceState);
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002403 mCameraProviderManager->notifyDeviceStateChange(newDeviceState);
2404
2405 return Status::ok();
2406}
2407
Emilian Peev8b64f282021-03-25 16:49:57 -07002408Status CameraService::notifyDisplayConfigurationChange() {
2409 ATRACE_CALL();
2410 const int callingPid = CameraThreadState::getCallingPid();
2411 const int selfPid = getpid();
2412
2413 // Permission checks
2414 if (callingPid != selfPid) {
2415 // Ensure we're being called by system_server, or similar process with
2416 // permissions to notify the camera service about system events
2417 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
2418 const int uid = CameraThreadState::getCallingUid();
2419 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
2420 " changes from pid=%d, uid=%d", callingPid, uid);
2421 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2422 "No permission to send updates to camera service about orientation"
2423 " changes from pid=%d, uid=%d", callingPid, uid);
2424 }
2425 }
2426
2427 Mutex::Autolock lock(mServiceLock);
2428
2429 // Don't do anything if rotate-and-crop override via cmd is active
2430 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
2431
2432 const auto clients = mActiveClientManager.getAll();
2433 for (auto& current : clients) {
2434 if (current != nullptr) {
2435 const auto basicClient = current->getValue();
Emilian Peeve23f1d92021-09-20 14:56:01 -07002436 if (basicClient.get() != nullptr && basicClient->canCastToApiClient(API_2)) {
Emilian Peev065b2c12021-11-23 13:12:57 -08002437 basicClient->setRotateAndCropOverride(
2438 CameraServiceProxyWrapper::getRotateAndCropOverride(
2439 basicClient->getPackageName(),
2440 basicClient->getCameraFacing(),
2441 multiuser_get_user_id(basicClient->getClientUid())));
Emilian Peev8b64f282021-03-25 16:49:57 -07002442 }
2443 }
2444 }
2445
2446 return Status::ok();
2447}
2448
2449Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002450 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
2451 ATRACE_CALL();
2452 if (!concurrentCameraIds) {
2453 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
2454 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
2455 }
2456
2457 if (!mInitialized) {
2458 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Rucha Katakward9ea6452021-05-06 11:57:16 -07002459 logServiceError(String8::format("Camera subsystem is not available"),ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002460 return STATUS_ERROR(ERROR_DISCONNECTED,
2461 "Camera subsystem is not available");
2462 }
2463 // First call into the provider and get the set of concurrent camera
2464 // combinations
2465 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07002466 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002467 for (auto &combination : concurrentCameraCombinations) {
2468 std::vector<std::string> validCombination;
2469 for (auto &cameraId : combination) {
2470 // if the camera state is not present, skip
2471 String8 cameraIdStr(cameraId.c_str());
2472 auto state = getCameraState(cameraIdStr);
2473 if (state == nullptr) {
2474 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
2475 continue;
2476 }
2477 StatusInternal status = state->getStatus();
2478 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
2479 continue;
2480 }
2481 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
2482 continue;
2483 }
2484 validCombination.push_back(cameraId);
2485 }
2486 if (validCombination.size() != 0) {
2487 concurrentCameraIds->push_back(std::move(validCombination));
2488 }
2489 }
2490 return Status::ok();
2491}
2492
2493Status CameraService::isConcurrentSessionConfigurationSupported(
2494 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002495 int targetSdkVersion, /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002496 if (!isSupported) {
2497 ALOGE("%s: isSupported is NULL", __FUNCTION__);
2498 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
2499 }
2500
2501 if (!mInitialized) {
2502 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2503 return STATUS_ERROR(ERROR_DISCONNECTED,
2504 "Camera subsystem is not available");
2505 }
2506
2507 // Check for camera permissions
2508 int callingPid = CameraThreadState::getCallingPid();
2509 int callingUid = CameraThreadState::getCallingUid();
2510 if ((callingPid != getpid()) && !checkPermission(sCameraPermission, callingPid, callingUid)) {
2511 ALOGE("%s: pid %d doesn't have camera permissions", __FUNCTION__, callingPid);
2512 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2513 "android.permission.CAMERA needed to call"
2514 "isConcurrentSessionConfigurationSupported");
2515 }
2516
2517 status_t res =
2518 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002519 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
2520 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002521 if (res != OK) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07002522 logServiceError(String8::format("Unable to query session configuration support"),
2523 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002524 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
2525 "support %s (%d)", strerror(-res), res);
2526 }
2527 return Status::ok();
2528}
2529
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002530Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
2531 /*out*/
2532 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002533 return addListenerHelper(listener, cameraStatuses);
2534}
2535
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002536binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
2537 std::vector<hardware::CameraStatus>* cameraStatuses) {
2538 return addListenerHelper(listener, cameraStatuses, false, true);
2539}
2540
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002541Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
2542 /*out*/
2543 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002544 bool isVendorListener, bool isProcessLocalTest) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002545
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002546 ATRACE_CALL();
2547
Igor Murashkinbfc99152013-02-27 12:55:20 -08002548 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08002549
Ruben Brunk3450ba72015-06-16 11:00:37 -07002550 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002551 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002552 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002553 }
2554
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002555 auto clientUid = CameraThreadState::getCallingUid();
2556 auto clientPid = CameraThreadState::getCallingPid();
Shuzhen Wang695044d2020-03-06 09:02:23 -08002557 bool openCloseCallbackAllowed = checkPermission(sCameraOpenCloseListenerPermission,
Jayant Chowdharyc3198c32021-07-28 20:59:14 +00002558 clientPid, clientUid, /*logPermissionFailure*/false);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002559
Igor Murashkinbfc99152013-02-27 12:55:20 -08002560 Mutex::Autolock lock(mServiceLock);
2561
Ruben Brunkcc776712015-02-17 20:18:47 -08002562 {
2563 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08002564 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002565 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002566 ALOGW("%s: Tried to add listener %p which was already subscribed",
2567 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002568 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08002569 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002570 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002571
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002572 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08002573 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
2574 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002575 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08002576 if (ret != NO_ERROR) {
2577 String8 msg = String8::format("Failed to initialize service listener: %s (%d)",
2578 strerror(-ret), ret);
Rucha Katakward9ea6452021-05-06 11:57:16 -07002579 logServiceError(msg,ERROR_ILLEGAL_ARGUMENT);
Emilian Peev53722fa2019-02-22 17:47:20 -08002580 ALOGE("%s: %s", __FUNCTION__, msg.string());
2581 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
2582 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002583 // The listener still needs to be added to the list of listeners, regardless of what
2584 // permissions the listener process has / whether it is a vendor listener. Since it might be
2585 // eligible to listen to other camera ids.
2586 mListenerList.emplace_back(serviceListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08002587 mUidPolicy->registerMonitorUid(clientUid);
Igor Murashkinbfc99152013-02-27 12:55:20 -08002588 }
2589
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002590 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07002591 {
Ruben Brunkcc776712015-02-17 20:18:47 -08002592 Mutex::Autolock lock(mCameraStatesLock);
2593 for (auto& i : mCameraStates) {
Shuzhen Wang43858162020-01-10 13:42:15 -08002594 cameraStatuses->emplace_back(i.first,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07002595 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
2596 openCloseCallbackAllowed ? i.second->getClientPackage() : String8::empty());
Igor Murashkincba2c162013-03-20 15:56:31 -07002597 }
2598 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002599 // Remove the camera statuses that should be hidden from the client, we do
2600 // this after collecting the states in order to avoid holding
2601 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
2602 // the same time.
2603 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
2604 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
2605 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
2606 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
2607 ALOGE("%s: Invalid camera id %s, skipping status update",
2608 __FUNCTION__, s.cameraId.c_str());
2609 return true;
2610 }
2611 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
2612 clientUid);}), cameraStatuses->end());
2613
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002614 //cameraStatuses will have non-eligible camera ids removed.
2615 std::set<String16> idsChosenForCallback;
2616 for (const auto &s : *cameraStatuses) {
2617 idsChosenForCallback.insert(String16(s.cameraId));
2618 }
Igor Murashkincba2c162013-03-20 15:56:31 -07002619
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002620 /*
2621 * Immediately signal current torch status to this listener only
2622 * This may be a subset of all the devices, so don't include it in the response directly
2623 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002624 {
2625 Mutex::Autolock al(mTorchStatusMutex);
2626 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002627 String16 id = String16(mTorchStatusMap.keyAt(i).string());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002628 // The camera id is visible to the client. Fine to send torch
2629 // callback.
2630 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
2631 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
2632 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002633 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002634 }
2635
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002636 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08002637}
Ruben Brunkcc776712015-02-17 20:18:47 -08002638
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002639Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002640 ATRACE_CALL();
2641
Igor Murashkinbfc99152013-02-27 12:55:20 -08002642 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
2643
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002644 if (listener == 0) {
2645 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002646 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002647 }
2648
Igor Murashkinbfc99152013-02-27 12:55:20 -08002649 Mutex::Autolock lock(mServiceLock);
2650
Ruben Brunkcc776712015-02-17 20:18:47 -08002651 {
2652 Mutex::Autolock lock(mStatusListenerLock);
2653 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002654 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
2655 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid());
2656 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08002657 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002658 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002659 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002660 }
2661 }
2662
2663 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
2664 __FUNCTION__, listener.get());
2665
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002666 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08002667}
2668
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002669Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002670
2671 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002672 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
2673
2674 if (parameters == NULL) {
2675 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002676 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07002677 }
2678
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002679 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002680
2681 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002682 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07002683 // Error logged by caller
2684 return ret;
2685 }
2686
2687 String8 shimParamsString8 = shimParams.flatten();
2688 String16 shimParamsString16 = String16(shimParamsString8);
2689
2690 *parameters = shimParamsString16;
2691
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002692 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07002693}
2694
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002695Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
2696 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002697 ATRACE_CALL();
2698
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002699 const String8 id = String8(cameraId);
2700
2701 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002702
2703 switch (apiVersion) {
2704 case API_VERSION_1:
2705 case API_VERSION_2:
2706 break;
2707 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002708 String8 msg = String8::format("Unknown API version %d", apiVersion);
2709 ALOGE("%s: %s", __FUNCTION__, msg.string());
2710 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002711 }
2712
Emilian Peev28ad2ea2017-02-07 16:14:32 +00002713 int deviceVersion = getDeviceVersion(id);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002714 switch (deviceVersion) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002715 case CAMERA_DEVICE_API_VERSION_1_0:
2716 case CAMERA_DEVICE_API_VERSION_3_0:
2717 case CAMERA_DEVICE_API_VERSION_3_1:
2718 if (apiVersion == API_VERSION_2) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002719 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without shim",
2720 __FUNCTION__, id.string(), deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002721 *isSupported = false;
2722 } else { // if (apiVersion == API_VERSION_1) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002723 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always supported",
2724 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002725 *isSupported = true;
2726 }
2727 break;
2728 case CAMERA_DEVICE_API_VERSION_3_2:
2729 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -07002730 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002731 case CAMERA_DEVICE_API_VERSION_3_5:
Yin-Chia Yeh56d98ba2020-01-16 16:57:14 -08002732 case CAMERA_DEVICE_API_VERSION_3_6:
Shuzhen Wang83bff122020-11-20 15:51:39 -08002733 case CAMERA_DEVICE_API_VERSION_3_7:
Shuzhen Wang90708ea2021-11-04 11:40:49 -07002734 case CAMERA_DEVICE_API_VERSION_3_8:
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002735 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
2736 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002737 *isSupported = true;
2738 break;
2739 case -1: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002740 String8 msg = String8::format("Unknown camera ID %s", id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002741 ALOGE("%s: %s", __FUNCTION__, msg.string());
2742 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002743 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002744 default: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002745 String8 msg = String8::format("Unknown device version %x for device %s",
2746 deviceVersion, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002747 ALOGE("%s: %s", __FUNCTION__, msg.string());
2748 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
2749 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07002750 }
2751
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002752 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002753}
2754
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002755Status CameraService::isHiddenPhysicalCamera(const String16& cameraId,
2756 /*out*/ bool *isSupported) {
2757 ATRACE_CALL();
2758
2759 const String8 id = String8(cameraId);
2760
2761 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
2762 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(id.string());
2763
2764 return Status::ok();
2765}
2766
Cliff Wud8cae102021-03-11 01:37:42 +08002767Status CameraService::injectCamera(
2768 const String16& packageName, const String16& internalCamId,
2769 const String16& externalCamId,
2770 const sp<ICameraInjectionCallback>& callback,
2771 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08002772 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08002773 ATRACE_CALL();
2774
2775 if (!checkCallingPermission(sCameraInjectExternalCameraPermission)) {
2776 const int pid = CameraThreadState::getCallingPid();
2777 const int uid = CameraThreadState::getCallingUid();
2778 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
2779 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2780 "Permission Denial: no permission to inject camera");
2781 }
2782
2783 ALOGV(
2784 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
2785 "%s",
2786 __FUNCTION__, String8(packageName).string(),
2787 String8(internalCamId).string(), String8(externalCamId).string());
2788
Cliff Wud3a05312021-04-26 23:07:31 +08002789 {
2790 Mutex::Autolock lock(mInjectionParametersLock);
2791 mInjectionInternalCamId = String8(internalCamId);
2792 mInjectionExternalCamId = String8(externalCamId);
Cliff Wu646bd612021-11-23 23:21:29 +08002793 mInjectionStatusListener->addListener(callback);
2794 *cameraInjectionSession = new CameraInjectionSession(this);
Cliff Wud3a05312021-04-26 23:07:31 +08002795 status_t res = NO_ERROR;
2796 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2797 // If the client already exists, we can directly connect to the camera device through the
2798 // client's injectCamera(), otherwise we need to wait until the client is established
2799 // (execute connectHelper()) before injecting the camera to the camera device.
2800 if (clientDescriptor != nullptr) {
2801 mInjectionInitPending = false;
Cliff Wu646bd612021-11-23 23:21:29 +08002802 sp<BasicClient> clientSp = clientDescriptor->getValue();
2803 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2804 if(res != OK) {
2805 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2806 "No camera device with ID \"%s\" currently available",
2807 mInjectionExternalCamId.string());
2808 }
2809 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08002810 if(res != OK) {
2811 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2812 }
2813 } else {
2814 mInjectionInitPending = true;
2815 }
2816 }
Cliff Wud8cae102021-03-11 01:37:42 +08002817
Cliff Wud3a05312021-04-26 23:07:31 +08002818 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08002819}
2820
Ruben Brunkcc776712015-02-17 20:18:47 -08002821void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002822 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002823 for (auto& i : mActiveClientManager.getAll()) {
2824 auto clientSp = i->getValue();
2825 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002826 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08002827 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08002828 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07002829 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002830 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08002831}
2832
Ruben Brunkcc776712015-02-17 20:18:47 -08002833bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002834 bool ret = false;
2835 {
2836 // Acquire mServiceLock and prevent other clients from connecting
2837 std::unique_ptr<AutoConditionLock> lock =
2838 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08002839
Igor Murashkin634a5152013-02-20 17:15:11 -08002840
Ruben Brunkcc776712015-02-17 20:18:47 -08002841 std::vector<sp<BasicClient>> evicted;
2842 for (auto& i : mActiveClientManager.getAll()) {
2843 auto clientSp = i->getValue();
2844 if (clientSp.get() == nullptr) {
2845 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2846 mActiveClientManager.remove(i);
2847 continue;
2848 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08002849 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002850 mActiveClientManager.remove(i);
2851 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08002852
Ruben Brunkcc776712015-02-17 20:18:47 -08002853 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002854 clientSp->notifyError(
2855 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002856 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08002857 }
2858 }
2859
Ruben Brunkcc776712015-02-17 20:18:47 -08002860 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2861 // other clients from connecting in mServiceLockWrapper if held
2862 mServiceLock.unlock();
2863
Ruben Brunk36597b22015-03-20 22:15:57 -07002864 // Do not clear caller identity, remote caller should be client proccess
2865
Ruben Brunkcc776712015-02-17 20:18:47 -08002866 for (auto& i : evicted) {
2867 if (i.get() != nullptr) {
2868 i->disconnect();
2869 ret = true;
2870 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002871 }
2872
Ruben Brunkcc776712015-02-17 20:18:47 -08002873 // Reacquire mServiceLock
2874 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08002875
Ruben Brunkcc776712015-02-17 20:18:47 -08002876 } // lock is destroyed, allow further connect calls
2877
2878 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07002879}
2880
Ruben Brunkcc776712015-02-17 20:18:47 -08002881std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
2882 const String8& cameraId) const {
2883 std::shared_ptr<CameraState> state;
2884 {
2885 Mutex::Autolock lock(mCameraStatesLock);
2886 auto iter = mCameraStates.find(cameraId);
2887 if (iter != mCameraStates.end()) {
2888 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002889 }
2890 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002891 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002892}
2893
Ruben Brunkcc776712015-02-17 20:18:47 -08002894sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
2895 // Remove from active clients list
2896 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
2897 if (clientDescriptorPtr == nullptr) {
2898 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
2899 cameraId.string());
2900 return sp<BasicClient>{nullptr};
2901 }
2902
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002903 sp<BasicClient> client = clientDescriptorPtr->getValue();
2904 if (client.get() != nullptr) {
2905 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
2906 }
2907 return client;
Keun young Parkd8973a72012-03-28 14:13:09 -07002908}
2909
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002910void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07002911 // Acquire mServiceLock and prevent other clients from connecting
2912 std::unique_ptr<AutoConditionLock> lock =
2913 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
2914
Ruben Brunk6267b532015-04-30 17:44:07 -07002915 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002916 for (size_t i = 0; i < newUserIds.size(); i++) {
2917 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07002918 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002919 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07002920 return;
2921 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002922 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07002923 }
2924
Ruben Brunka8ca9152015-04-07 14:23:40 -07002925
Ruben Brunk6267b532015-04-30 17:44:07 -07002926 if (newAllowedUsers == mAllowedUsers) {
2927 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
2928 return;
2929 }
2930
2931 logUserSwitch(mAllowedUsers, newAllowedUsers);
2932
2933 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07002934
2935 // Current user has switched, evict all current clients.
2936 std::vector<sp<BasicClient>> evicted;
2937 for (auto& i : mActiveClientManager.getAll()) {
2938 auto clientSp = i->getValue();
2939
2940 if (clientSp.get() == nullptr) {
2941 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2942 continue;
2943 }
2944
Ruben Brunk6267b532015-04-30 17:44:07 -07002945 // Don't evict clients that are still allowed.
2946 uid_t clientUid = clientSp->getClientUid();
2947 userid_t clientUserId = multiuser_get_user_id(clientUid);
2948 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
2949 continue;
2950 }
2951
Ruben Brunk36597b22015-03-20 22:15:57 -07002952 evicted.push_back(clientSp);
2953
2954 String8 curTime = getFormattedCurrentTime();
2955
2956 ALOGE("Evicting conflicting client for camera ID %s due to user change",
2957 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07002958
Ruben Brunk36597b22015-03-20 22:15:57 -07002959 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002960 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00002961 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
2962 " to user switch.", i->getKey().string(),
2963 String8{clientSp->getPackageName()}.string(),
2964 i->getOwnerId(), i->getPriority().getScore(),
2965 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07002966
2967 }
2968
2969 // Do not hold mServiceLock while disconnecting clients, but retain the condition
2970 // blocking other clients from connecting in mServiceLockWrapper if held.
2971 mServiceLock.unlock();
2972
2973 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07002974 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07002975
2976 for (auto& i : evicted) {
2977 i->disconnect();
2978 }
2979
Jayant Chowdhary12361932018-08-27 14:46:13 -07002980 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07002981
2982 // Reacquire mServiceLock
2983 mServiceLock.lock();
2984}
Ruben Brunkcc776712015-02-17 20:18:47 -08002985
Ruben Brunka8ca9152015-04-07 14:23:40 -07002986void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002987 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07002988 Mutex::Autolock l(mLogLock);
Rucha Katakward9ea6452021-05-06 11:57:16 -07002989 String8 msg = String8::format("%s : %s", curTime.string(), event);
2990 // For service error events, print the msg only once.
2991 if(!msg.contains("SERVICE ERROR")) {
2992 mEventLog.add(msg);
2993 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
2994 // Error event not added to the dumpsys log before
2995 mEventLog.add(msg);
2996 sServiceErrorEventSet.insert(msg);
2997 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002998}
2999
Ruben Brunka8ca9152015-04-07 14:23:40 -07003000void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003001 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003002 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07003003 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003004 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003005}
3006
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003007void CameraService::logDisconnectedOffline(const char* cameraId, int clientPid,
3008 const char* clientPackage) {
3009 // Log the clients evicted
3010 logEvent(String8::format("DISCONNECT offline device %s client for package %s (PID %d)",
3011 cameraId, clientPackage, clientPid));
3012}
3013
Ruben Brunka8ca9152015-04-07 14:23:40 -07003014void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003015 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003016 // Log the clients evicted
3017 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003018 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003019}
3020
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003021void CameraService::logConnectedOffline(const char* cameraId, int clientPid,
3022 const char* clientPackage) {
3023 // Log the clients evicted
3024 logEvent(String8::format("CONNECT offline device %s client for package %s (PID %d)", cameraId,
3025 clientPackage, clientPid));
3026}
3027
Ruben Brunka8ca9152015-04-07 14:23:40 -07003028void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003029 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003030 // Log the client rejected
3031 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003032 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003033}
3034
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003035void CameraService::logTorchEvent(const char* cameraId, const char *torchState, int clientPid) {
3036 // Log torch event
3037 logEvent(String8::format("Torch for camera id %s turned %s for client PID %d", cameraId,
3038 torchState, clientPid));
3039}
3040
Ruben Brunk6267b532015-04-30 17:44:07 -07003041void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
3042 const std::set<userid_t>& newUserIds) {
3043 String8 newUsers = toString(newUserIds);
3044 String8 oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003045 if (oldUsers.size() == 0) {
3046 oldUsers = "<None>";
3047 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07003048 // Log the new and old users
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003049 logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
Ruben Brunk6267b532015-04-30 17:44:07 -07003050 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003051}
3052
3053void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
3054 // Log the device removal
3055 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
3056}
3057
3058void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
3059 // Log the device removal
3060 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
3061}
3062
3063void CameraService::logClientDied(int clientPid, const char* reason) {
3064 // Log the device removal
3065 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07003066}
3067
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003068void CameraService::logServiceError(const char* msg, int errorCode) {
3069 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08003070 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003071}
3072
Ruben Brunk36597b22015-03-20 22:15:57 -07003073status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
3074 uint32_t flags) {
3075
Mathias Agopian65ab4712010-07-14 17:59:35 -07003076 // Permission checks
3077 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003078 case SHELL_COMMAND_TRANSACTION: {
3079 int in = data.readFileDescriptor();
3080 int out = data.readFileDescriptor();
3081 int err = data.readFileDescriptor();
3082 int argc = data.readInt32();
3083 Vector<String16> args;
3084 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
3085 args.add(data.readString16());
3086 }
3087 sp<IBinder> unusedCallback;
3088 sp<IResultReceiver> resultReceiver;
3089 status_t status;
3090 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
3091 return status;
3092 }
3093 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
3094 return status;
3095 }
3096 status = shellCommand(in, out, err, args);
3097 if (resultReceiver != nullptr) {
3098 resultReceiver->send(status);
3099 }
3100 return NO_ERROR;
3101 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003102 }
3103
3104 return BnCameraService::onTransact(code, data, reply, flags);
3105}
3106
Mathias Agopian65ab4712010-07-14 17:59:35 -07003107// We share the media players for shutter and recording sound for all clients.
3108// A reference count is kept to determine when we will actually release the
3109// media players.
3110
Jaekyun Seokef498052018-03-23 13:09:44 +09003111sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
3112 sp<MediaPlayer> mp = new MediaPlayer();
3113 status_t error;
3114 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08003115 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09003116 error = mp->prepare();
3117 }
3118 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00003119 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09003120 mp->disconnect();
3121 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003122 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003123 }
3124 return mp;
3125}
3126
username5755fea2018-12-27 09:48:08 +08003127void CameraService::increaseSoundRef() {
3128 Mutex::Autolock lock(mSoundLock);
3129 mSoundRef++;
3130}
3131
3132void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003133 ATRACE_CALL();
3134
username5755fea2018-12-27 09:48:08 +08003135 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
3136 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
3137 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
3138 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
3139 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
3140 }
3141 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
3142 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
3143 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
3144 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003145 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08003146 }
3147 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
3148 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
3149 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
3150 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
3151 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003152 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003153}
3154
username5755fea2018-12-27 09:48:08 +08003155void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003156 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08003157 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003158 if (--mSoundRef) return;
3159
3160 for (int i = 0; i < NUM_SOUNDS; i++) {
3161 if (mSoundPlayer[i] != 0) {
3162 mSoundPlayer[i]->disconnect();
3163 mSoundPlayer[i].clear();
3164 }
3165 }
3166}
3167
3168void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003169 ATRACE_CALL();
3170
Mathias Agopian65ab4712010-07-14 17:59:35 -07003171 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07003172 if (kind < 0 || kind >= NUM_SOUNDS) {
3173 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
3174 return;
3175 }
3176
Mathias Agopian65ab4712010-07-14 17:59:35 -07003177 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08003178 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003179 sp<MediaPlayer> player = mSoundPlayer[kind];
3180 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08003181 player->seekTo(0);
3182 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003183 }
3184}
3185
3186// ----------------------------------------------------------------------------
3187
3188CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07003189 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003190 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09003191 const std::optional<String16>& clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003192 const String8& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07003193 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003194 int clientPid, uid_t clientUid,
3195 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08003196 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08003197 IInterface::asBinder(cameraClient),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08003198 clientPackageName, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07003199 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003200 clientPid, clientUid,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003201 servicePid),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003202 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08003203{
Jayant Chowdhary12361932018-08-27 14:46:13 -07003204 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003205 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003206
Igor Murashkin44cfcf02013-03-01 16:22:28 -08003207 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003208
username5755fea2018-12-27 09:48:08 +08003209 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003210
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003211 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003212}
3213
Mathias Agopian65ab4712010-07-14 17:59:35 -07003214// tear down the client
3215CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003216 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08003217 mDestructionStarted = true;
3218
username5755fea2018-12-27 09:48:08 +08003219 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003220 // unconditionally disconnect. function is idempotent
3221 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003222}
3223
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003224sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
3225
Igor Murashkin634a5152013-02-20 17:15:11 -08003226CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003227 const sp<IBinder>& remoteCallback,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09003228 const String16& clientPackageName, const std::optional<String16>& clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07003229 const String8& cameraIdStr, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003230 int clientPid, uid_t clientUid,
3231 int servicePid):
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003232 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07003233 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09003234 mClientPackageName(clientPackageName), mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08003235 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003236 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07003237 mDisconnected(false), mUidIsTrusted(false),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003238 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003239 mRemoteBinder(remoteCallback),
3240 mOpsActive(false),
3241 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08003242{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003243 if (sCameraService == nullptr) {
3244 sCameraService = cameraService;
3245 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08003246
3247 // In some cases the calling code has no access to the package it runs under.
3248 // For example, NDK camera API.
3249 // In this case we will get the packages for the calling UID and pick the first one
3250 // for attributing the app op. This will work correctly for runtime permissions
3251 // as for legacy apps we will toggle the app op for all packages in the UID.
3252 // The caveat is that the operation may be attributed to the wrong package and
3253 // stats based on app ops may be slightly off.
3254 if (mClientPackageName.size() <= 0) {
3255 sp<IServiceManager> sm = defaultServiceManager();
3256 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
3257 if (binder == 0) {
3258 ALOGE("Cannot get permission service");
3259 // Leave mClientPackageName unchanged (empty) and the further interaction
3260 // with camera will fail in BasicClient::startCameraOps
3261 return;
3262 }
3263
3264 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
3265 Vector<String16> packages;
3266
3267 permCtrl->getPackagesForUid(mClientUid, packages);
3268
3269 if (packages.isEmpty()) {
3270 ALOGE("No packages for calling UID");
3271 // Leave mClientPackageName unchanged (empty) and the further interaction
3272 // with camera will fail in BasicClient::startCameraOps
3273 return;
3274 }
3275 mClientPackageName = packages[0];
3276 }
Steven Moreland89a2c5c2020-01-31 15:02:25 -08003277 if (getCurrentServingCall() != BinderCallType::HWBINDER) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003278 mAppOpsManager = std::make_unique<AppOpsManager>();
3279 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07003280
3281 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08003282}
3283
3284CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003285 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08003286 mDestructionStarted = true;
3287}
3288
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003289binder::Status CameraService::BasicClient::disconnect() {
3290 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003291 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003292 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07003293 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07003294 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08003295
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003296 sCameraService->removeByClient(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003297 sCameraService->logDisconnected(mCameraIdStr, mClientPid, String8(mClientPackageName));
Peter Kalauskasa29c1352018-10-10 12:05:42 -07003298 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
3299 mCameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003300
3301 sp<IBinder> remote = getRemote();
3302 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003303 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08003304 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003305
3306 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07003307 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003308 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
3309 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
3310 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003311
Igor Murashkincba2c162013-03-20 15:56:31 -07003312 // client shouldn't be able to call into us anymore
3313 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003314
3315 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08003316}
3317
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08003318status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
3319 // No dumping of clients directly over Binder,
3320 // must go through CameraService::dump
3321 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07003322 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08003323 return OK;
3324}
3325
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07003326status_t CameraService::BasicClient::startWatchingTags(const String8&, int) {
3327 // Can't watch tags directly, must go through CameraService::startWatchingTags
3328 return OK;
3329}
3330
3331status_t CameraService::BasicClient::stopWatchingTags(int) {
3332 // Can't watch tags directly, must go through CameraService::stopWatchingTags
3333 return OK;
3334}
3335
3336status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
3337 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
3338 return OK;
3339}
3340
Ruben Brunkcc776712015-02-17 20:18:47 -08003341String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003342 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08003343}
3344
Emilian Peev8b64f282021-03-25 16:49:57 -07003345int CameraService::BasicClient::getCameraFacing() const {
3346 return mCameraFacing;
3347}
3348
3349int CameraService::BasicClient::getCameraOrientation() const {
3350 return mOrientation;
3351}
Ruben Brunkcc776712015-02-17 20:18:47 -08003352
3353int CameraService::BasicClient::getClientPid() const {
3354 return mClientPid;
3355}
3356
Ruben Brunk6267b532015-04-30 17:44:07 -07003357uid_t CameraService::BasicClient::getClientUid() const {
3358 return mClientUid;
3359}
3360
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003361bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
3362 // Defaults to API2.
3363 return level == API_2;
3364}
3365
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07003366status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003367 {
3368 Mutex::Autolock l(mAudioRestrictionLock);
3369 mAudioRestriction = mode;
3370 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07003371 sCameraService->updateAudioRestriction();
3372 return OK;
3373}
3374
3375int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003376 return sCameraService->updateAudioRestriction();
3377}
3378
3379int32_t CameraService::BasicClient::getAudioRestriction() const {
3380 Mutex::Autolock l(mAudioRestrictionLock);
3381 return mAudioRestriction;
3382}
3383
3384bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
3385 switch (mode) {
3386 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
3387 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
3388 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
3389 return true;
3390 default:
3391 return false;
3392 }
3393}
3394
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003395status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
3396 if (mode == AppOpsManager::MODE_ERRORED) {
3397 ALOGI("Camera %s: Access for \"%s\" has been revoked",
3398 mCameraIdStr.string(), String8(mClientPackageName).string());
3399 return PERMISSION_DENIED;
3400 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
3401 // If the calling Uid is trusted (a native service), the AppOpsManager could
3402 // return MODE_IGNORED. Do not treat such case as error.
3403 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
3404 mClientPackageName);
3405 bool isCameraPrivacyEnabled =
3406 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled(
3407 multiuser_get_user_id(mClientUid));
3408 if (!isUidActive || !isCameraPrivacyEnabled) {
3409 ALOGI("Camera %s: Access for \"%s\" has been restricted",
3410 mCameraIdStr.string(), String8(mClientPackageName).string());
3411 // Return the same error as for device policy manager rejection
3412 return -EACCES;
3413 }
3414 }
3415 return OK;
3416}
3417
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003418status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003419 ATRACE_CALL();
3420
Igor Murashkine6800ce2013-03-04 17:25:57 -08003421 {
3422 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003423 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08003424 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003425 if (mAppOpsManager != nullptr) {
3426 // Notify app ops that the camera is not available
3427 mOpsCallback = new OpsCallback(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003428 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
3429 mClientPackageName, mOpsCallback);
Igor Murashkine6800ce2013-03-04 17:25:57 -08003430
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003431 // Just check for camera acccess here on open - delay startOp until
3432 // camera frames start streaming in startCameraStreamingOps
3433 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
3434 mClientPackageName);
3435 status_t res = handleAppOpMode(mode);
3436 if (res != OK) {
3437 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003438 }
Svetoslav28e8ef72015-05-11 19:21:31 -07003439 }
3440
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003441 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003442
3443 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003444 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003445
Emilian Peev53722fa2019-02-22 17:47:20 -08003446 sCameraService->mUidPolicy->registerMonitorUid(mClientUid);
3447
Shuzhen Wang695044d2020-03-06 09:02:23 -08003448 // Notify listeners of camera open/close status
3449 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
3450
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003451 return OK;
3452}
3453
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003454status_t CameraService::BasicClient::startCameraStreamingOps() {
3455 ATRACE_CALL();
3456
3457 if (!mOpsActive) {
3458 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
3459 return INVALID_OPERATION;
3460 }
3461 if (mOpsStreaming) {
3462 ALOGV("%s: Streaming already active!", __FUNCTION__);
3463 return OK;
3464 }
3465
3466 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
3467 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
3468
3469 if (mAppOpsManager != nullptr) {
3470 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
3471 mClientPackageName, /*startIfModeDefault*/ false, mClientFeatureId,
3472 String16("start camera ") + String16(mCameraIdStr));
3473 status_t res = handleAppOpMode(mode);
3474 if (res != OK) {
3475 return res;
3476 }
3477 }
3478
3479 mOpsStreaming = true;
3480
3481 return OK;
3482}
3483
Valentin Iftimec0b8d472021-07-23 20:21:06 +02003484status_t CameraService::BasicClient::noteAppOp() {
3485 ATRACE_CALL();
3486
3487 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d",
3488 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
3489
3490 // noteAppOp is only used for when camera mute is not supported, in order
3491 // to trigger the sensor privacy "Unblock" dialog
3492 if (mAppOpsManager != nullptr) {
3493 int32_t mode = mAppOpsManager->noteOp(AppOpsManager::OP_CAMERA, mClientUid,
3494 mClientPackageName, mClientFeatureId,
3495 String16("start camera ") + String16(mCameraIdStr));
3496 status_t res = handleAppOpMode(mode);
3497 if (res != OK) {
3498 return res;
3499 }
3500 }
3501
3502 return OK;
3503}
3504
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003505status_t CameraService::BasicClient::finishCameraStreamingOps() {
3506 ATRACE_CALL();
3507
3508 if (!mOpsActive) {
3509 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
3510 return INVALID_OPERATION;
3511 }
3512 if (!mOpsStreaming) {
3513 ALOGV("%s: Streaming not active!", __FUNCTION__);
3514 return OK;
3515 }
3516
3517 if (mAppOpsManager != nullptr) {
3518 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
3519 mClientPackageName, mClientFeatureId);
3520 mOpsStreaming = false;
3521 }
3522
3523 return OK;
3524}
3525
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003526status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003527 ATRACE_CALL();
3528
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003529 if (mOpsStreaming) {
3530 // Make sure we've notified everyone about camera stopping
3531 finishCameraStreamingOps();
3532 }
3533
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003534 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003535 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003536 mOpsActive = false;
3537
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01003538 // This function is called when a client disconnects. This should
3539 // release the camera, but actually only if it was in a proper
3540 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003541 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01003542 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003543
Ruben Brunkcc776712015-02-17 20:18:47 -08003544 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003545 sCameraService->updateStatus(StatusInternal::PRESENT,
3546 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003547 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003548 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003549 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
3550 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08003551 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003552 mOpsCallback.clear();
3553
Emilian Peev53722fa2019-02-22 17:47:20 -08003554 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid);
3555
Shuzhen Wang695044d2020-03-06 09:02:23 -08003556 // Notify listeners of camera open/close status
3557 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
3558
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003559 return OK;
3560}
3561
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003562void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003563 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003564 if (mAppOpsManager == nullptr) {
3565 return;
3566 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003567 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003568 if (op != AppOpsManager::OP_CAMERA) {
3569 ALOGW("Unexpected app ops notification received: %d", op);
3570 return;
3571 }
3572
3573 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003574 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003575 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003576 ALOGV("checkOp returns: %d, %s ", res,
3577 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
3578 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
3579 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
3580 "UNKNOWN");
3581
Shuzhen Wang64900852021-02-05 09:03:29 -08003582 if (res == AppOpsManager::MODE_ERRORED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003583 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003584 String8(mClientPackageName).string());
Svet Ganova453d0d2018-01-11 15:37:58 -08003585 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08003586 } else if (res == AppOpsManager::MODE_IGNORED) {
3587 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Evan Severson09ab4002021-02-10 14:15:19 -08003588 bool isCameraPrivacyEnabled =
3589 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled(
3590 multiuser_get_user_id(mClientUid));
Shuzhen Wang64900852021-02-05 09:03:29 -08003591 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d",
3592 mCameraIdStr.string(), String8(mClientPackageName).string(),
3593 mUidIsTrusted, isUidActive);
3594 // If the calling Uid is trusted (a native service), or the client Uid is active (WAR for
3595 // b/175320666), the AppOpsManager could return MODE_IGNORED. Do not treat such cases as
3596 // error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02003597 if (!mUidIsTrusted) {
3598 if (isUidActive && isCameraPrivacyEnabled && supportsCameraMute()) {
3599 setCameraMute(true);
3600 } else if (!isUidActive
3601 || (isCameraPrivacyEnabled && !supportsCameraMute())) {
3602 block();
3603 }
Shuzhen Wang64900852021-02-05 09:03:29 -08003604 }
Evan Severson09ab4002021-02-10 14:15:19 -08003605 } else if (res == AppOpsManager::MODE_ALLOWED) {
3606 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003607 }
3608}
3609
Svet Ganova453d0d2018-01-11 15:37:58 -08003610void CameraService::BasicClient::block() {
3611 ATRACE_CALL();
3612
3613 // Reset the client PID to allow server-initiated disconnect,
3614 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003615 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08003616 CaptureResultExtras resultExtras; // a dummy result (invalid)
3617 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
3618 disconnect();
3619}
3620
Mathias Agopian65ab4712010-07-14 17:59:35 -07003621// ----------------------------------------------------------------------------
3622
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003623void CameraService::Client::notifyError(int32_t errorCode,
Jianing Weicb0652e2014-03-12 18:29:36 -07003624 const CaptureResultExtras& resultExtras) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08003625 (void) resultExtras;
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003626 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07003627 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
3628 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
3629 api1ErrorCode = CAMERA_ERROR_DISABLED;
3630 }
3631 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003632 } else {
3633 ALOGE("mRemoteCallback is NULL!!");
3634 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003635}
3636
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003637// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003638binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003639 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003640 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08003641}
3642
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003643bool CameraService::Client::canCastToApiClient(apiLevel level) const {
3644 return level == API_1;
3645}
3646
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003647CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
3648 mClient(client) {
3649}
3650
3651void CameraService::Client::OpsCallback::opChanged(int32_t op,
3652 const String16& packageName) {
3653 sp<BasicClient> client = mClient.promote();
3654 if (client != NULL) {
3655 client->opChanged(op, packageName);
3656 }
3657}
3658
Mathias Agopian65ab4712010-07-14 17:59:35 -07003659// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08003660// UidPolicy
3661// ----------------------------------------------------------------------------
3662
3663void CameraService::UidPolicy::registerSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003664 Mutex::Autolock _l(mUidLock);
3665
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003666 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07003667 status_t res = mAm.linkToDeath(this);
3668 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08003669 | ActivityManager::UID_OBSERVER_IDLE
Emilian Peev53722fa2019-02-22 17:47:20 -08003670 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganova453d0d2018-01-11 15:37:58 -08003671 ActivityManager::PROCESS_STATE_UNKNOWN,
3672 String16("cameraserver"));
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003673 if (res == OK) {
3674 mRegistered = true;
3675 ALOGV("UidPolicy: Registered with ActivityManager");
3676 }
Svet Ganova453d0d2018-01-11 15:37:58 -08003677}
3678
3679void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003680 Mutex::Autolock _l(mUidLock);
3681
Steven Moreland2f348142019-07-02 15:59:07 -07003682 mAm.unregisterUidObserver(this);
3683 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003684 mRegistered = false;
3685 mActiveUids.clear();
3686 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08003687}
3688
3689void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
3690 onUidIdle(uid, disabled);
3691}
3692
3693void CameraService::UidPolicy::onUidActive(uid_t uid) {
3694 Mutex::Autolock _l(mUidLock);
3695 mActiveUids.insert(uid);
3696}
3697
3698void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
3699 bool deleted = false;
3700 {
3701 Mutex::Autolock _l(mUidLock);
3702 if (mActiveUids.erase(uid) > 0) {
3703 deleted = true;
3704 }
3705 }
3706 if (deleted) {
3707 sp<CameraService> service = mService.promote();
3708 if (service != nullptr) {
3709 service->blockClientsForUid(uid);
3710 }
3711 }
3712}
3713
Emilian Peev53722fa2019-02-22 17:47:20 -08003714void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07003715 int64_t procStateSeq __unused, int32_t capability __unused) {
Emilian Peev53722fa2019-02-22 17:47:20 -08003716 bool procStateChange = false;
3717 {
3718 Mutex::Autolock _l(mUidLock);
3719 if ((mMonitoredUids.find(uid) != mMonitoredUids.end()) &&
3720 (mMonitoredUids[uid].first != procState)) {
3721 mMonitoredUids[uid].first = procState;
3722 procStateChange = true;
3723 }
3724 }
3725
3726 if (procStateChange) {
3727 sp<CameraService> service = mService.promote();
3728 if (service != nullptr) {
3729 service->notifyMonitoredUids();
3730 }
3731 }
3732}
3733
3734void CameraService::UidPolicy::registerMonitorUid(uid_t uid) {
3735 Mutex::Autolock _l(mUidLock);
3736 auto it = mMonitoredUids.find(uid);
3737 if (it != mMonitoredUids.end()) {
3738 it->second.second++;
3739 } else {
3740 mMonitoredUids.emplace(
3741 std::pair<uid_t, std::pair<int32_t, size_t>> (uid,
3742 std::pair<int32_t, size_t> (ActivityManager::PROCESS_STATE_NONEXISTENT, 1)));
3743 }
3744}
3745
3746void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid) {
3747 Mutex::Autolock _l(mUidLock);
3748 auto it = mMonitoredUids.find(uid);
3749 if (it != mMonitoredUids.end()) {
3750 it->second.second--;
3751 if (it->second.second == 0) {
3752 mMonitoredUids.erase(it);
3753 }
3754 } else {
3755 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
3756 }
3757}
3758
Svet Ganov7b4ab782018-03-25 12:48:10 -07003759bool CameraService::UidPolicy::isUidActive(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003760 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003761 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003762}
3763
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003764static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
3765static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003766
Svet Ganov7b4ab782018-03-25 12:48:10 -07003767bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003768 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003769 // If activity manager is unreachable, assume everything is active
3770 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003771 return true;
3772 }
3773 auto it = mOverrideUids.find(uid);
3774 if (it != mOverrideUids.end()) {
3775 return it->second;
3776 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003777 bool active = mActiveUids.find(uid) != mActiveUids.end();
3778 if (!active) {
3779 // We want active UIDs to always access camera with their first attempt since
3780 // there is no guarantee the app is robustly written and would retry getting
3781 // the camera on failure. The inverse case is not a problem as we would take
3782 // camera away soon once we get the callback that the uid is no longer active.
3783 ActivityManager am;
3784 // Okay to access with a lock held as UID changes are dispatched without
3785 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07003786 int64_t startTimeMillis = 0;
3787 do {
3788 // TODO: Fix this b/109950150!
3789 // Okay this is a hack. There is a race between the UID turning active and
3790 // activity being resumed. The proper fix is very risky, so we temporary add
3791 // some polling which should happen pretty rarely anyway as the race is hard
3792 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003793 active = mActiveUids.find(uid) != mActiveUids.end();
Hui Yu12c7ec72020-05-04 17:40:52 +00003794 if (!active) active = am.isUidActive(uid, callingPackage);
Svet Ganov94ec46f2018-06-08 15:03:46 -07003795 if (active) {
3796 break;
3797 }
3798 if (startTimeMillis <= 0) {
3799 startTimeMillis = uptimeMillis();
3800 }
3801 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003802 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003803 if (remainingTimeMillis <= 0) {
3804 break;
3805 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003806 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
3807
3808 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003809 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003810 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003811 } while (true);
3812
Svet Ganov7b4ab782018-03-25 12:48:10 -07003813 if (active) {
3814 // Now that we found out the UID is actually active, cache that
3815 mActiveUids.insert(uid);
3816 }
3817 }
3818 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08003819}
3820
Varun Shahb42f1eb2019-04-16 14:45:13 -07003821int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
3822 Mutex::Autolock _l(mUidLock);
3823 return getProcStateLocked(uid);
3824}
3825
3826int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
3827 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
3828 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
3829 procState = mMonitoredUids[uid].first;
3830 }
3831 return procState;
3832}
3833
Svet Ganov7b4ab782018-03-25 12:48:10 -07003834void CameraService::UidPolicy::UidPolicy::addOverrideUid(uid_t uid,
3835 String16 callingPackage, bool active) {
3836 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08003837}
3838
Svet Ganov7b4ab782018-03-25 12:48:10 -07003839void CameraService::UidPolicy::removeOverrideUid(uid_t uid, String16 callingPackage) {
3840 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08003841}
3842
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003843void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
3844 Mutex::Autolock _l(mUidLock);
3845 ALOGV("UidPolicy: ActivityManager has died");
3846 mRegistered = false;
3847 mActiveUids.clear();
3848}
3849
Svet Ganov7b4ab782018-03-25 12:48:10 -07003850void CameraService::UidPolicy::updateOverrideUid(uid_t uid, String16 callingPackage,
3851 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003852 bool wasActive = false;
3853 bool isActive = false;
3854 {
3855 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003856 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003857 mOverrideUids.erase(uid);
3858 if (insert) {
3859 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
3860 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003861 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003862 }
3863 if (wasActive != isActive && !isActive) {
3864 sp<CameraService> service = mService.promote();
3865 if (service != nullptr) {
3866 service->blockClientsForUid(uid);
3867 }
3868 }
3869}
3870
3871// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08003872// SensorPrivacyPolicy
3873// ----------------------------------------------------------------------------
3874void CameraService::SensorPrivacyPolicy::registerSelf() {
3875 Mutex::Autolock _l(mSensorPrivacyLock);
3876 if (mRegistered) {
3877 return;
3878 }
Evan Severson09ab4002021-02-10 14:15:19 -08003879 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08003880 mSpm.addSensorPrivacyListener(this);
3881 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
3882 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003883 if (res == OK) {
3884 mRegistered = true;
3885 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
3886 }
3887}
3888
3889void CameraService::SensorPrivacyPolicy::unregisterSelf() {
3890 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08003891 mSpm.removeSensorPrivacyListener(this);
3892 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003893 mRegistered = false;
3894 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
3895}
3896
3897bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
3898 Mutex::Autolock _l(mSensorPrivacyLock);
3899 return mSensorPrivacyEnabled;
3900}
3901
Evan Severson09ab4002021-02-10 14:15:19 -08003902bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled(userid_t userId) {
3903 if (!hasCameraPrivacyFeature()) {
3904 return false;
3905 }
3906 return mSpm.isIndividualSensorPrivacyEnabled(userId,
3907 SensorPrivacyManager::INDIVIDUAL_SENSOR_CAMERA);
3908}
3909
Michael Grooverd1d435a2018-12-18 17:39:42 -08003910binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
3911 {
3912 Mutex::Autolock _l(mSensorPrivacyLock);
3913 mSensorPrivacyEnabled = enabled;
3914 }
3915 // if sensor privacy is enabled then block all clients from accessing the camera
Evan Severson09ab4002021-02-10 14:15:19 -08003916 if (enabled) {
3917 sp<CameraService> service = mService.promote();
3918 if (service != nullptr) {
3919 service->blockAllClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08003920 }
3921 }
3922 return binder::Status::ok();
3923}
3924
3925void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
3926 Mutex::Autolock _l(mSensorPrivacyLock);
3927 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
3928 mRegistered = false;
3929}
3930
Evan Severson09ab4002021-02-10 14:15:19 -08003931bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Severson671806e2021-04-20 16:44:53 -07003932 return mSpm.supportsSensorToggle(SensorPrivacyManager::INDIVIDUAL_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08003933}
3934
Michael Grooverd1d435a2018-12-18 17:39:42 -08003935// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003936// CameraState
3937// ----------------------------------------------------------------------------
3938
3939CameraService::CameraState::CameraState(const String8& id, int cost,
Shuzhen Wang403af6d2021-12-21 00:08:43 +00003940 const std::set<String8>& conflicting, SystemCameraKind systemCameraKind,
3941 const std::vector<std::string>& physicalCameras) : mId(id),
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003942 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
Shuzhen Wang403af6d2021-12-21 00:08:43 +00003943 mSystemCameraKind(systemCameraKind), mPhysicalCameras(physicalCameras) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08003944
3945CameraService::CameraState::~CameraState() {}
3946
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003947CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003948 Mutex::Autolock lock(mStatusLock);
3949 return mStatus;
3950}
3951
Shuzhen Wang43858162020-01-10 13:42:15 -08003952std::vector<String8> CameraService::CameraState::getUnavailablePhysicalIds() const {
3953 Mutex::Autolock lock(mStatusLock);
3954 std::vector<String8> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
3955 return res;
3956}
3957
Ruben Brunkcc776712015-02-17 20:18:47 -08003958CameraParameters CameraService::CameraState::getShimParams() const {
3959 return mShimParams;
3960}
3961
3962void CameraService::CameraState::setShimParams(const CameraParameters& params) {
3963 mShimParams = params;
3964}
3965
3966int CameraService::CameraState::getCost() const {
3967 return mCost;
3968}
3969
3970std::set<String8> CameraService::CameraState::getConflicting() const {
3971 return mConflicting;
3972}
3973
3974String8 CameraService::CameraState::getId() const {
3975 return mId;
3976}
3977
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003978SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
3979 return mSystemCameraKind;
3980}
3981
Shuzhen Wang403af6d2021-12-21 00:08:43 +00003982bool CameraService::CameraState::containsPhysicalCamera(const std::string& physicalCameraId) const {
3983 return std::find(mPhysicalCameras.begin(), mPhysicalCameras.end(), physicalCameraId)
3984 != mPhysicalCameras.end();
3985}
3986
Shuzhen Wang43858162020-01-10 13:42:15 -08003987bool CameraService::CameraState::addUnavailablePhysicalId(const String8& physicalId) {
3988 Mutex::Autolock lock(mStatusLock);
3989 auto result = mUnavailablePhysicalIds.insert(physicalId);
3990 return result.second;
3991}
3992
3993bool CameraService::CameraState::removeUnavailablePhysicalId(const String8& physicalId) {
3994 Mutex::Autolock lock(mStatusLock);
3995 auto count = mUnavailablePhysicalIds.erase(physicalId);
3996 return count > 0;
3997}
3998
Shuzhen Wange7aa0342021-08-03 11:29:47 -07003999void CameraService::CameraState::setClientPackage(const String8& clientPackage) {
4000 Mutex::Autolock lock(mStatusLock);
4001 mClientPackage = clientPackage;
4002}
4003
4004String8 CameraService::CameraState::getClientPackage() const {
4005 Mutex::Autolock lock(mStatusLock);
4006 return mClientPackage;
4007}
4008
Ruben Brunkcc776712015-02-17 20:18:47 -08004009// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07004010// ClientEventListener
4011// ----------------------------------------------------------------------------
4012
4013void CameraService::ClientEventListener::onClientAdded(
4014 const resource_policy::ClientDescriptor<String8,
4015 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07004016 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07004017 if (basicClient.get() != nullptr) {
4018 BatteryNotifier& notifier(BatteryNotifier::getInstance());
4019 notifier.noteStartCamera(descriptor.getKey(),
4020 static_cast<int>(basicClient->getClientUid()));
4021 }
4022}
4023
4024void CameraService::ClientEventListener::onClientRemoved(
4025 const resource_policy::ClientDescriptor<String8,
4026 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07004027 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07004028 if (basicClient.get() != nullptr) {
4029 BatteryNotifier& notifier(BatteryNotifier::getInstance());
4030 notifier.noteStopCamera(descriptor.getKey(),
4031 static_cast<int>(basicClient->getClientUid()));
4032 }
4033}
4034
4035
4036// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08004037// CameraClientManager
4038// ----------------------------------------------------------------------------
4039
Ruben Brunk99e69712015-05-26 17:25:07 -07004040CameraService::CameraClientManager::CameraClientManager() {
4041 setListener(std::make_shared<ClientEventListener>());
4042}
4043
Ruben Brunkcc776712015-02-17 20:18:47 -08004044CameraService::CameraClientManager::~CameraClientManager() {}
4045
4046sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
4047 const String8& id) const {
4048 auto descriptor = get(id);
4049 if (descriptor == nullptr) {
4050 return sp<BasicClient>{nullptr};
4051 }
4052 return descriptor->getValue();
4053}
4054
4055String8 CameraService::CameraClientManager::toString() const {
4056 auto all = getAll();
4057 String8 ret("[");
4058 bool hasAny = false;
4059 for (auto& i : all) {
4060 hasAny = true;
4061 String8 key = i->getKey();
4062 int32_t cost = i->getCost();
4063 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00004064 int32_t score = i->getPriority().getScore();
4065 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08004066 auto conflicting = i->getConflicting();
4067 auto clientSp = i->getValue();
4068 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07004069 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08004070 if (clientSp.get() != nullptr) {
4071 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07004072 uid_t clientUid = clientSp->getClientUid();
4073 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08004074 }
Emilian Peev8131a262017-02-01 12:33:43 +00004075 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
4076 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08004077
Ruben Brunk6267b532015-04-30 17:44:07 -07004078 if (clientSp.get() != nullptr) {
4079 ret.appendFormat("User Id: %d, ", clientUserId);
4080 }
Ruben Brunkcc776712015-02-17 20:18:47 -08004081 if (packageName.size() != 0) {
4082 ret.appendFormat("Client Package Name: %s", packageName.string());
4083 }
4084
4085 ret.append(", Conflicting Client Devices: {");
4086 for (auto& j : conflicting) {
4087 ret.appendFormat("%s, ", j.string());
4088 }
4089 ret.append("})");
4090 }
4091 if (hasAny) ret.append("\n");
4092 ret.append("]\n");
4093 return ret;
4094}
4095
4096CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
4097 const String8& key, const sp<BasicClient>& value, int32_t cost,
Emilian Peev8131a262017-02-01 12:33:43 +00004098 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00004099 int32_t state, int32_t oomScoreOffset) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004100
Steven Moreland89a2c5c2020-01-31 15:02:25 -08004101 bool isVendorClient = getCurrentServingCall() == BinderCallType::HWBINDER;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07004102 int32_t score_adj = isVendorClient ? kVendorClientScore : score;
4103 int32_t state_adj = isVendorClient ? kVendorClientState: state;
4104
Ruben Brunkcc776712015-02-17 20:18:47 -08004105 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00004106 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj, isVendorClient,
4107 oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08004108}
4109
4110CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00004111 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
4112 int32_t oomScoreOffset) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004113 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00004114 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00004115 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08004116}
4117
4118// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08004119// InjectionStatusListener
4120// ----------------------------------------------------------------------------
4121
4122void CameraService::InjectionStatusListener::addListener(
4123 const sp<ICameraInjectionCallback>& callback) {
4124 Mutex::Autolock lock(mListenerLock);
4125 if (mCameraInjectionCallback) return;
4126 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
4127 if (res == OK) {
4128 mCameraInjectionCallback = callback;
4129 }
4130}
4131
4132void CameraService::InjectionStatusListener::removeListener() {
4133 Mutex::Autolock lock(mListenerLock);
4134 if (mCameraInjectionCallback == nullptr) {
4135 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
4136 return;
4137 }
4138 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
4139 mCameraInjectionCallback = nullptr;
4140}
4141
4142void CameraService::InjectionStatusListener::notifyInjectionError(
Cliff Wud3a05312021-04-26 23:07:31 +08004143 String8 injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08004144 if (mCameraInjectionCallback == nullptr) {
4145 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
4146 return;
4147 }
Cliff Wud3a05312021-04-26 23:07:31 +08004148
4149 switch (err) {
4150 case -ENODEV:
4151 mCameraInjectionCallback->onInjectionError(
4152 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4153 ALOGE("No camera device with ID \"%s\" currently available!",
4154 injectedCamId.string());
4155 break;
4156 case -EBUSY:
4157 mCameraInjectionCallback->onInjectionError(
4158 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4159 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
4160 injectedCamId.string());
4161 break;
4162 case DEAD_OBJECT:
4163 mCameraInjectionCallback->onInjectionError(
4164 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4165 ALOGE("Camera ID \"%s\" object is dead!",
4166 injectedCamId.string());
4167 break;
4168 case INVALID_OPERATION:
4169 mCameraInjectionCallback->onInjectionError(
4170 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4171 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
4172 injectedCamId.string());
4173 break;
4174 case UNKNOWN_TRANSACTION:
4175 mCameraInjectionCallback->onInjectionError(
4176 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
4177 ALOGE("Camera ID \"%s\" method doesn't support!",
4178 injectedCamId.string());
4179 break;
4180 default:
4181 mCameraInjectionCallback->onInjectionError(
4182 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
4183 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
4184 strerror(-err), err, injectedCamId.string());
4185 }
Cliff Wud8cae102021-03-11 01:37:42 +08004186}
4187
4188void CameraService::InjectionStatusListener::binderDied(
4189 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08004190 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
4191 auto parent = mParent.promote();
4192 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08004193 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
4194 if (clientDescriptor != nullptr) {
4195 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
4196 baseClientPtr->stopInjection();
4197 }
Cliff Wu3b268182021-07-06 15:44:43 +08004198 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08004199 }
4200}
4201
4202// ----------------------------------------------------------------------------
4203// CameraInjectionSession
4204// ----------------------------------------------------------------------------
4205
4206binder::Status CameraService::CameraInjectionSession::stopInjection() {
4207 Mutex::Autolock lock(mInjectionSessionLock);
4208 auto parent = mParent.promote();
4209 if (parent == nullptr) {
4210 ALOGE("CameraInjectionSession: Parent is gone");
4211 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
4212 "Camera service encountered error");
4213 }
Cliff Wud3a05312021-04-26 23:07:31 +08004214
4215 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08004216 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
4217 if (clientDescriptor != nullptr) {
4218 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
4219 res = baseClientPtr->stopInjection();
4220 if (res != OK) {
4221 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
4222 " ret != NO_ERROR: %d", res);
4223 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
4224 "Camera session encountered error");
4225 }
4226 }
Cliff Wu3b268182021-07-06 15:44:43 +08004227 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08004228 return binder::Status::ok();
4229}
4230
4231// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07004232
4233static const int kDumpLockRetries = 50;
4234static const int kDumpLockSleep = 60000;
4235
4236static bool tryLock(Mutex& mutex)
4237{
4238 bool locked = false;
4239 for (int i = 0; i < kDumpLockRetries; ++i) {
4240 if (mutex.tryLock() == NO_ERROR) {
4241 locked = true;
4242 break;
4243 }
4244 usleep(kDumpLockSleep);
4245 }
4246 return locked;
4247}
4248
Rucha Katakwardf223072021-06-15 10:21:00 -07004249void CameraService::cacheDump() {
4250 if (mMemFd != -1) {
4251 const Vector<String16> args;
4252 ATRACE_CALL();
4253 // Acquiring service lock here will avoid the deadlock since
4254 // cacheDump will not be called during the second disconnect.
4255 Mutex::Autolock lock(mServiceLock);
4256
4257 Mutex::Autolock l(mCameraStatesLock);
4258 // Start collecting the info for open sessions and store it in temp file.
4259 for (const auto& state : mCameraStates) {
4260 String8 cameraId = state.first;
4261 auto clientDescriptor = mActiveClientManager.get(cameraId);
4262 if (clientDescriptor != nullptr) {
4263 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.string());
4264 // Log the current open session info before device is disconnected.
4265 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
4266 }
4267 }
4268 }
4269}
4270
Mathias Agopian65ab4712010-07-14 17:59:35 -07004271status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004272 ATRACE_CALL();
4273
Jayant Chowdhary5216b212019-07-17 09:26:23 -07004274 if (checkCallingPermission(sDumpPermission) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004275 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07004276 CameraThreadState::getCallingPid(),
4277 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004278 return NO_ERROR;
4279 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004280 bool locked = tryLock(mServiceLock);
4281 // failed to lock - CameraService is probably deadlocked
4282 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004283 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004284 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004285
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004286 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004287 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07004288
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004289 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004290 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08004291
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004292 if (locked) mServiceLock.unlock();
4293 return NO_ERROR;
4294 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004295 dprintf(fd, "\n== Service global info: ==\n\n");
4296 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004297 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07004298 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
4299 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004300 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
4301 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
4302 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004303 String8 activeClientString = mActiveClientManager.toString();
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004304 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
4305 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004306
4307 dumpEventLog(fd);
4308
4309 bool stateLocked = tryLock(mCameraStatesLock);
4310 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004311 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004312 }
4313
Emilian Peevbd8c5032018-02-14 23:05:40 +00004314 int argSize = args.size();
4315 for (int i = 0; i < argSize; i++) {
4316 if (args[i] == TagMonitor::kMonitorOption) {
4317 if (i + 1 < argSize) {
4318 mMonitorTags = String8(args[i + 1]);
4319 }
4320 break;
4321 }
4322 }
4323
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004324 for (auto& state : mCameraStates) {
4325 String8 cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004326
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004327 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004328
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004329 CameraParameters p = state.second->getShimParams();
4330 if (!p.isEmpty()) {
4331 dprintf(fd, " Camera1 API shim is using parameters:\n ");
4332 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004333 }
4334
4335 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08004336 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07004337 // log the current open session info
4338 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08004339 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07004340 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004341 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004342
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004343 }
4344
4345 if (stateLocked) mCameraStatesLock.unlock();
4346
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004347 if (locked) mServiceLock.unlock();
4348
Emilian Peevf53f66e2017-04-11 14:29:43 +01004349 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004350
4351 dprintf(fd, "\n== Vendor tags: ==\n\n");
4352
4353 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
4354 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00004355 sp<VendorTagDescriptorCache> cache =
4356 VendorTagDescriptorCache::getGlobalVendorTagCache();
4357 if (cache == NULL) {
4358 dprintf(fd, "No vendor tags.\n");
4359 } else {
4360 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
4361 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004362 } else {
4363 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
4364 }
4365
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004366 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004367 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004368 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004369
4370 // Process dump arguments, if any
4371 int n = args.size();
4372 String16 verboseOption("-v");
4373 String16 unreachableOption("--unreachable");
4374 for (int i = 0; i < n; i++) {
4375 if (args[i] == verboseOption) {
4376 // change logging level
4377 if (i + 1 >= n) continue;
4378 String8 levelStr(args[i+1]);
4379 int level = atoi(levelStr.string());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004380 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004381 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004382 } else if (args[i] == unreachableOption) {
4383 // Dump memory analysis
4384 // TODO - should limit be an argument parameter?
4385 UnreachableMemoryInfo info;
4386 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
4387 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004388 dprintf(fd, "\n== Unable to dump unreachable memory. "
4389 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004390 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004391 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004392 std::string s = info.ToString(/*log_contents*/ true);
4393 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004394 }
4395 }
4396 }
Rucha Katakwardf223072021-06-15 10:21:00 -07004397
4398 bool serviceLocked = tryLock(mServiceLock);
4399
4400 // Dump info from previous open sessions.
4401 // Reposition the offset to beginning of the file before reading
4402
4403 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
4404 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
4405 ssize_t size_read;
4406 char buf[4096];
4407 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
4408 // Read data from file to a small buffer and write it to fd.
4409 write(fd, buf, size_read);
4410 if (size_read == -1) {
4411 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
4412 break;
4413 }
4414 }
4415 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
4416 } else {
4417 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
4418 }
4419
4420 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004421 return NO_ERROR;
4422}
4423
Rucha Katakwardf223072021-06-15 10:21:00 -07004424void CameraService::dumpOpenSessionClientLogs(int fd,
4425 const Vector<String16>& args, const String8& cameraId) {
4426 auto clientDescriptor = mActiveClientManager.get(cameraId);
4427 dprintf(fd, " Device %s is open. Client instance dump:\n",
4428 cameraId.string());
4429 dprintf(fd, " Client priority score: %d state: %d\n",
4430 clientDescriptor->getPriority().getScore(),
4431 clientDescriptor->getPriority().getState());
4432 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
4433
4434 auto client = clientDescriptor->getValue();
4435 dprintf(fd, " Client package: %s\n",
4436 String8(client->getPackageName()).string());
4437
4438 client->dumpClient(fd, args);
4439}
4440
4441void CameraService::dumpClosedSessionClientLogs(int fd, const String8& cameraId) {
4442 dprintf(fd, " Device %s is closed, no client instance\n",
4443 cameraId.string());
4444}
4445
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004446void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004447 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004448
4449 Mutex::Autolock l(mLogLock);
4450 for (const auto& msg : mEventLog) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004451 dprintf(fd, " %s\n", msg.string());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004452 }
4453
4454 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004455 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004456 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004457 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004458 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004459 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004460}
4461
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004462void CameraService::cacheClientTagDumpIfNeeded(const char *cameraId, BasicClient* client) {
4463 Mutex::Autolock lock(mLogLock);
4464 if (!isClientWatchedLocked(client)) { return; }
4465
4466 std::vector<std::string> dumpVector;
4467 client->dumpWatchedEventsToVector(dumpVector);
4468
4469 if (dumpVector.empty()) { return; }
4470
Avichal Rakesh882c08b2021-12-09 17:47:07 -08004471 std::string dumpString;
4472
4473 String8 currentTime = getFormattedCurrentTime();
4474 dumpString += "Cached @ ";
4475 dumpString += currentTime.string();
4476 dumpString += "\n"; // First line is the timestamp of when client is cached.
4477
4478
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08004479 const String16 &packageName = client->getPackageName();
4480
4481 String8 packageName8 = String8(packageName);
4482 const char *printablePackageName = packageName8.lockBuffer(packageName.size());
4483
Avichal Rakesh882c08b2021-12-09 17:47:07 -08004484
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004485 size_t i = dumpVector.size();
4486
4487 // Store the string in reverse order (latest last)
4488 while (i > 0) {
4489 i--;
4490 dumpString += cameraId;
4491 dumpString += ":";
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08004492 dumpString += printablePackageName;
4493 dumpString += " ";
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004494 dumpString += dumpVector[i]; // implicitly ends with '\n'
4495 }
4496
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08004497 packageName8.unlockBuffer();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004498 mWatchedClientsDumpCache[packageName] = dumpString;
4499}
4500
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004501void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004502 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004503 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
4504 if (mTorchClientMap[i] == who) {
4505 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004506 String8 cameraId = mTorchClientMap.keyAt(i);
4507 status_t res = mFlashlight->setTorchMode(cameraId, false);
4508 if (res) {
4509 ALOGE("%s: torch client died but couldn't turn off torch: "
4510 "%s (%d)", __FUNCTION__, strerror(-res), res);
4511 return;
4512 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004513 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004514 break;
4515 }
4516 }
4517}
4518
Ruben Brunkcc776712015-02-17 20:18:47 -08004519/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07004520
Igor Murashkin294d0ec2012-10-05 10:44:57 -07004521 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07004522 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
4523 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07004524 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08004525 // PID here is approximate and can be wrong.
Jayant Chowdhary12361932018-08-27 14:46:13 -07004526 logClientDied(CameraThreadState::getCallingPid(), String8("Binder died unexpectedly"));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004527
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004528 // check torch client
4529 handleTorchClientBinderDied(who);
4530
4531 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08004532 if(!evictClientIdByRemote(who)) {
4533 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07004534 return;
4535 }
4536
Ruben Brunkcc776712015-02-17 20:18:47 -08004537 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
4538 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07004539}
4540
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004541void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004542 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08004543}
4544
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004545void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
4546 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004547 // Do not lock mServiceLock here or can get into a deadlock from
4548 // connect() -> disconnect -> updateStatus
4549
4550 auto state = getCameraState(cameraId);
4551
4552 if (state == nullptr) {
4553 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
4554 cameraId.string());
4555 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07004556 }
4557
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004558 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
4559 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
4560 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
4561 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
4562 return;
4563 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004564
4565 // Collect the logical cameras without holding mStatusLock in updateStatus
4566 // as that can lead to a deadlock(b/162192331).
4567 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08004568 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08004569 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07004570 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004571 &logicalCameraIds]
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004572 (const String8& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004573
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004574 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004575 // Update torch status if it has a flash unit.
4576 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004577 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004578 if (getTorchStatusLocked(cameraId, &torchStatus) !=
4579 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004580 TorchModeStatus newTorchStatus =
4581 status == StatusInternal::PRESENT ?
4582 TorchModeStatus::AVAILABLE_OFF :
4583 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004584 if (torchStatus != newTorchStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07004585 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004586 }
4587 }
Ruben Brunkcc776712015-02-17 20:18:47 -08004588 }
4589
4590 Mutex::Autolock lock(mStatusListenerLock);
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004591 notifyPhysicalCameraStatusLocked(mapToInterface(status), String16(cameraId),
4592 logicalCameraIds, deviceKind);
Shuzhen Wang43858162020-01-10 13:42:15 -08004593
Ruben Brunkcc776712015-02-17 20:18:47 -08004594 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07004595 bool isVendorListener = listener->isVendorListener();
4596 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
4597 listener->getListenerPid(), listener->getListenerUid()) ||
Shuzhen Wangb8259792021-05-27 09:27:06 -07004598 isVendorListener) {
4599 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07004600 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08004601 continue;
4602 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07004603 listener->getListener()->onStatusChanged(mapToInterface(status),
Emilian Peev53722fa2019-02-22 17:47:20 -08004604 String16(cameraId));
Ruben Brunkcc776712015-02-17 20:18:47 -08004605 }
4606 });
Igor Murashkincba2c162013-03-20 15:56:31 -07004607}
4608
Shuzhen Wang695044d2020-03-06 09:02:23 -08004609void CameraService::updateOpenCloseStatus(const String8& cameraId, bool open,
4610 const String16& clientPackageName) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07004611 auto state = getCameraState(cameraId);
4612 if (state == nullptr) {
4613 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
4614 cameraId.string());
4615 return;
4616 }
4617 if (open) {
4618 state->setClientPackage(String8(clientPackageName));
4619 } else {
4620 state->setClientPackage(String8::empty());
4621 }
4622
Shuzhen Wang695044d2020-03-06 09:02:23 -08004623 Mutex::Autolock lock(mStatusListenerLock);
4624
4625 for (const auto& it : mListenerList) {
4626 if (!it->isOpenCloseCallbackAllowed()) {
4627 continue;
4628 }
4629
4630 binder::Status ret;
4631 String16 cameraId64(cameraId);
4632 if (open) {
4633 ret = it->getListener()->onCameraOpened(cameraId64, clientPackageName);
4634 } else {
4635 ret = it->getListener()->onCameraClosed(cameraId64);
4636 }
4637 if (!ret.isOk()) {
4638 ALOGE("%s: Failed to trigger onCameraOpened/onCameraClosed callback: %d", __FUNCTION__,
4639 ret.exceptionCode());
4640 }
4641 }
4642}
4643
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004644template<class Func>
4645void CameraService::CameraState::updateStatus(StatusInternal status,
4646 const String8& cameraId,
4647 std::initializer_list<StatusInternal> rejectSourceStates,
4648 Func onStatusUpdatedLocked) {
4649 Mutex::Autolock lock(mStatusLock);
4650 StatusInternal oldStatus = mStatus;
4651 mStatus = status;
4652
4653 if (oldStatus == status) {
4654 return;
4655 }
4656
4657 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
4658 cameraId.string(), oldStatus, status);
4659
4660 if (oldStatus == StatusInternal::NOT_PRESENT &&
4661 (status != StatusInternal::PRESENT &&
4662 status != StatusInternal::ENUMERATING)) {
4663
4664 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
4665 __FUNCTION__);
4666 mStatus = oldStatus;
4667 return;
4668 }
4669
4670 /**
4671 * Sometimes we want to conditionally do a transition.
4672 * For example if a client disconnects, we want to go to PRESENT
4673 * only if we weren't already in NOT_PRESENT or ENUMERATING.
4674 */
4675 for (auto& rejectStatus : rejectSourceStates) {
4676 if (oldStatus == rejectStatus) {
4677 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
4678 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
4679 mStatus = oldStatus;
4680 return;
4681 }
4682 }
4683
4684 onStatusUpdatedLocked(cameraId, status);
4685}
4686
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004687status_t CameraService::getTorchStatusLocked(
4688 const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004689 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004690 if (!status) {
4691 return BAD_VALUE;
4692 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004693 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
4694 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004695 // invalid camera ID or the camera doesn't have a flash unit
4696 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004697 }
4698
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004699 *status = mTorchStatusMap.valueAt(index);
4700 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004701}
4702
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004703status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004704 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004705 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
4706 if (index == NAME_NOT_FOUND) {
4707 return BAD_VALUE;
4708 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004709 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004710
4711 return OK;
4712}
4713
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004714std::list<String16> CameraService::getLogicalCameras(
4715 const String8& physicalCameraId) {
4716 std::list<String16> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08004717 Mutex::Autolock lock(mCameraStatesLock);
4718 for (const auto& state : mCameraStates) {
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004719 if (state.second->containsPhysicalCamera(physicalCameraId.c_str())) {
4720 retList.emplace_back(String16(state.first));
Shuzhen Wang43858162020-01-10 13:42:15 -08004721 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004722 }
4723 return retList;
4724}
4725
4726void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
4727 const String16& physicalCameraId, const std::list<String16>& logicalCameraIds,
4728 SystemCameraKind deviceKind) {
4729 // mStatusListenerLock is expected to be locked
4730 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08004731 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004732 // Note: we check only the deviceKind of the physical camera id
4733 // since, logical camera ids and their physical camera ids are
4734 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07004735 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
4736 listener->getListenerPid(), listener->getListenerUid())) {
4737 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004738 String8(physicalCameraId).c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07004739 continue;
4740 }
Shuzhen Wang43858162020-01-10 13:42:15 -08004741 listener->getListener()->onPhysicalCameraStatusChanged(status,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004742 logicalCameraId, physicalCameraId);
Shuzhen Wang43858162020-01-10 13:42:15 -08004743 }
4744 }
4745}
4746
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004747
Svet Ganova453d0d2018-01-11 15:37:58 -08004748void CameraService::blockClientsForUid(uid_t uid) {
4749 const auto clients = mActiveClientManager.getAll();
4750 for (auto& current : clients) {
4751 if (current != nullptr) {
4752 const auto basicClient = current->getValue();
4753 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
4754 basicClient->block();
4755 }
4756 }
4757 }
4758}
4759
Michael Grooverd1d435a2018-12-18 17:39:42 -08004760void CameraService::blockAllClients() {
4761 const auto clients = mActiveClientManager.getAll();
4762 for (auto& current : clients) {
4763 if (current != nullptr) {
4764 const auto basicClient = current->getValue();
4765 if (basicClient.get() != nullptr) {
4766 basicClient->block();
4767 }
4768 }
4769 }
4770}
4771
Svet Ganova453d0d2018-01-11 15:37:58 -08004772// NOTE: This is a remote API - make sure all args are validated
4773status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
4774 if (!checkCallingPermission(sManageCameraPermission, nullptr, nullptr)) {
4775 return PERMISSION_DENIED;
4776 }
4777 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
4778 return BAD_VALUE;
4779 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004780 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004781 return handleSetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07004782 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004783 return handleResetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07004784 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004785 return handleGetUidState(args, out, err);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004786 } else if (args.size() >= 2 && args[0] == String16("set-rotate-and-crop")) {
4787 return handleSetRotateAndCrop(args);
4788 } else if (args.size() >= 1 && args[0] == String16("get-rotate-and-crop")) {
4789 return handleGetRotateAndCrop(out);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004790 } else if (args.size() >= 2 && args[0] == String16("set-image-dump-mask")) {
4791 return handleSetImageDumpMask(args);
4792 } else if (args.size() >= 1 && args[0] == String16("get-image-dump-mask")) {
4793 return handleGetImageDumpMask(out);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004794 } else if (args.size() >= 2 && args[0] == String16("set-camera-mute")) {
4795 return handleSetCameraMute(args);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004796 } else if (args.size() >= 2 && args[0] == String16("watch")) {
Avichal Rakesh84147132021-11-11 17:47:11 -08004797 return handleWatchCommand(args, in, out);
Svet Ganova453d0d2018-01-11 15:37:58 -08004798 } else if (args.size() == 1 && args[0] == String16("help")) {
4799 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004800 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08004801 }
4802 printHelp(err);
4803 return BAD_VALUE;
4804}
4805
4806status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004807 String16 packageName = args[1];
4808
Svet Ganova453d0d2018-01-11 15:37:58 -08004809 bool active = false;
4810 if (args[2] == String16("active")) {
4811 active = true;
4812 } else if ((args[2] != String16("idle"))) {
4813 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
4814 return BAD_VALUE;
4815 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004816
4817 int userId = 0;
4818 if (args.size() >= 5 && args[3] == String16("--user")) {
4819 userId = atoi(String8(args[4]));
4820 }
4821
4822 uid_t uid;
4823 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
4824 return BAD_VALUE;
4825 }
4826
4827 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08004828 return NO_ERROR;
4829}
4830
4831status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004832 String16 packageName = args[1];
4833
4834 int userId = 0;
4835 if (args.size() >= 4 && args[2] == String16("--user")) {
4836 userId = atoi(String8(args[3]));
4837 }
4838
4839 uid_t uid;
4840 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004841 return BAD_VALUE;
4842 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004843
4844 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08004845 return NO_ERROR;
4846}
4847
4848status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004849 String16 packageName = args[1];
4850
4851 int userId = 0;
4852 if (args.size() >= 4 && args[2] == String16("--user")) {
4853 userId = atoi(String8(args[3]));
4854 }
4855
4856 uid_t uid;
4857 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004858 return BAD_VALUE;
4859 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004860
4861 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004862 return dprintf(out, "active\n");
4863 } else {
4864 return dprintf(out, "idle\n");
4865 }
4866}
4867
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004868status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
4869 int rotateValue = atoi(String8(args[1]));
4870 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
4871 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
4872 Mutex::Autolock lock(mServiceLock);
4873
4874 mOverrideRotateAndCropMode = rotateValue;
4875
4876 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
4877
4878 const auto clients = mActiveClientManager.getAll();
4879 for (auto& current : clients) {
4880 if (current != nullptr) {
4881 const auto basicClient = current->getValue();
4882 if (basicClient.get() != nullptr) {
4883 basicClient->setRotateAndCropOverride(rotateValue);
4884 }
4885 }
4886 }
4887
4888 return OK;
4889}
4890
4891status_t CameraService::handleGetRotateAndCrop(int out) {
4892 Mutex::Autolock lock(mServiceLock);
4893
4894 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
4895}
4896
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004897status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
4898 char *endPtr;
4899 errno = 0;
4900 String8 maskString8 = String8(args[1]);
4901 long maskValue = strtol(maskString8.c_str(), &endPtr, 10);
4902
4903 if (errno != 0) return BAD_VALUE;
4904 if (endPtr != maskString8.c_str() + maskString8.size()) return BAD_VALUE;
4905 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
4906
4907 Mutex::Autolock lock(mServiceLock);
4908
4909 mImageDumpMask = maskValue;
4910
4911 return OK;
4912}
4913
4914status_t CameraService::handleGetImageDumpMask(int out) {
4915 Mutex::Autolock lock(mServiceLock);
4916
4917 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
4918}
4919
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004920status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
4921 int muteValue = strtol(String8(args[1]), nullptr, 10);
4922 if (errno != 0) return BAD_VALUE;
4923
4924 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
4925 Mutex::Autolock lock(mServiceLock);
4926
4927 mOverrideCameraMuteMode = (muteValue == 1);
4928
4929 const auto clients = mActiveClientManager.getAll();
4930 for (auto& current : clients) {
4931 if (current != nullptr) {
4932 const auto basicClient = current->getValue();
4933 if (basicClient.get() != nullptr) {
4934 if (basicClient->supportsCameraMute()) {
4935 basicClient->setCameraMute(mOverrideCameraMuteMode);
4936 }
4937 }
4938 }
4939 }
4940
4941 return OK;
4942}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004943
Avichal Rakesh84147132021-11-11 17:47:11 -08004944status_t CameraService::handleWatchCommand(const Vector<String16>& args, int inFd, int outFd) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004945 if (args.size() >= 3 && args[1] == String16("start")) {
4946 return startWatchingTags(args, outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004947 } else if (args.size() == 2 && args[1] == String16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004948 return stopWatchingTags(outFd);
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08004949 } else if (args.size() == 2 && args[1] == String16("dump")) {
4950 return printWatchedTags(outFd);
4951 } else if (args.size() >= 2 && args[1] == String16("live")) {
4952 return printWatchedTagsUntilInterrupt(args, inFd, outFd);
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08004953 } else if (args.size() == 2 && args[1] == String16("clear")) {
4954 return clearCachedMonitoredTagDumps(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004955 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004956 dprintf(outFd, "Camera service watch commands:\n"
4957 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
4958 " starts watching the provided tags for clients with provided package\n"
4959 " recognizes tag shorthands like '3a'\n"
4960 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08004961 " dump dumps the monitoring information and exits\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004962 " stop stops watching all tags\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08004963 " live [-n <refresh_interval_ms>]\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004964 " prints the monitored information in real time\n"
Avichal Rakesh84147132021-11-11 17:47:11 -08004965 " Hit return to exit\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08004966 " clear clears all buffers storing information for watch command");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004967 return BAD_VALUE;
4968}
4969
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004970status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
4971 Mutex::Autolock lock(mLogLock);
4972 size_t tagsIdx; // index of '-m'
4973 String16 tags("");
4974 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != String16("-m"); tagsIdx++);
4975 if (tagsIdx < args.size() - 1) {
4976 tags = args[tagsIdx + 1];
4977 } else {
4978 dprintf(outFd, "No tags provided.\n");
4979 return BAD_VALUE;
4980 }
4981
4982 size_t clientsIdx; // index of '-c'
4983 String16 clients = kWatchAllClientsFlag; // watch all clients if no clients are provided
4984 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != String16("-c");
4985 clientsIdx++);
4986 if (clientsIdx < args.size() - 1) {
4987 clients = args[clientsIdx + 1];
4988 }
4989 parseClientsToWatchLocked(String8(clients));
4990
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004991 // track tags to initialize future clients with the monitoring information
4992 mMonitorTags = String8(tags);
4993
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004994 bool serviceLock = tryLock(mServiceLock);
4995 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004996 auto cameraClients = mActiveClientManager.getAll();
4997 for (const auto &clientDescriptor: cameraClients) {
4998 if (clientDescriptor == nullptr) { continue; }
4999 sp<BasicClient> client = clientDescriptor->getValue();
5000 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005001
5002 if (isClientWatchedLocked(client.get())) {
5003 client->startWatchingTags(mMonitorTags, outFd);
5004 numWatchedClients++;
5005 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005006 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005007 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
5008
5009 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005010 return OK;
5011}
5012
5013status_t CameraService::stopWatchingTags(int outFd) {
5014 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005015 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005016 mMonitorTags = String8::empty();
5017
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005018 mWatchedClientPackages.clear();
5019 mWatchedClientsDumpCache.clear();
5020
5021 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005022 auto cameraClients = mActiveClientManager.getAll();
5023 for (const auto &clientDescriptor : cameraClients) {
5024 if (clientDescriptor == nullptr) { continue; }
5025 sp<BasicClient> client = clientDescriptor->getValue();
5026 if (client.get() == nullptr) { continue; }
5027 client->stopWatchingTags(outFd);
5028 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005029 dprintf(outFd, "Stopped watching all clients.\n");
5030 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005031 return OK;
5032}
5033
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005034status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
5035 Mutex::Autolock lock(mLogLock);
5036 size_t clearedSize = mWatchedClientsDumpCache.size();
5037 mWatchedClientsDumpCache.clear();
5038 dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
5039 return OK;
5040}
5041
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005042status_t CameraService::printWatchedTags(int outFd) {
5043 Mutex::Autolock logLock(mLogLock);
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08005044 std::set<String16> connectedMonitoredClients;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005045
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005046 bool printedSomething = false; // tracks if any monitoring information was printed
5047 // (from either cached or active clients)
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005048
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005049 bool serviceLock = tryLock(mServiceLock);
5050 // get all watched clients that are currently connected
5051 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
5052 if (clientDescriptor == nullptr) { continue; }
5053
5054 sp<BasicClient> client = clientDescriptor->getValue();
5055 if (client.get() == nullptr) { continue; }
5056 if (!isClientWatchedLocked(client.get())) { continue; }
5057
5058 std::vector<std::string> dumpVector;
5059 client->dumpWatchedEventsToVector(dumpVector);
5060
5061 size_t printIdx = dumpVector.size();
5062 if (printIdx == 0) {
5063 continue;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005064 }
5065
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005066 // Print tag dumps for active client
5067 const String8 &cameraId = clientDescriptor->getKey();
5068 String8 packageName8 = String8(client->getPackageName());
5069 const char *printablePackageName = packageName8.lockBuffer(packageName8.size());
5070 dprintf(outFd, "Client: %s (active)\n", printablePackageName);
5071 while(printIdx > 0) {
5072 printIdx--;
5073 dprintf(outFd, "%s:%s %s", cameraId.string(), printablePackageName,
5074 dumpVector[printIdx].c_str());
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005075 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005076 dprintf(outFd, "\n");
5077 packageName8.unlockBuffer();
5078 printedSomething = true;
5079
5080 connectedMonitoredClients.emplace(client->getPackageName());
5081 }
5082 if (serviceLock) { mServiceLock.unlock(); }
5083
5084 // Print entries in mWatchedClientsDumpCache for clients that are not connected
5085 for (const auto &kv: mWatchedClientsDumpCache) {
5086 const String16 &package = kv.first;
5087 if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
5088 continue;
5089 }
5090
5091 dprintf(outFd, "Client: %s (cached)\n", String8(package).string());
5092 dprintf(outFd, "%s\n", kv.second.c_str());
5093 printedSomething = true;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005094 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005095
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005096 if (!printedSomething) {
5097 dprintf(outFd, "No monitoring information to print.\n");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005098 }
5099
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005100 return OK;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005101}
5102
Avichal Rakesh84147132021-11-11 17:47:11 -08005103// Print all events in vector `events' that came after lastPrintedEvent
5104void printNewWatchedEvents(int outFd,
5105 const char *cameraId,
5106 const String16 &packageName,
5107 const std::vector<std::string> &events,
5108 const std::string &lastPrintedEvent) {
5109 if (events.empty()) { return; }
5110
5111 // index of lastPrintedEvent in events.
5112 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
5113 size_t lastPrintedIdx;
5114 for (lastPrintedIdx = 0;
5115 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
5116 lastPrintedIdx++);
5117
5118 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
5119
5120 String8 packageName8(packageName);
5121 const char *printablePackageName = packageName8.lockBuffer(packageName8.size());
5122
5123 // print events in chronological order (latest event last)
5124 size_t idxToPrint = lastPrintedIdx;
5125 do {
5126 idxToPrint--;
5127 dprintf(outFd, "%s:%s %s", cameraId, printablePackageName, events[idxToPrint].c_str());
5128 } while (idxToPrint != 0);
5129
5130 packageName8.unlockBuffer();
5131}
5132
5133// Returns true if adb shell cmd watch should be interrupted based on data in inFd. The watch
5134// command should be interrupted if the user presses the return key, or if user loses any way to
5135// signal interrupt.
5136// If timeoutMs == 0, this function will always return false
5137bool shouldInterruptWatchCommand(int inFd, int outFd, long timeoutMs) {
5138 struct timeval startTime;
5139 int startTimeError = gettimeofday(&startTime, nullptr);
5140 if (startTimeError) {
5141 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
5142 return true;
5143 }
5144
5145 const nfds_t numFds = 1;
5146 struct pollfd pollFd = { .fd = inFd, .events = POLLIN, .revents = 0 };
5147
5148 struct timeval currTime;
5149 char buffer[2];
5150 while(true) {
5151 int currTimeError = gettimeofday(&currTime, nullptr);
5152 if (currTimeError) {
5153 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
5154 return true;
5155 }
5156
5157 long elapsedTimeMs = ((currTime.tv_sec - startTime.tv_sec) * 1000L)
5158 + ((currTime.tv_usec - startTime.tv_usec) / 1000L);
5159 int remainingTimeMs = (int) (timeoutMs - elapsedTimeMs);
5160
5161 if (remainingTimeMs <= 0) {
5162 // No user interrupt within timeoutMs, don't interrupt watch command
5163 return false;
5164 }
5165
5166 int numFdsUpdated = poll(&pollFd, numFds, remainingTimeMs);
5167 if (numFdsUpdated < 0) {
5168 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
5169 return true;
5170 }
5171
5172 if (numFdsUpdated == 0) {
5173 // No user input within timeoutMs, don't interrupt watch command
5174 return false;
5175 }
5176
5177 if (!(pollFd.revents & POLLIN)) {
5178 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
5179 return true;
5180 }
5181
5182 ssize_t sizeRead = read(inFd, buffer, sizeof(buffer) - 1);
5183 if (sizeRead < 0) {
5184 dprintf(outFd, "Error reading user input. Exiting.\n");
5185 return true;
5186 }
5187
5188 if (sizeRead == 0) {
5189 // Reached end of input fd (can happen if input is piped)
5190 // User has no way to signal an interrupt, so interrupt here
5191 return true;
5192 }
5193
5194 if (buffer[0] == '\n') {
5195 // User pressed return, interrupt watch command.
5196 return true;
5197 }
5198 }
5199}
5200
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005201status_t CameraService::printWatchedTagsUntilInterrupt(const Vector<String16> &args,
5202 int inFd, int outFd) {
5203 // Figure out refresh interval, if present in args
5204 long refreshTimeoutMs = 1000L; // refresh every 1s by default
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005205 if (args.size() > 2) {
5206 size_t intervalIdx; // index of '-n'
5207 for (intervalIdx = 2; intervalIdx < args.size() && String16("-n") != args[intervalIdx];
5208 intervalIdx++);
5209
5210 size_t intervalValIdx = intervalIdx + 1;
5211 if (intervalValIdx < args.size()) {
5212 refreshTimeoutMs = strtol(String8(args[intervalValIdx].string()), nullptr, 10);
5213 if (errno) { return BAD_VALUE; }
5214 }
5215 }
5216
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005217 // Set min timeout of 10ms. This prevents edge cases in polling when timeout of 0 is passed.
5218 refreshTimeoutMs = refreshTimeoutMs < 10 ? 10 : refreshTimeoutMs;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005219
Avichal Rakesh84147132021-11-11 17:47:11 -08005220 dprintf(outFd, "Press return to exit...\n\n");
Avichal Rakesha14d9832021-11-11 01:41:55 -08005221 std::map<String16, std::string> packageNameToLastEvent;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005222
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005223 while (true) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08005224 bool serviceLock = tryLock(mServiceLock);
5225 auto cameraClients = mActiveClientManager.getAll();
5226 if (serviceLock) { mServiceLock.unlock(); }
5227
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005228 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005229 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005230 if (clientDescriptor == nullptr) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005231
5232 sp<BasicClient> client = clientDescriptor->getValue();
5233 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005234 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005235
Avichal Rakesha14d9832021-11-11 01:41:55 -08005236 const String16 &packageName = client->getPackageName();
5237 // This also initializes the map entries with an empty string
5238 const std::string& lastPrintedEvent = packageNameToLastEvent[packageName];
5239
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005240 std::vector<std::string> latestEvents;
5241 client->dumpWatchedEventsToVector(latestEvents);
5242
5243 if (!latestEvents.empty()) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08005244 String8 cameraId = clientDescriptor->getKey();
5245 const char *printableCameraId = cameraId.lockBuffer(cameraId.size());
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005246 printNewWatchedEvents(outFd,
Avichal Rakesha14d9832021-11-11 01:41:55 -08005247 printableCameraId,
5248 packageName,
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005249 latestEvents,
5250 lastPrintedEvent);
Avichal Rakesha14d9832021-11-11 01:41:55 -08005251 packageNameToLastEvent[packageName] = latestEvents[0];
5252 cameraId.unlockBuffer();
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005253 }
5254 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005255 if (shouldInterruptWatchCommand(inFd, outFd, refreshTimeoutMs)) {
Avichal Rakesh84147132021-11-11 17:47:11 -08005256 break;
5257 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005258 }
5259 return OK;
5260}
5261
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005262void CameraService::parseClientsToWatchLocked(String8 clients) {
5263 mWatchedClientPackages.clear();
5264
5265 const char *allSentinel = String8(kWatchAllClientsFlag).string();
5266
5267 char *tokenized = clients.lockBuffer(clients.size());
5268 char *savePtr;
5269 char *nextClient = strtok_r(tokenized, ",", &savePtr);
5270
5271 while (nextClient != nullptr) {
5272 if (strcmp(nextClient, allSentinel) == 0) {
5273 // Don't need to track any other package if 'all' is present
5274 mWatchedClientPackages.clear();
5275 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
5276 break;
5277 }
5278
5279 // track package names
5280 mWatchedClientPackages.emplace(nextClient);
5281 nextClient = strtok_r(nullptr, ",", &savePtr);
5282 }
5283 clients.unlockBuffer();
5284}
5285
Svet Ganova453d0d2018-01-11 15:37:58 -08005286status_t CameraService::printHelp(int out) {
5287 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07005288 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
5289 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
5290 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005291 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
5292 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
5293 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005294 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
5295 " Valid values 0=OFF, 1=ON for JPEG\n"
5296 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005297 " set-camera-mute <0/1> enable or disable camera muting\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005298 " watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08005299 " help print this message\n");
5300}
5301
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005302bool CameraService::isClientWatched(const BasicClient *client) {
5303 Mutex::Autolock lock(mLogLock);
5304 return isClientWatchedLocked(client);
5305}
5306
5307bool CameraService::isClientWatchedLocked(const BasicClient *client) {
5308 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
5309 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
5310}
5311
Yin-Chia Yehdba03232019-08-19 15:54:28 -07005312int32_t CameraService::updateAudioRestriction() {
5313 Mutex::Autolock lock(mServiceLock);
5314 return updateAudioRestrictionLocked();
5315}
5316
5317int32_t CameraService::updateAudioRestrictionLocked() {
5318 int32_t mode = 0;
5319 // iterate through all active client
5320 for (const auto& i : mActiveClientManager.getAll()) {
5321 const auto clientSp = i->getValue();
5322 mode |= clientSp->getAudioRestriction();
5323 }
5324
5325 bool modeChanged = (mAudioRestriction != mode);
5326 mAudioRestriction = mode;
5327 if (modeChanged) {
5328 mAppOps.setCameraAudioRestriction(mode);
5329 }
5330 return mode;
5331}
5332
Cliff Wu646bd612021-11-23 23:21:29 +08005333status_t CameraService::checkIfInjectionCameraIsPresent(const String8& externalCamId,
5334 sp<BasicClient> clientSp) {
5335 std::unique_ptr<AutoConditionLock> lock =
5336 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
5337 status_t res = NO_ERROR;
5338 if ((res = checkIfDeviceIsUsable(externalCamId)) != NO_ERROR) {
5339 ALOGW("Device %s is not usable!", externalCamId.string());
5340 mInjectionStatusListener->notifyInjectionError(
5341 externalCamId, UNKNOWN_TRANSACTION);
5342 clientSp->notifyError(
5343 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
5344 CaptureResultExtras());
5345
5346 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
5347 // other clients from connecting in mServiceLockWrapper if held
5348 mServiceLock.unlock();
5349
5350 // Clear caller identity temporarily so client disconnect PID checks work correctly
5351 int64_t token = CameraThreadState::clearCallingIdentity();
5352 clientSp->disconnect();
5353 CameraThreadState::restoreCallingIdentity(token);
5354
5355 // Reacquire mServiceLock
5356 mServiceLock.lock();
5357 }
5358
5359 return res;
5360}
5361
Cliff Wud3a05312021-04-26 23:07:31 +08005362void CameraService::clearInjectionParameters() {
5363 {
5364 Mutex::Autolock lock(mInjectionParametersLock);
Cliff Wu646bd612021-11-23 23:21:29 +08005365 mInjectionInitPending = false;
Cliff Wud3a05312021-04-26 23:07:31 +08005366 mInjectionInternalCamId = "";
5367 }
5368 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08005369 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08005370}
5371
Mathias Agopian65ab4712010-07-14 17:59:35 -07005372}; // namespace android