blob: 32977f7ebf509956a21594a421032087970dd8a0 [file] [log] [blame]
Mathias Agopian65ab4712010-07-14 17:59:35 -07001/*
Ruben Brunkd1176ef2014-02-21 10:51:38 -08002 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Mathias Agopian65ab4712010-07-14 17:59:35 -070016
17#define LOG_TAG "CameraService"
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -070018#define ATRACE_TAG ATRACE_TAG_CAMERA
Iliyan Malchev8951a972011-04-14 16:55:59 -070019//#define LOG_NDEBUG 0
Mathias Agopian65ab4712010-07-14 17:59:35 -070020
Ruben Brunkcc776712015-02-17 20:18:47 -080021#include <algorithm>
22#include <climits>
Mathias Agopian65ab4712010-07-14 17:59:35 -070023#include <stdio.h>
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -080024#include <cstdlib>
Ruben Brunkcc776712015-02-17 20:18:47 -080025#include <cstring>
26#include <ctime>
27#include <string>
Mathias Agopian65ab4712010-07-14 17:59:35 -070028#include <sys/types.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080029#include <inttypes.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070030#include <pthread.h>
Avichal Rakesh84147132021-11-11 17:47:11 -080031#include <poll.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070032
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080033#include <android/hardware/ICamera.h>
34#include <android/hardware/ICameraClient.h>
35
Alex Deymo9c2a2c22016-08-25 11:59:14 -070036#include <android-base/macros.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080037#include <android-base/parseint.h>
Jayant Chowdharyb61526c2019-05-13 19:37:42 -070038#include <android-base/stringprintf.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080039#include <binder/ActivityManager.h>
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -080040#include <binder/AppOpsManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070041#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070042#include <binder/MemoryBase.h>
43#include <binder/MemoryHeapBase.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080044#include <binder/PermissionController.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080045#include <binder/IResultReceiver.h>
Steven Moreland89a2c5c2020-01-31 15:02:25 -080046#include <binderthreadstate/CallerUtils.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070047#include <cutils/atomic.h>
Nipun Kwatrab5ca4612010-09-11 19:31:10 -070048#include <cutils/properties.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080049#include <cutils/misc.h>
Mathias Agopiandf712ea2012-02-25 18:48:35 -080050#include <gui/Surface.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070051#include <hardware/hardware.h>
Jayant Chowdharybe543d42018-08-15 13:16:14 -070052#include "hidl/HidlCameraService.h"
53#include <hidl/HidlTransportSupport.h>
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -080054#include <hwbinder/IPCThreadState.h>
Eino-Ville Talvalad89821e2016-04-20 11:23:50 -070055#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070056#include <media/AudioSystem.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080057#include <media/IMediaHTTPService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070058#include <media/mediaplayer.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070059#include <mediautils/BatteryNotifier.h>
Steven Moreland886d7322021-04-02 04:19:45 +000060#include <processinfo/ProcessInfoService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070061#include <utils/Errors.h>
62#include <utils/Log.h>
63#include <utils/String16.h>
Svet Ganov94ec46f2018-06-08 15:03:46 -070064#include <utils/SystemClock.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080065#include <utils/Trace.h>
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080066#include <utils/CallStack.h>
Chien-Yu Chen98a668f2015-12-18 14:10:33 -080067#include <private/android_filesystem_config.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080068#include <system/camera_vendor_tags.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070069#include <system/camera_metadata.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080070
Ruben Brunkb2119af2014-05-09 19:57:56 -070071#include <system/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070072
73#include "CameraService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070074#include "api1/Camera2Client.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070075#include "api2/CameraDeviceClient.h"
Igor Murashkinff3e31d2013-10-23 16:40:06 -070076#include "utils/CameraTraces.h"
Emilian Peevbd8c5032018-02-14 23:05:40 +000077#include "utils/TagMonitor.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070078#include "utils/CameraThreadState.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070079#include "utils/CameraServiceProxyWrapper.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070080
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080081namespace {
82 const char* kPermissionServiceName = "permission";
83}; // namespace anonymous
84
Mathias Agopian65ab4712010-07-14 17:59:35 -070085namespace android {
86
Jayant Chowdharyb61526c2019-05-13 19:37:42 -070087using base::StringPrintf;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080088using binder::Status;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -070089using camera3::SessionConfigurationUtils;
Jayant Chowdharybe543d42018-08-15 13:16:14 -070090using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -080091using hardware::ICamera;
92using hardware::ICameraClient;
93using hardware::ICameraServiceListener;
94using hardware::camera::common::V1_0::CameraDeviceStatus;
95using hardware::camera::common::V1_0::TorchModeStatus;
Cliff Wud8cae102021-03-11 01:37:42 +080096using hardware::camera2::ICameraInjectionCallback;
97using hardware::camera2::ICameraInjectionSession;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080098using hardware::camera2::utils::CameraIdAndSessionConfiguration;
99using hardware::camera2::utils::ConcurrentCameraIdCombination;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800100
Mathias Agopian65ab4712010-07-14 17:59:35 -0700101// ----------------------------------------------------------------------------
102// Logging support -- this is for debugging only
103// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700104volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700105
Steve Blockb8a80522011-12-20 16:23:08 +0000106#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
107#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700108
109static void setLogLevel(int level) {
110 android_atomic_write(level, &gLogLevel);
111}
112
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800113// Convenience methods for constructing binder::Status objects for error returns
114
115#define STATUS_ERROR(errorCode, errorString) \
116 binder::Status::fromServiceSpecificError(errorCode, \
117 String8::format("%s:%d: %s", __FUNCTION__, __LINE__, errorString))
118
119#define STATUS_ERROR_FMT(errorCode, errorString, ...) \
120 binder::Status::fromServiceSpecificError(errorCode, \
121 String8::format("%s:%d: " errorString, __FUNCTION__, __LINE__, \
122 __VA_ARGS__))
123
Mathias Agopian65ab4712010-07-14 17:59:35 -0700124// ----------------------------------------------------------------------------
125
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700126static const String16 sDumpPermission("android.permission.DUMP");
Svet Ganova453d0d2018-01-11 15:37:58 -0800127static const String16 sManageCameraPermission("android.permission.MANAGE_CAMERA");
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700128static const String16 sCameraPermission("android.permission.CAMERA");
129static const String16 sSystemCameraPermission("android.permission.SYSTEM_CAMERA");
130static const String16
131 sCameraSendSystemEventsPermission("android.permission.CAMERA_SEND_SYSTEM_EVENTS");
Shuzhen Wang695044d2020-03-06 09:02:23 -0800132static const String16 sCameraOpenCloseListenerPermission(
133 "android.permission.CAMERA_OPEN_CLOSE_LISTENER");
Cliff Wud8cae102021-03-11 01:37:42 +0800134static const String16
135 sCameraInjectExternalCameraPermission("android.permission.CAMERA_INJECT_EXTERNAL_CAMERA");
Rucha Katakwardf223072021-06-15 10:21:00 -0700136const char *sFileName = "lastOpenSessionDumpFile";
Eino-Ville Talvala7c602c32021-03-20 17:00:18 -0700137static constexpr int32_t kVendorClientScore = resource_policy::PERCEPTIBLE_APP_ADJ;
138static constexpr int32_t kVendorClientState = ActivityManager::PROCESS_STATE_PERSISTENT_UI;
139
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800140const String8 CameraService::kOfflineDevice("offline-");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -0700141const String16 CameraService::kWatchAllClientsFlag("all");
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700142
Rucha Katakward9ea6452021-05-06 11:57:16 -0700143// Set to keep track of logged service error events.
144static std::set<String8> sServiceErrorEventSet;
145
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800146CameraService::CameraService() :
147 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800148 mNumberOfCameras(0),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700149 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700150 mSoundRef(0), mInitialized(false),
151 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000152 ALOGI("CameraService started (pid=%d)", getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800153 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Rucha Katakwardf223072021-06-15 10:21:00 -0700154 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
155 if (mMemFd == -1) {
156 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
157 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700158}
159
Iliyan Malchev8951a972011-04-14 16:55:59 -0700160void CameraService::onFirstRef()
161{
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -0700162
Ruben Brunkcc776712015-02-17 20:18:47 -0800163 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800164
Iliyan Malchev8951a972011-04-14 16:55:59 -0700165 BnCameraService::onFirstRef();
166
Ruben Brunk99e69712015-05-26 17:25:07 -0700167 // Update battery life tracking if service is restarting
168 BatteryNotifier& notifier(BatteryNotifier::getInstance());
169 notifier.noteResetCamera();
170 notifier.noteResetFlashlight();
171
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800172 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800173
Emilian Peevf53f66e2017-04-11 14:29:43 +0100174 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800175 if (res == OK) {
176 mInitialized = true;
177 }
178
Svet Ganova453d0d2018-01-11 15:37:58 -0800179 mUidPolicy = new UidPolicy(this);
180 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800181 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
182 mSensorPrivacyPolicy->registerSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800183 mInjectionStatusListener = new InjectionStatusListener(this);
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700184 mAppOps.setCameraAudioRestriction(mAudioRestriction);
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700185 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
186 if (hcs->registerAsService() != android::OK) {
187 ALOGE("%s: Failed to register default android.frameworks.cameraservice.service@1.0",
188 __FUNCTION__);
189 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700190
191 // This needs to be last call in this function, so that it's as close to
192 // ServiceManager::addService() as possible.
Shuzhen Wang316781a2020-08-18 18:11:01 -0700193 CameraServiceProxyWrapper::pingCameraServiceProxy();
Shuzhen Wang24b44152019-09-20 10:38:11 -0700194 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800195}
196
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800197status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800198 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100199
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800200 std::vector<std::string> deviceIds;
201 {
202 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800203
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800204 if (nullptr == mCameraProviderManager.get()) {
205 mCameraProviderManager = new CameraProviderManager();
206 res = mCameraProviderManager->initialize(this);
207 if (res != OK) {
208 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
209 __FUNCTION__, strerror(-res), res);
Rucha Katakward9ea6452021-05-06 11:57:16 -0700210 logServiceError(String8::format("Unable to initialize camera provider manager"),
211 ERROR_DISCONNECTED);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800212 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100213 }
214 }
215
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800216
217 // Setup vendor tags before we call get_camera_info the first time
218 // because HAL might need to setup static vendor keys in get_camera_info
219 // TODO: maybe put this into CameraProviderManager::initialize()?
220 mCameraProviderManager->setUpVendorTags();
221
222 if (nullptr == mFlashlight.get()) {
223 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700224 }
225
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800226 res = mFlashlight->findFlashUnits();
227 if (res != OK) {
228 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
229 }
230
231 deviceIds = mCameraProviderManager->getCameraDeviceIds();
232 }
233
234
235 for (auto& cameraId : deviceIds) {
236 String8 id8 = String8(cameraId.c_str());
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800237 if (getCameraState(id8) == nullptr) {
238 onDeviceStatusChanged(id8, CameraDeviceStatus::PRESENT);
239 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800240 }
241
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700242 // Derive primary rear/front cameras, and filter their charactierstics.
243 // This needs to be done after all cameras are enumerated and camera ids are sorted.
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700244 if (SessionConfigurationUtils::IS_PERF_CLASS) {
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700245 // Assume internal cameras are advertised from the same
246 // provider. If multiple providers are registered at different time,
247 // and each provider contains multiple internal color cameras, the current
248 // logic may filter the characteristics of more than one front/rear color
249 // cameras.
250 Mutex::Autolock l(mServiceLock);
251 filterSPerfClassCharacteristicsLocked();
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700252 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700253
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800254 return OK;
255}
256
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700257void CameraService::broadcastTorchModeStatus(const String8& cameraId, TorchModeStatus status,
258 SystemCameraKind systemCameraKind) {
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800259 Mutex::Autolock lock(mStatusListenerLock);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800260 for (auto& i : mListenerList) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700261 if (shouldSkipStatusUpdates(systemCameraKind, i->isVendorListener(), i->getListenerPid(),
262 i->getListenerUid())) {
263 ALOGV("Skipping torch callback for system-only camera device %s",
264 cameraId.c_str());
265 continue;
266 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700267 i->getListener()->onTorchStatusChanged(mapToInterface(status), String16{cameraId});
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800268 }
269}
270
Mathias Agopian65ab4712010-07-14 17:59:35 -0700271CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800272 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800273 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800274 mSensorPrivacyPolicy->unregisterSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800275 mInjectionStatusListener->removeListener();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700276}
277
Emilian Peevaee727d2017-05-04 16:35:48 +0100278void CameraService::onNewProviderRegistered() {
279 enumerateProviders();
280}
281
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700282void CameraService::filterAPI1SystemCameraLocked(
283 const std::vector<std::string> &normalDeviceIds) {
284 mNormalDeviceIdsWithoutSystemCamera.clear();
285 for (auto &deviceId : normalDeviceIds) {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700286 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
287 if (getSystemCameraKind(String8(deviceId.c_str()), &deviceKind) != OK) {
288 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, deviceId.c_str());
289 continue;
290 }
291 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700292 // All system camera ids will necessarily come after public camera
293 // device ids as per the HAL interface contract.
294 break;
295 }
296 mNormalDeviceIdsWithoutSystemCamera.push_back(deviceId);
297 }
298 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
299 mNormalDeviceIdsWithoutSystemCamera.size());
300}
301
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700302status_t CameraService::getSystemCameraKind(const String8& cameraId, SystemCameraKind *kind) const {
303 auto state = getCameraState(cameraId);
304 if (state != nullptr) {
305 *kind = state->getSystemCameraKind();
306 return OK;
307 }
308 // Hidden physical camera ids won't have CameraState
309 return mCameraProviderManager->getSystemCameraKind(cameraId.c_str(), kind);
310}
311
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800312void CameraService::updateCameraNumAndIds() {
313 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700314 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
315 // Excludes hidden secure cameras
316 mNumberOfCameras =
317 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
318 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800319 mNormalDeviceIds =
320 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700321 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800322}
323
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700324void CameraService::filterSPerfClassCharacteristicsLocked() {
Shuzhen Wang89db2992021-05-20 13:09:48 -0700325 // To claim to be S Performance primary cameras, the cameras must be
326 // backward compatible. So performance class primary camera Ids must be API1
327 // compatible.
328 bool firstRearCameraSeen = false, firstFrontCameraSeen = false;
329 for (const auto& cameraId : mNormalDeviceIdsWithoutSystemCamera) {
330 int facing = -1;
331 int orientation = 0;
332 String8 cameraId8(cameraId.c_str());
333 getDeviceVersion(cameraId8, /*out*/&facing, /*out*/&orientation);
334 if (facing == -1) {
335 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
336 return;
337 }
338
339 if ((facing == hardware::CAMERA_FACING_BACK && !firstRearCameraSeen) ||
340 (facing == hardware::CAMERA_FACING_FRONT && !firstFrontCameraSeen)) {
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700341 status_t res = mCameraProviderManager->filterSmallJpegSizes(cameraId);
342 if (res == OK) {
343 mPerfClassPrimaryCameraIds.insert(cameraId);
344 } else {
345 ALOGE("%s: Failed to filter small JPEG sizes for performance class primary "
346 "camera %s: %s(%d)", __FUNCTION__, cameraId.c_str(), strerror(-res), res);
347 break;
348 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700349
350 if (facing == hardware::CAMERA_FACING_BACK) {
351 firstRearCameraSeen = true;
352 }
353 if (facing == hardware::CAMERA_FACING_FRONT) {
354 firstFrontCameraSeen = true;
355 }
356 }
357
358 if (firstRearCameraSeen && firstFrontCameraSeen) {
359 break;
360 }
361 }
362}
363
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100364void CameraService::addStates(const String8 id) {
365 std::string cameraId(id.c_str());
366 hardware::camera::common::V1_0::CameraResourceCost cost;
367 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700368 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100369 if (res != OK) {
370 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
371 return;
372 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700373 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
374 if (res != OK) {
375 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
376 return;
377 }
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100378 std::set<String8> conflicting;
379 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
380 conflicting.emplace(String8(cost.conflictingDevices[i].c_str()));
381 }
382
383 {
384 Mutex::Autolock lock(mCameraStatesLock);
385 mCameraStates.emplace(id, std::make_shared<CameraState>(id, cost.resourceCost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700386 conflicting, deviceKind));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100387 }
388
389 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100390 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100391 mTorchStatusMap.add(id, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800392
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700393 broadcastTorchModeStatus(id, TorchModeStatus::AVAILABLE_OFF, deviceKind);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100394 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800395
396 updateCameraNumAndIds();
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100397 logDeviceAdded(id, "Device added");
398}
399
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100400void CameraService::removeStates(const String8 id) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800401 updateCameraNumAndIds();
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100402 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100403 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100404 mTorchStatusMap.removeItem(id);
405 }
406
407 {
408 Mutex::Autolock lock(mCameraStatesLock);
409 mCameraStates.erase(id);
410 }
411}
412
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800413void CameraService::onDeviceStatusChanged(const String8& id,
414 CameraDeviceStatus newHalStatus) {
415 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
416 id.string(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700417
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800418 StatusInternal newStatus = mapToInternal(newHalStatus);
419
Ruben Brunkcc776712015-02-17 20:18:47 -0800420 std::shared_ptr<CameraState> state = getCameraState(id);
421
422 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700423 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100424 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700425 __FUNCTION__, id.string());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100426
427 // First add as absent to make sure clients are notified below
428 addStates(id);
429
430 updateStatus(newStatus, id);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700431 } else {
432 ALOGE("%s: Bad camera ID %s", __FUNCTION__, id.string());
433 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700434 return;
435 }
436
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800437 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800438
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800439 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800440 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700441 return;
442 }
443
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800444 if (newStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700445 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
446 newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800447
448 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
449 // to this device until the status changes
450 updateStatus(StatusInternal::NOT_PRESENT, id);
451
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800452 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700453 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800454 // Don't do this in updateStatus to avoid deadlock over mServiceLock
455 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700456
Ruben Brunkcc776712015-02-17 20:18:47 -0800457 // Remove cached shim parameters
458 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700459
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800460 // Remove online as well as offline client from the list of active clients,
461 // if they are present
462 clientToDisconnectOnline = removeClientLocked(id);
463 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + id);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700464 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800465
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800466 disconnectClient(id, clientToDisconnectOnline);
467 disconnectClient(kOfflineDevice + id, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700468
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100469 removeStates(id);
Ruben Brunkcc776712015-02-17 20:18:47 -0800470 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800471 if (oldStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700472 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
473 newStatus));
474 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800475 updateStatus(newStatus, id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700476 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800477}
Igor Murashkincba2c162013-03-20 15:56:31 -0700478
Shuzhen Wang43858162020-01-10 13:42:15 -0800479void CameraService::onDeviceStatusChanged(const String8& id,
480 const String8& physicalId,
481 CameraDeviceStatus newHalStatus) {
482 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
483 __FUNCTION__, id.string(), physicalId.string(), newHalStatus);
484
485 StatusInternal newStatus = mapToInternal(newHalStatus);
486
487 std::shared_ptr<CameraState> state = getCameraState(id);
488
489 if (state == nullptr) {
490 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
491 __FUNCTION__, id.string(), physicalId.string());
492 return;
493 }
494
495 StatusInternal logicalCameraStatus = state->getStatus();
496 if (logicalCameraStatus != StatusInternal::PRESENT &&
497 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
498 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
499 __FUNCTION__, physicalId.string(), newHalStatus, logicalCameraStatus);
500 return;
501 }
502
503 bool updated = false;
504 if (newStatus == StatusInternal::PRESENT) {
505 updated = state->removeUnavailablePhysicalId(physicalId);
506 } else {
507 updated = state->addUnavailablePhysicalId(physicalId);
508 }
509
510 if (updated) {
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800511 String8 idCombo = id + " : " + physicalId;
512 if (newStatus == StatusInternal::PRESENT) {
513 logDeviceAdded(idCombo,
514 String8::format("Device status changed to %d", newStatus));
515 } else {
516 logDeviceRemoved(idCombo,
517 String8::format("Device status changed to %d", newStatus));
518 }
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700519 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
520 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
521 if (getSystemCameraKind(id, &deviceKind) != OK) {
522 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.string());
523 return;
524 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800525 String16 id16(id), physicalId16(physicalId);
526 Mutex::Autolock lock(mStatusListenerLock);
527 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700528 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
529 listener->getListenerPid(), listener->getListenerUid())) {
530 ALOGV("Skipping discovery callback for system-only camera device %s",
531 id.c_str());
532 continue;
533 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800534 listener->getListener()->onPhysicalCameraStatusChanged(mapToInterface(newStatus),
535 id16, physicalId16);
536 }
537 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700538}
539
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800540void CameraService::disconnectClient(const String8& id, sp<BasicClient> clientToDisconnect) {
541 if (clientToDisconnect.get() != nullptr) {
542 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
543 __FUNCTION__, id.string());
544 // Notify the client of disconnection
545 clientToDisconnect->notifyError(
546 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
547 CaptureResultExtras{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800548 clientToDisconnect->disconnect();
549 }
550}
551
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800552void CameraService::onTorchStatusChanged(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800553 TorchModeStatus newStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700554 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
555 status_t res = getSystemCameraKind(cameraId, &systemCameraKind);
556 if (res != OK) {
557 ALOGE("%s: Could not get system camera kind for camera id %s", __FUNCTION__,
558 cameraId.string());
559 return;
560 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800561 Mutex::Autolock al(mTorchStatusMutex);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700562 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800563}
564
Jayant Chowdhary46ef0f52021-10-05 14:36:13 -0700565
566void CameraService::onTorchStatusChanged(const String8& cameraId,
567 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
568 Mutex::Autolock al(mTorchStatusMutex);
569 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
570}
571
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800572void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700573 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800574 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
575 __FUNCTION__, cameraId.string(), newStatus);
576
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800577 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800578 status_t res = getTorchStatusLocked(cameraId, &status);
579 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700580 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
581 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800582 return;
583 }
584 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800585 return;
586 }
587
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800588 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800589 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800590 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
591 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800592 return;
593 }
594
Ruben Brunkcc776712015-02-17 20:18:47 -0800595 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700596 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700597 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700598 auto iter = mTorchUidMap.find(cameraId);
599 if (iter != mTorchUidMap.end()) {
600 int oldUid = iter->second.second;
601 int newUid = iter->second.first;
602 BatteryNotifier& notifier(BatteryNotifier::getInstance());
603 if (oldUid != newUid) {
604 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800605 if (status == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700606 notifier.noteFlashlightOff(cameraId, oldUid);
607 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800608 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700609 notifier.noteFlashlightOn(cameraId, newUid);
610 }
611 iter->second.second = newUid;
612 } else {
613 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800614 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700615 notifier.noteFlashlightOn(cameraId, oldUid);
616 } else {
617 notifier.noteFlashlightOff(cameraId, oldUid);
618 }
619 }
620 }
621 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700622 broadcastTorchModeStatus(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800623}
624
Jayant Chowdharyc3198c32021-07-28 20:59:14 +0000625static bool hasPermissionsForSystemCamera(int callingPid, int callingUid,
626 bool logPermissionFailure = false) {
627 return checkPermission(sSystemCameraPermission, callingPid, callingUid,
628 logPermissionFailure) &&
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700629 checkPermission(sCameraPermission, callingPid, callingUid);
630}
631
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800632Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700633 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100634 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700635 bool hasSystemCameraPermissions =
636 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
637 CameraThreadState::getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700638 switch (type) {
639 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700640 if (hasSystemCameraPermissions) {
641 *numCameras = static_cast<int>(mNormalDeviceIds.size());
642 } else {
643 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
644 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800645 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700646 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700647 if (hasSystemCameraPermissions) {
648 *numCameras = mNumberOfCameras;
649 } else {
650 *numCameras = mNumberOfCamerasWithoutSystemCamera;
651 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800652 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700653 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800654 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700655 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800656 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
657 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700658 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800659 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700660}
661
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800662Status CameraService::getCameraInfo(int cameraId,
663 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700664 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100665 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700666 std::string cameraIdStr = cameraIdIntToStrLocked(cameraId);
667 if (shouldRejectSystemCameraConnection(String8(cameraIdStr.c_str()))) {
668 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
669 "characteristics for system only device %s: ", cameraIdStr.c_str());
670 }
Emilian Peevaee727d2017-05-04 16:35:48 +0100671
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800672 if (!mInitialized) {
Rucha Katakward9ea6452021-05-06 11:57:16 -0700673 logServiceError(String8::format("Camera subsystem is not available"),ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800674 return STATUS_ERROR(ERROR_DISCONNECTED,
675 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -0700676 }
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700677 bool hasSystemCameraPermissions =
678 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
679 CameraThreadState::getCallingUid());
680 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
681 if (hasSystemCameraPermissions) {
682 cameraIdBound = mNumberOfCameras;
683 }
684 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800685 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
686 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700687 }
688
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800689 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800690 status_t err = mCameraProviderManager->getCameraInfo(
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700691 cameraIdStr.c_str(), cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100692 if (err != OK) {
693 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
694 "Error retrieving camera info from device %d: %s (%d)", cameraId,
695 strerror(-err), err);
Rucha Katakward9ea6452021-05-06 11:57:16 -0700696 logServiceError(String8::format("Error retrieving camera info from device %d",cameraId),
697 ERROR_INVALID_OPERATION);
Ruben Brunkcc776712015-02-17 20:18:47 -0800698 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100699
Ruben Brunkcc776712015-02-17 20:18:47 -0800700 return ret;
701}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700702
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800703std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700704 const std::vector<std::string> *deviceIds = &mNormalDeviceIdsWithoutSystemCamera;
705 auto callingPid = CameraThreadState::getCallingPid();
706 auto callingUid = CameraThreadState::getCallingUid();
Jayant Chowdharyc3198c32021-07-28 20:59:14 +0000707 if (checkPermission(sSystemCameraPermission, callingPid, callingUid,
708 /*logPermissionFailure*/false) || getpid() == callingPid) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700709 deviceIds = &mNormalDeviceIds;
710 }
711 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(deviceIds->size())) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800712 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700713 __FUNCTION__, cameraIdInt, deviceIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800714 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800715 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800716
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700717 return (*deviceIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800718}
719
720String8 CameraService::cameraIdIntToStr(int cameraIdInt) {
721 Mutex::Autolock lock(mServiceLock);
722 return String8(cameraIdIntToStrLocked(cameraIdInt).c_str());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800723}
724
725Status CameraService::getCameraCharacteristics(const String16& cameraId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700726 int targetSdkVersion, CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700727 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700728 if (!cameraInfo) {
729 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800730 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -0700731 }
732
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800733 if (!mInitialized) {
734 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Rucha Katakward9ea6452021-05-06 11:57:16 -0700735 logServiceError(String8::format("Camera subsystem is not available"),ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800736 return STATUS_ERROR(ERROR_DISCONNECTED,
737 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -0700738 }
739
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700740 if (shouldRejectSystemCameraConnection(String8(cameraId))) {
741 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
742 "characteristics for system only device %s: ", String8(cameraId).string());
743 }
744
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800745 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800746
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700747
748 std::string cameraIdStr = String8(cameraId).string();
749 bool overrideForPerfClass =
750 SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
751 cameraIdStr, targetSdkVersion);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100752 status_t res = mCameraProviderManager->getCameraCharacteristics(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700753 cameraIdStr, overrideForPerfClass, cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100754 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700755 if (res == NAME_NOT_FOUND) {
756 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
757 "characteristics for unknown device %s: %s (%d)", String8(cameraId).string(),
758 strerror(-res), res);
759 } else {
Rucha Katakward9ea6452021-05-06 11:57:16 -0700760 logServiceError(String8::format("Unable to retrieve camera characteristics for "
761 "device %s.", String8(cameraId).string()),ERROR_INVALID_OPERATION);
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700762 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
763 "characteristics for device %s: %s (%d)", String8(cameraId).string(),
764 strerror(-res), res);
765 }
Ruben Brunkb2119af2014-05-09 19:57:56 -0700766 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700767 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
768 if (getSystemCameraKind(String8(cameraId), &deviceKind) != OK) {
769 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, String8(cameraId).string());
770 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera kind "
771 "for device %s", String8(cameraId).string());
772 }
Jayant Chowdhary12361932018-08-27 14:46:13 -0700773 int callingPid = CameraThreadState::getCallingPid();
774 int callingUid = CameraThreadState::getCallingUid();
Emilian Peeve20c6372018-08-14 18:45:53 +0100775 std::vector<int32_t> tagsRemoved;
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700776 // If it's not calling from cameraserver, check the permission only if
777 // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
778 // it would've already been checked in shouldRejectSystemCameraConnection.
Emilian Peeve20c6372018-08-14 18:45:53 +0100779 if ((callingPid != getpid()) &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700780 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700781 !checkPermission(sCameraPermission, callingPid, callingUid)) {
Emilian Peeve20c6372018-08-14 18:45:53 +0100782 res = cameraInfo->removePermissionEntries(
783 mCameraProviderManager->getProviderTagIdLocked(String8(cameraId).string()),
784 &tagsRemoved);
785 if (res != OK) {
786 cameraInfo->clear();
787 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
788 " characteristics needing camera permission for device %s: %s (%d)",
789 String8(cameraId).string(), strerror(-res), res);
790 }
791 }
792
793 if (!tagsRemoved.empty()) {
794 res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
795 tagsRemoved.data(), tagsRemoved.size());
796 if (res != OK) {
797 cameraInfo->clear();
798 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
799 "keys needing permission for device %s: %s (%d)", String8(cameraId).string(),
800 strerror(-res), res);
801 }
802 }
803
Zhijun He2b59be82013-09-25 10:14:30 -0700804 return ret;
805}
806
Ruben Brunkcc776712015-02-17 20:18:47 -0800807String8 CameraService::getFormattedCurrentTime() {
808 time_t now = time(nullptr);
809 char formattedTime[64];
810 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
811 return String8(formattedTime);
812}
813
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800814Status CameraService::getCameraVendorTagDescriptor(
815 /*out*/
816 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700817 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800818 if (!mInitialized) {
819 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800820 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800821 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -0800822 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
823 if (globalDescriptor != nullptr) {
824 *desc = *(globalDescriptor.get());
825 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800826 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800827}
828
Emilian Peev71c73a22017-03-21 16:35:51 +0000829Status CameraService::getCameraVendorTagCache(
830 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
831 ATRACE_CALL();
832 if (!mInitialized) {
833 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
834 return STATUS_ERROR(ERROR_DISCONNECTED,
835 "Camera subsystem not available");
836 }
837 sp<VendorTagDescriptorCache> globalCache =
838 VendorTagDescriptorCache::getGlobalVendorTagCache();
839 if (globalCache != nullptr) {
840 *cache = *(globalCache.get());
841 }
842 return Status::ok();
843}
844
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -0700845void CameraService::clearCachedVariables() {
846 BasicClient::BasicClient::sCameraService = nullptr;
847}
848
Emilian Peevb91f1802021-03-23 14:50:28 -0700849int CameraService::getDeviceVersion(const String8& cameraId, int* facing, int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700850 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800851
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800852 int deviceVersion = 0;
853
Emilian Peevf53f66e2017-04-11 14:29:43 +0100854 status_t res;
855 hardware::hidl_version maxVersion{0,0};
856 res = mCameraProviderManager->getHighestSupportedVersion(cameraId.string(),
857 &maxVersion);
858 if (res != OK) return -1;
859 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800860
Emilian Peevf53f66e2017-04-11 14:29:43 +0100861 hardware::CameraInfo info;
862 if (facing) {
863 res = mCameraProviderManager->getCameraInfo(cameraId.string(), &info);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -0800864 if (res != OK) return -1;
Emilian Peevf53f66e2017-04-11 14:29:43 +0100865 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -0700866 if (orientation) {
867 *orientation = info.orientation;
868 }
Igor Murashkin634a5152013-02-20 17:15:11 -0800869 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100870
Igor Murashkin634a5152013-02-20 17:15:11 -0800871 return deviceVersion;
872}
873
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800874Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700875 switch(err) {
876 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800877 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800878 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800879 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
880 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800881 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800882 return STATUS_ERROR(ERROR_DISCONNECTED,
883 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700884 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800885 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
886 "Camera HAL encountered error %d: %s",
887 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700888 }
Igor Murashkinbfc99152013-02-27 12:55:20 -0800889}
890
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800891Status CameraService::makeClient(const sp<CameraService>& cameraService,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800892 const sp<IInterface>& cameraCb, const String16& packageName,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700893 const std::optional<String16>& featureId, const String8& cameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -0700894 int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700895 int servicePid, int deviceVersion, apiLevel effectiveApiLevel, bool overrideForPerfClass,
Ruben Brunkcc776712015-02-17 20:18:47 -0800896 /*out*/sp<BasicClient>* client) {
897
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700898 // Create CameraClient based on device version reported by the HAL.
899 switch(deviceVersion) {
900 case CAMERA_DEVICE_API_VERSION_1_0:
901 ALOGE("Camera using old HAL version: %d", deviceVersion);
902 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
903 "Camera device \"%s\" HAL version %d no longer supported",
904 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800905 break;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700906 case CAMERA_DEVICE_API_VERSION_3_0:
907 case CAMERA_DEVICE_API_VERSION_3_1:
908 case CAMERA_DEVICE_API_VERSION_3_2:
909 case CAMERA_DEVICE_API_VERSION_3_3:
910 case CAMERA_DEVICE_API_VERSION_3_4:
911 case CAMERA_DEVICE_API_VERSION_3_5:
912 case CAMERA_DEVICE_API_VERSION_3_6:
Shuzhen Wang83bff122020-11-20 15:51:39 -0800913 case CAMERA_DEVICE_API_VERSION_3_7:
Ruben Brunkcc776712015-02-17 20:18:47 -0800914 if (effectiveApiLevel == API_1) { // Camera1 API route
915 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800916 *client = new Camera2Client(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800917 cameraId, api1CameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -0700918 facing, sensorOrientation, clientPid, clientUid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700919 servicePid, overrideForPerfClass);
Ruben Brunkcc776712015-02-17 20:18:47 -0800920 } else { // Camera2 API route
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800921 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
922 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800923 *client = new CameraDeviceClient(cameraService, tmp, packageName, featureId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700924 cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid,
925 overrideForPerfClass);
Ruben Brunkcc776712015-02-17 20:18:47 -0800926 }
927 break;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700928 default:
Ruben Brunkcc776712015-02-17 20:18:47 -0800929 // Should not be reachable
930 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800931 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800932 "Camera device \"%s\" has unknown HAL version %d",
933 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800934 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800935 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800936}
937
Ruben Brunk6267b532015-04-30 17:44:07 -0700938String8 CameraService::toString(std::set<userid_t> intSet) {
939 String8 s("");
940 bool first = true;
941 for (userid_t i : intSet) {
942 if (first) {
943 s.appendFormat("%d", i);
944 first = false;
945 } else {
946 s.appendFormat(", %d", i);
947 }
948 }
949 return s;
950}
951
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800952int32_t CameraService::mapToInterface(TorchModeStatus status) {
953 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
954 switch (status) {
955 case TorchModeStatus::NOT_AVAILABLE:
956 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
957 break;
958 case TorchModeStatus::AVAILABLE_OFF:
959 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
960 break;
961 case TorchModeStatus::AVAILABLE_ON:
962 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
963 break;
964 default:
965 ALOGW("Unknown new flash status: %d", status);
966 }
967 return serviceStatus;
968}
969
970CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
971 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
972 switch (status) {
973 case CameraDeviceStatus::NOT_PRESENT:
974 serviceStatus = StatusInternal::NOT_PRESENT;
975 break;
976 case CameraDeviceStatus::PRESENT:
977 serviceStatus = StatusInternal::PRESENT;
978 break;
979 case CameraDeviceStatus::ENUMERATING:
980 serviceStatus = StatusInternal::ENUMERATING;
981 break;
982 default:
983 ALOGW("Unknown new HAL device status: %d", status);
984 }
985 return serviceStatus;
986}
987
988int32_t CameraService::mapToInterface(StatusInternal status) {
989 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
990 switch (status) {
991 case StatusInternal::NOT_PRESENT:
992 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
993 break;
994 case StatusInternal::PRESENT:
995 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
996 break;
997 case StatusInternal::ENUMERATING:
998 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
999 break;
1000 case StatusInternal::NOT_AVAILABLE:
1001 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
1002 break;
1003 case StatusInternal::UNKNOWN:
1004 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
1005 break;
1006 default:
1007 ALOGW("Unknown new internal device status: %d", status);
1008 }
1009 return serviceStatus;
1010}
1011
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001012Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001013 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -07001014
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001015 String16 internalPackageName("cameraserver");
Ruben Brunkcc776712015-02-17 20:18:47 -08001016 String8 id = String8::format("%d", cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001017 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001018 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001019 if (!(ret = connectHelper<ICameraClient,Client>(
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001020 sp<ICameraClient>{nullptr}, id, cameraId,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001021 internalPackageName, {}, uid, USE_CALLING_PID,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001022 API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0,
1023 /*targetSdkVersion*/ __ANDROID_API_FUTURE__, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001024 ).isOk()) {
1025 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
Ruben Brunkb2119af2014-05-09 19:57:56 -07001026 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001027 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001028}
1029
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001030Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -07001031 /*out*/
1032 CameraParameters* parameters) {
1033
1034 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1035
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001036 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001037
1038 if (parameters == NULL) {
1039 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001040 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001041 }
1042
Ruben Brunkcc776712015-02-17 20:18:47 -08001043 String8 id = String8::format("%d", cameraId);
1044
1045 // Check if we already have parameters
1046 {
1047 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001048 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001049 auto cameraState = getCameraState(id);
1050 if (cameraState == nullptr) {
1051 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001052 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1053 "Invalid camera ID: %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001054 }
1055 CameraParameters p = cameraState->getShimParams();
1056 if (!p.isEmpty()) {
1057 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001058 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001059 }
1060 }
1061
Jayant Chowdhary12361932018-08-27 14:46:13 -07001062 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001063 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001064 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001065 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001066 // Error already logged by callee
1067 return ret;
1068 }
1069
1070 // Check for parameters again
1071 {
1072 // Scope for service lock
1073 Mutex::Autolock lock(mServiceLock);
1074 auto cameraState = getCameraState(id);
1075 if (cameraState == nullptr) {
1076 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001077 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1078 "Invalid camera ID: %s", id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001079 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001080 CameraParameters p = cameraState->getShimParams();
1081 if (!p.isEmpty()) {
1082 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001083 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001084 }
1085 }
1086
Ruben Brunkcc776712015-02-17 20:18:47 -08001087 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1088 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001089 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001090}
1091
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001092// Can camera service trust the caller based on the calling UID?
1093static bool isTrustedCallingUid(uid_t uid) {
1094 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001095 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001096 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001097 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001098 return true;
1099 default:
1100 return false;
1101 }
1102}
1103
Nicholas Sauera3620332019-04-03 14:05:17 -07001104static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1105 PermissionController pc;
1106 uid = pc.getPackageUid(packageName, 0);
1107 if (uid <= 0) {
1108 ALOGE("Unknown package: '%s'", String8(packageName).string());
1109 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
1110 return BAD_VALUE;
1111 }
1112
1113 if (userId < 0) {
1114 ALOGE("Invalid user: %d", userId);
1115 dprintf(err, "Invalid user: %d\n", userId);
1116 return BAD_VALUE;
1117 }
1118
1119 uid = multiuser_get_uid(userId, uid);
1120 return NO_ERROR;
1121}
1122
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001123Status CameraService::validateConnectLocked(const String8& cameraId,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001124 const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
1125 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001126
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001127#ifdef __BRILLO__
1128 UNUSED(clientName8);
1129 UNUSED(clientUid);
1130 UNUSED(clientPid);
1131 UNUSED(originalClientPid);
1132#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001133 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1134 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001135 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001136 return allowed;
1137 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001138#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001139
Jayant Chowdhary12361932018-08-27 14:46:13 -07001140 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001141
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001142 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001143 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1144 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001145 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1146 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001147 }
1148
Ruben Brunkcc776712015-02-17 20:18:47 -08001149 if (getCameraState(cameraId) == nullptr) {
1150 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1151 cameraId.string());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001152 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1153 "No camera device with ID \"%s\" available", cameraId.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001154 }
1155
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001156 status_t err = checkIfDeviceIsUsable(cameraId);
1157 if (err != NO_ERROR) {
1158 switch(err) {
1159 case -ENODEV:
1160 case -EBUSY:
1161 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1162 "No camera device with ID \"%s\" currently available", cameraId.string());
1163 default:
1164 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1165 "Unknown error connecting to ID \"%s\"", cameraId.string());
1166 }
1167 }
1168 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001169}
1170
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001171Status CameraService::validateClientPermissionsLocked(const String8& cameraId,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001172 const String8& clientName8, int& clientUid, int& clientPid,
1173 /*out*/int& originalClientPid) const {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001174 int callingPid = CameraThreadState::getCallingPid();
1175 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001176
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001177 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001178 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001179 clientUid = callingUid;
1180 } else if (!isTrustedCallingUid(callingUid)) {
1181 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1182 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001183 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1184 "Untrusted caller (calling PID %d, UID %d) trying to "
1185 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1186 callingPid, callingUid, cameraId.string(),
1187 clientName8.string(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001188 }
1189
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001190 // Check if we can trust clientPid
1191 if (clientPid == USE_CALLING_PID) {
1192 clientPid = callingPid;
1193 } else if (!isTrustedCallingUid(callingUid)) {
1194 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1195 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001196 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1197 "Untrusted caller (calling PID %d, UID %d) trying to "
1198 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1199 callingPid, callingUid, cameraId.string(),
1200 clientName8.string(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001201 }
1202
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001203 if (shouldRejectSystemCameraConnection(cameraId)) {
1204 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1205 cameraId.c_str());
1206 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
1207 "available", cameraId.string());
1208 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001209 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1210 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1211 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
1212 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
1213 "found while trying to query device kind", cameraId.string());
1214
1215 }
1216
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001217 // If it's not calling from cameraserver, check the permission if the
1218 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1219 // android.permission.SYSTEM_CAMERA for system only camera devices).
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001220 if (callingPid != getpid() &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001221 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001222 !checkPermission(sCameraPermission, clientPid, clientUid)) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001223 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001224 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1225 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
1226 clientName8.string(), clientUid, clientPid, cameraId.string());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001227 }
1228
Svet Ganova453d0d2018-01-11 15:37:58 -08001229 // Make sure the UID is in an active state to use the camera
Svet Ganov7b4ab782018-03-25 12:48:10 -07001230 if (!mUidPolicy->isUidActive(callingUid, String16(clientName8))) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001231 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001232 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1233 clientPid, clientUid);
1234 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001235 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1236 "calling UID %d proc state %" PRId32 ")",
1237 clientName8.string(), clientUid, clientPid, cameraId.string(),
1238 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001239 }
1240
Michael Grooverd1d435a2018-12-18 17:39:42 -08001241 // If sensor privacy is enabled then prevent access to the camera
1242 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1243 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1244 return STATUS_ERROR_FMT(ERROR_DISABLED,
1245 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
1246 "is enabled", clientName8.string(), clientUid, clientPid, cameraId.string());
1247 }
1248
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001249 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1250 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001251 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001252 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001253
Ruben Brunk6267b532015-04-30 17:44:07 -07001254 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001255
Ruben Brunka8ca9152015-04-07 14:23:40 -07001256 // Only allow clients who are being used by the current foreground device user, unless calling
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001257 // from our own process OR the caller is using the cameraserver's HIDL interface.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001258 if (getCurrentServingCall() != BinderCallType::HWBINDER && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001259 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001260 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1261 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
1262 toString(mAllowedUsers).string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001263 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1264 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
1265 clientUserId, cameraId.string());
Ruben Brunk36597b22015-03-20 22:15:57 -07001266 }
1267
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001268 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001269}
1270
1271status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
1272 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001273 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001274 if (cameraState == nullptr) {
1275 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1276 cameraId.string());
1277 return -ENODEV;
1278 }
1279
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001280 StatusInternal currentStatus = cameraState->getStatus();
1281 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001282 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
1283 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001284 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001285 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001286 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
1287 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001288 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001289 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001290
Ruben Brunkcc776712015-02-17 20:18:47 -08001291 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001292}
1293
Ruben Brunkcc776712015-02-17 20:18:47 -08001294void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001295 const CameraService::DescriptorPtr& desc, int oomScoreOffset) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001296
Ruben Brunkcc776712015-02-17 20:18:47 -08001297 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001298 auto clientDescriptor =
1299 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
1300 oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08001301 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1302
1303 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
1304 String8(client->getPackageName()));
1305
1306 if (evicted.size() > 0) {
1307 // This should never happen - clients should already have been removed in disconnect
1308 for (auto& i : evicted) {
1309 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
1310 __FUNCTION__, i->getKey().string());
1311 }
1312
1313 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1314 __FUNCTION__);
1315 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001316
1317 // And register a death notification for the client callback. Do
1318 // this last to avoid Binder policy where a nested Binder
1319 // transaction might be pre-empted to service the client death
1320 // notification if the client process dies before linkToDeath is
1321 // invoked.
1322 sp<IBinder> remoteCallback = client->getRemote();
1323 if (remoteCallback != nullptr) {
1324 remoteCallback->linkToDeath(this);
1325 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001326}
1327
1328status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
1329 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001330 int oomScoreOffset,
Ruben Brunkcc776712015-02-17 20:18:47 -08001331 /*out*/
1332 sp<BasicClient>* client,
1333 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001334 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001335 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001336 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001337 DescriptorPtr clientDescriptor;
1338 {
1339 if (effectiveApiLevel == API_1) {
1340 // If we are using API1, any existing client for this camera ID with the same remote
1341 // should be returned rather than evicted to allow MediaRecorder to work properly.
1342
1343 auto current = mActiveClientManager.get(cameraId);
1344 if (current != nullptr) {
1345 auto clientSp = current->getValue();
1346 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001347 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
Shuzhen Wangb2d43f62021-08-25 14:01:11 -07001348 ALOGW("CameraService connect called with a different"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001349 " API level, evicting prior client...");
1350 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001351 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001352 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001353 *client = clientSp;
1354 return NO_ERROR;
1355 }
1356 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001357 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001358 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001359
Ruben Brunkcc776712015-02-17 20:18:47 -08001360 // Get current active client PIDs
1361 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1362 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001363
Emilian Peev8131a262017-02-01 12:33:43 +00001364 std::vector<int> priorityScores(ownerPids.size());
1365 std::vector<int> states(ownerPids.size());
Igor Murashkine6800ce2013-03-04 17:25:57 -08001366
Emilian Peev8131a262017-02-01 12:33:43 +00001367 // Get priority scores of all active PIDs
1368 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1369 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1370 /*out*/&priorityScores[0]);
1371 if (err != OK) {
1372 ALOGE("%s: Priority score query failed: %d",
1373 __FUNCTION__, err);
1374 return err;
1375 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001376
Ruben Brunkcc776712015-02-17 20:18:47 -08001377 // Update all active clients' priorities
Emilian Peev8131a262017-02-01 12:33:43 +00001378 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
Ruben Brunkcc776712015-02-17 20:18:47 -08001379 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
Emilian Peev8131a262017-02-01 12:33:43 +00001380 pidToPriorityMap.emplace(ownerPids[i],
Jayant Chowdharyc578a502019-05-08 10:57:54 -07001381 resource_policy::ClientPriority(priorityScores[i], states[i],
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001382 /* isVendorClient won't get copied over*/ false,
1383 /* oomScoreOffset won't get copied over*/ 0));
Ruben Brunkcc776712015-02-17 20:18:47 -08001384 }
1385 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001386
Ruben Brunkcc776712015-02-17 20:18:47 -08001387 // Get state for the given cameraId
1388 auto state = getCameraState(cameraId);
1389 if (state == nullptr) {
1390 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1391 clientPid, cameraId.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001392 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001393 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001394 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001395
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001396 int32_t actualScore = priorityScores[priorityScores.size() - 1];
1397 int32_t actualState = states[states.size() - 1];
1398
1399 // Make descriptor for incoming client. We store the oomScoreOffset
1400 // since we might need it later on new handleEvictionsLocked and
1401 // ProcessInfoService would not take that into account.
Shuzhen Wang2db86ff2018-04-25 01:11:17 +00001402 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001403 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001404 state->getConflicting(), actualScore, clientPid, actualState,
1405 oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08001406
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001407 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1408
Ruben Brunkcc776712015-02-17 20:18:47 -08001409 // Find clients that would be evicted
1410 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1411
1412 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1413 // background, so we cannot do evictions
1414 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1415 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1416 " priority).", clientPid);
1417
1418 sp<BasicClient> clientSp = clientDescriptor->getValue();
1419 String8 curTime = getFormattedCurrentTime();
1420 auto incompatibleClients =
1421 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1422
1423 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Emilian Peev8131a262017-02-01 12:33:43 +00001424 "(PID %d, score %d state %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001425 cameraId.string(), packageName.string(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001426 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001427
1428 for (auto& i : incompatibleClients) {
1429 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001430 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
1431 i->getKey().string(),
1432 String8{i->getValue()->getPackageName()}.string(),
1433 i->getOwnerId(), i->getPriority().getScore(),
1434 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001435 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00001436 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(),
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001437 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001438 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001439 }
1440
1441 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001442 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001443 mEventLog.add(msg);
1444
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001445 auto current = mActiveClientManager.get(cameraId);
1446 if (current != nullptr) {
1447 return -EBUSY; // CAMERA_IN_USE
1448 } else {
1449 return -EUSERS; // MAX_CAMERAS_IN_USE
1450 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001451 }
1452
1453 for (auto& i : evicted) {
1454 sp<BasicClient> clientSp = i->getValue();
1455 if (clientSp.get() == nullptr) {
1456 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1457
1458 // TODO: Remove this
1459 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1460 __FUNCTION__);
1461 mActiveClientManager.remove(i);
1462 continue;
1463 }
1464
1465 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1466 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001467 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001468
Ruben Brunkcc776712015-02-17 20:18:47 -08001469 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001470 logEvent(String8::format("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00001471 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1472 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001473 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
Emilian Peev8131a262017-02-01 12:33:43 +00001474 i->getOwnerId(), i->getPriority().getScore(),
1475 i->getPriority().getState(), cameraId.string(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001476 packageName.string(), clientPid, clientPriority.getScore(),
1477 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08001478
1479 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001480 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001481 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001482 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001483 }
1484
Ruben Brunkcc776712015-02-17 20:18:47 -08001485 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1486 // other clients from connecting in mServiceLockWrapper if held
1487 mServiceLock.unlock();
1488
1489 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07001490 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001491
1492 // Destroy evicted clients
1493 for (auto& i : evictedClients) {
1494 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001495 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001496 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001497
Jayant Chowdhary12361932018-08-27 14:46:13 -07001498 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08001499
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001500 for (const auto& i : evictedClients) {
1501 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1502 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1503 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1504 if (ret == TIMED_OUT) {
1505 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1506 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1507 mActiveClientManager.toString().string());
1508 return -EBUSY;
1509 }
1510 if (ret != NO_ERROR) {
1511 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1512 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1513 ret, mActiveClientManager.toString().string());
1514 return ret;
1515 }
1516 }
1517
1518 evictedClients.clear();
1519
Ruben Brunkcc776712015-02-17 20:18:47 -08001520 // Once clients have been disconnected, relock
1521 mServiceLock.lock();
1522
1523 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1524 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1525 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001526 }
1527
Ruben Brunkcc776712015-02-17 20:18:47 -08001528 *partial = clientDescriptor;
1529 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001530}
1531
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001532Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001533 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001534 int api1CameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001535 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001536 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001537 int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001538 int targetSdkVersion,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001539 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001540 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001541
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001542 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001543 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001544
1545 String8 id = cameraIdIntToStr(api1CameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001546 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001547 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001548 clientPackageName, {}, clientUid, clientPid, API_1,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001549 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001550
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001551 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001552 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001553 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001554 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001555 }
1556
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001557 *device = client;
1558 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001559}
1560
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001561bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
1562 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001563 // If the client is not a vendor client, don't add listener if
1564 // a) the camera is a publicly hidden secure camera OR
1565 // b) the camera is a system only camera and the client doesn't
1566 // have android.permission.SYSTEM_CAMERA permissions.
1567 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
1568 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1569 !hasPermissionsForSystemCamera(clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001570 return true;
1571 }
1572 return false;
1573}
1574
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001575bool CameraService::shouldRejectSystemCameraConnection(const String8& cameraId) const {
1576 // Rules for rejection:
1577 // 1) If cameraserver tries to access this camera device, accept the
1578 // connection.
1579 // 2) The camera device is a publicly hidden secure camera device AND some
1580 // component is trying to access it on a non-hwbinder thread (generally a non HAL client),
1581 // reject it.
1582 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
1583 // and the serving thread is a non hwbinder thread, the client must have
1584 // android.permission.SYSTEM_CAMERA permissions to connect.
1585
1586 int cPid = CameraThreadState::getCallingPid();
1587 int cUid = CameraThreadState::getCallingUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001588 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
1589 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001590 // This isn't a known camera ID, so it's not a system camera
1591 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
1592 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001593 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001594
1595 // (1) Cameraserver trying to connect, accept.
1596 if (CameraThreadState::getCallingPid() == getpid()) {
1597 return false;
1598 }
1599 // (2)
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001600 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001601 systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
1602 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
1603 return true;
1604 }
1605 // (3) Here we only check for permissions if it is a system only camera device. This is since
1606 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
1607 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
1608 // same behavior for system camera devices.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001609 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001610 systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Jayant Chowdharyc3198c32021-07-28 20:59:14 +00001611 !hasPermissionsForSystemCamera(cPid, cUid, /*logPermissionFailure*/true)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001612 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
1613 cameraId.c_str());
1614 return true;
1615 }
1616
1617 return false;
1618}
1619
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001620Status CameraService::connectDevice(
1621 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001622 const String16& cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001623 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001624 const std::optional<String16>& clientFeatureId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001625 int clientUid, int oomScoreOffset, int targetSdkVersion,
Ruben Brunkcc776712015-02-17 20:18:47 -08001626 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001627 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001628
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001629 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001630 Status ret = Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001631 String8 id = String8(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001632 sp<CameraDeviceClient> client = nullptr;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001633 String16 clientPackageNameAdj = clientPackageName;
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001634 int callingPid = CameraThreadState::getCallingPid();
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001635
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001636 if (getCurrentServingCall() == BinderCallType::HWBINDER) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001637 std::string vendorClient =
1638 StringPrintf("vendor.client.pid<%d>", CameraThreadState::getCallingPid());
1639 clientPackageNameAdj = String16(vendorClient.c_str());
1640 }
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001641
1642 if (oomScoreOffset < 0) {
1643 String8 msg =
1644 String8::format("Cannot increase the priority of a client %s pid %d for "
1645 "camera id %s", String8(clientPackageNameAdj).string(), callingPid,
1646 id.string());
1647 ALOGE("%s: %s", __FUNCTION__, msg.string());
1648 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
1649 }
1650
1651 // enforce system camera permissions
1652 if (oomScoreOffset > 0 &&
1653 !hasPermissionsForSystemCamera(callingPid, CameraThreadState::getCallingUid())) {
1654 String8 msg =
1655 String8::format("Cannot change the priority of a client %s pid %d for "
1656 "camera id %s without SYSTEM_CAMERA permissions",
1657 String8(clientPackageNameAdj).string(), callingPid, id.string());
1658 ALOGE("%s: %s", __FUNCTION__, msg.string());
1659 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.string());
1660 }
1661
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001662 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001663 /*api1CameraId*/-1, clientPackageNameAdj, clientFeatureId,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001664 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, oomScoreOffset,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001665 targetSdkVersion, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08001666
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001667 if(!ret.isOk()) {
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001668 logRejected(id, callingPid, String8(clientPackageNameAdj), ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001669 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001670 }
1671
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001672 *device = client;
Rucha Katakwardf223072021-06-15 10:21:00 -07001673 Mutex::Autolock lock(mServiceLock);
1674
1675 // Clear the previous cached logs and reposition the
1676 // file offset to beginning of the file to log new data.
1677 // If either truncate or lseek fails, close the previous file and create a new one.
1678 if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
1679 ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
1680 // Close the previous memfd.
1681 close(mMemFd);
1682 // If failure to wipe the data, then create a new file and
1683 // assign the new value to mMemFd.
1684 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
1685 if (mMemFd == -1) {
1686 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
1687 }
1688 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001689 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001690}
1691
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001692template<class CALLBACK, class CLIENT>
1693Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001694 int api1CameraId, const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001695 const std::optional<String16>& clientFeatureId, int clientUid, int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001696 apiLevel effectiveApiLevel, bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001697 /*out*/sp<CLIENT>& device) {
1698 binder::Status ret = binder::Status::ok();
1699
1700 String8 clientName8(clientPackageName);
1701
1702 int originalClientPid = 0;
1703
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001704 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001705 "Camera API version %d", clientPid, clientName8.string(), cameraId.string(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001706 static_cast<int>(effectiveApiLevel));
1707
Shuzhen Wang316781a2020-08-18 18:11:01 -07001708 nsecs_t openTimeNs = systemTime();
1709
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001710 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001711 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07001712 int orientation = 0;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001713 bool isNdk = (clientPackageName.size() == 0);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001714 {
1715 // Acquire mServiceLock and prevent other clients from connecting
1716 std::unique_ptr<AutoConditionLock> lock =
1717 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1718
1719 if (lock == nullptr) {
1720 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
1721 , clientPid);
1722 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1723 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
1724 cameraId.string(), clientName8.string(), clientPid);
1725 }
1726
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07001727 // Enforce client permissions and do basic validity checks
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001728 if(!(ret = validateConnectLocked(cameraId, clientName8,
1729 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
1730 return ret;
1731 }
1732
1733 // Check the shim parameters after acquiring lock, if they have already been updated and
1734 // we were doing a shim update, return immediately
1735 if (shimUpdateOnly) {
1736 auto cameraState = getCameraState(cameraId);
1737 if (cameraState != nullptr) {
1738 if (!cameraState->getShimParams().isEmpty()) return ret;
1739 }
1740 }
1741
1742 status_t err;
1743
1744 sp<BasicClient> clientTmp = nullptr;
1745 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
1746 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001747 IInterface::asBinder(cameraCb), clientName8, oomScoreOffset, /*out*/&clientTmp,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001748 /*out*/&partial)) != NO_ERROR) {
1749 switch (err) {
1750 case -ENODEV:
1751 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1752 "No camera device with ID \"%s\" currently available",
1753 cameraId.string());
1754 case -EBUSY:
1755 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1756 "Higher-priority client using camera, ID \"%s\" currently unavailable",
1757 cameraId.string());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001758 case -EUSERS:
1759 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1760 "Too many cameras already open, cannot open camera \"%s\"",
1761 cameraId.string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001762 default:
1763 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1764 "Unexpected error %s (%d) opening camera \"%s\"",
1765 strerror(-err), err, cameraId.string());
1766 }
1767 }
1768
1769 if (clientTmp.get() != nullptr) {
1770 // Handle special case for API1 MediaRecorder where the existing client is returned
1771 device = static_cast<CLIENT*>(clientTmp.get());
1772 return ret;
1773 }
1774
1775 // give flashlight a chance to close devices if necessary.
1776 mFlashlight->prepareDeviceOpen(cameraId);
1777
Emilian Peevb91f1802021-03-23 14:50:28 -07001778 int deviceVersion = getDeviceVersion(cameraId, /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08001779 if (facing == -1) {
1780 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.string());
1781 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1782 "Unable to get camera device \"%s\" facing", cameraId.string());
1783 }
1784
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001785 sp<BasicClient> tmp = nullptr;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001786 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
1787 mPerfClassPrimaryCameraIds, cameraId.string(), targetSdkVersion);
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001788 if(!(ret = makeClient(this, cameraCb, clientPackageName, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07001789 cameraId, api1CameraId, facing, orientation,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001790 clientPid, clientUid, getpid(),
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001791 deviceVersion, effectiveApiLevel, overrideForPerfClass,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001792 /*out*/&tmp)).isOk()) {
1793 return ret;
1794 }
1795 client = static_cast<CLIENT*>(tmp.get());
1796
1797 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
1798 __FUNCTION__);
1799
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07001800 String8 monitorTags = isClientWatched(client.get()) ? mMonitorTags : String8("");
1801 err = client->initialize(mCameraProviderManager, monitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001802 if (err != OK) {
1803 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001804 // Errors could be from the HAL module open call or from AppOpsManager
1805 switch(err) {
1806 case BAD_VALUE:
1807 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1808 "Illegal argument to HAL module for camera \"%s\"", cameraId.string());
1809 case -EBUSY:
1810 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1811 "Camera \"%s\" is already open", cameraId.string());
1812 case -EUSERS:
1813 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1814 "Too many cameras already open, cannot open camera \"%s\"",
1815 cameraId.string());
1816 case PERMISSION_DENIED:
1817 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1818 "No permission to open camera \"%s\"", cameraId.string());
1819 case -EACCES:
1820 return STATUS_ERROR_FMT(ERROR_DISABLED,
1821 "Camera \"%s\" disabled by policy", cameraId.string());
1822 case -ENODEV:
1823 default:
1824 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1825 "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
1826 strerror(-err), err);
1827 }
1828 }
1829
1830 // Update shim paremeters for legacy clients
1831 if (effectiveApiLevel == API_1) {
1832 // Assume we have always received a Client subclass for API1
1833 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
1834 String8 rawParams = shimClient->getParameters();
1835 CameraParameters params(rawParams);
1836
1837 auto cameraState = getCameraState(cameraId);
1838 if (cameraState != nullptr) {
1839 cameraState->setShimParams(params);
1840 } else {
1841 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
1842 __FUNCTION__, cameraId.string());
1843 }
1844 }
1845
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001846 // Set rotate-and-crop override behavior
1847 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
1848 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
Emilian Peev5368ebf2021-10-08 17:52:18 -07001849 } else if (effectiveApiLevel == API_2) {
1850 client->setRotateAndCropOverride(CameraServiceProxyWrapper::getRotateAndCropOverride(
1851 clientPackageName, facing));
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001852 }
1853
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08001854 // Set camera muting behavior
Valentin Iftimec0b8d472021-07-23 20:21:06 +02001855 bool isCameraPrivacyEnabled =
1856 mSensorPrivacyPolicy->isCameraPrivacyEnabled(multiuser_get_user_id(clientUid));
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08001857 if (client->supportsCameraMute()) {
Valentin Iftimec0b8d472021-07-23 20:21:06 +02001858 client->setCameraMute(
1859 mOverrideCameraMuteMode || isCameraPrivacyEnabled);
1860 } else if (isCameraPrivacyEnabled) {
1861 // no camera mute supported, but privacy is on! => disconnect
1862 ALOGI("Camera mute not supported for package: %s, camera id: %s",
1863 String8(client->getPackageName()).string(), cameraId.string());
1864 // Do not hold mServiceLock while disconnecting clients, but
1865 // retain the condition blocking other clients from connecting
1866 // in mServiceLockWrapper if held.
1867 mServiceLock.unlock();
1868 // Clear caller identity temporarily so client disconnect PID
1869 // checks work correctly
1870 int64_t token = CameraThreadState::clearCallingIdentity();
1871 // Note AppOp to trigger the "Unblock" dialog
1872 client->noteAppOp();
1873 client->disconnect();
1874 CameraThreadState::restoreCallingIdentity(token);
1875 // Reacquire mServiceLock
1876 mServiceLock.lock();
1877
1878 return STATUS_ERROR_FMT(ERROR_DISABLED,
1879 "Camera \"%s\" disabled due to camera mute", cameraId.string());
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08001880 }
1881
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001882 if (shimUpdateOnly) {
1883 // If only updating legacy shim parameters, immediately disconnect client
1884 mServiceLock.unlock();
1885 client->disconnect();
1886 mServiceLock.lock();
1887 } else {
1888 // Otherwise, add client to active clients list
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001889 finishConnectLocked(client, partial, oomScoreOffset);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001890 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001891
1892 client->setImageDumpMask(mImageDumpMask);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001893 } // lock is destroyed, allow further connect calls
1894
1895 // Important: release the mutex here so the client can call back into the service from its
1896 // destructor (can be at the end of the call)
1897 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001898
1899 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
1900 CameraServiceProxyWrapper::logOpen(cameraId, facing, clientPackageName,
1901 effectiveApiLevel, isNdk, openLatencyMs);
1902
Cliff Wud3a05312021-04-26 23:07:31 +08001903 {
1904 Mutex::Autolock lock(mInjectionParametersLock);
1905 if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
1906 mInjectionInitPending = false;
1907 status_t res = NO_ERROR;
1908 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
1909 if (clientDescriptor != nullptr) {
1910 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
1911 res = baseClientPtr->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
1912 if (res != OK) {
1913 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
1914 }
1915 } else {
1916 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
1917 __FUNCTION__, mInjectionInternalCamId.string());
1918 res = NO_INIT;
1919 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
1920 }
1921 }
1922 }
1923
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001924 return ret;
1925}
1926
Emilian Peevb2bc5a42019-11-20 16:02:14 -08001927status_t CameraService::addOfflineClient(String8 cameraId, sp<BasicClient> offlineClient) {
1928 if (offlineClient.get() == nullptr) {
1929 return BAD_VALUE;
1930 }
1931
1932 {
1933 // Acquire mServiceLock and prevent other clients from connecting
1934 std::unique_ptr<AutoConditionLock> lock =
1935 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1936
1937 if (lock == nullptr) {
1938 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
1939 , __FUNCTION__, offlineClient->getClientPid());
1940 return TIMED_OUT;
1941 }
1942
1943 auto onlineClientDesc = mActiveClientManager.get(cameraId);
1944 if (onlineClientDesc.get() == nullptr) {
1945 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
1946 cameraId.c_str());
1947 return BAD_VALUE;
1948 }
1949
1950 // Offline clients do not evict or conflict with other online devices. Resource sharing
1951 // conflicts are handled by the camera provider which will either succeed or fail before
1952 // reaching this method.
1953 const auto& onlinePriority = onlineClientDesc->getPriority();
1954 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
1955 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
1956 /*conflictingKeys*/ std::set<String8>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001957 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
1958 /*ommScoreOffset*/ 0);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08001959
1960 // Allow only one offline device per camera
1961 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
1962 if (!incompatibleClients.empty()) {
1963 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
1964 return BAD_VALUE;
1965 }
1966
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07001967 String8 monitorTags = isClientWatched(offlineClient.get()) ? mMonitorTags : String8("");
1968 auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08001969 if (err != OK) {
1970 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
1971 return err;
1972 }
1973
1974 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
1975 if (evicted.size() > 0) {
1976 for (auto& i : evicted) {
1977 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
1978 __FUNCTION__, i->getKey().string());
1979 }
1980
1981 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
1982 "properly", __FUNCTION__);
1983
1984 return BAD_VALUE;
1985 }
1986
1987 logConnectedOffline(offlineClientDesc->getKey(),
1988 static_cast<int>(offlineClientDesc->getOwnerId()),
1989 String8(offlineClient->getPackageName()));
1990
1991 sp<IBinder> remoteCallback = offlineClient->getRemote();
1992 if (remoteCallback != nullptr) {
1993 remoteCallback->linkToDeath(this);
1994 }
1995 } // lock is destroyed, allow further connect calls
1996
1997 return OK;
1998}
1999
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002000Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002001 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002002 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002003
2004 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07002005 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002006 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002007 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2008 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002009 }
2010
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002011 String8 id = String8(cameraId.string());
Jayant Chowdhary12361932018-08-27 14:46:13 -07002012 int uid = CameraThreadState::getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002013
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002014 if (shouldRejectSystemCameraConnection(id)) {
2015 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
2016 " for system only device %s: ", id.string());
2017 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002018 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08002019 auto state = getCameraState(id);
2020 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07002021 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002022 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2023 "Camera ID \"%s\" is a not valid camera ID", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08002024 }
2025
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002026 StatusInternal cameraStatus = state->getStatus();
2027 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002028 cameraStatus != StatusInternal::NOT_AVAILABLE) {
2029 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002030 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2031 "Camera ID \"%s\" is a not valid camera ID", id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002032 }
2033
2034 {
2035 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002036 TorchModeStatus status;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002037 status_t err = getTorchStatusLocked(id, &status);
2038 if (err != OK) {
2039 if (err == NAME_NOT_FOUND) {
2040 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2041 "Camera \"%s\" does not have a flash unit", id.string());
2042 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002043 ALOGE("%s: getting current torch status failed for camera %s",
2044 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002045 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2046 "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
2047 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002048 }
2049
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002050 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002051 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002052 ALOGE("%s: torch mode of camera %s is not available because "
2053 "camera is in use", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002054 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2055 "Torch for camera \"%s\" is not available due to an existing camera user",
2056 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002057 } else {
2058 ALOGE("%s: torch mode of camera %s is not available due to "
2059 "insufficient resources", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002060 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2061 "Torch for camera \"%s\" is not available due to insufficient resources",
2062 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002063 }
2064 }
2065 }
2066
Ruben Brunk99e69712015-05-26 17:25:07 -07002067 {
2068 // Update UID map - this is used in the torch status changed callbacks, so must be done
2069 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07002070 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -07002071 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
2072 mTorchUidMap[id].first = uid;
2073 mTorchUidMap[id].second = uid;
2074 } else {
2075 // Set the pending UID
2076 mTorchUidMap[id].first = uid;
2077 }
2078 }
2079
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002080 status_t err = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07002081
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002082 if (err != OK) {
2083 int32_t errorCode;
2084 String8 msg;
2085 switch (err) {
2086 case -ENOSYS:
2087 msg = String8::format("Camera \"%s\" has no flashlight",
2088 id.string());
2089 errorCode = ERROR_ILLEGAL_ARGUMENT;
2090 break;
Dijack Dongc8a6f252021-09-17 16:21:16 +08002091 case -EBUSY:
2092 msg = String8::format("Camera \"%s\" is in use",
2093 id.string());
2094 errorCode = ERROR_CAMERA_IN_USE;
2095 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002096 default:
2097 msg = String8::format(
2098 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
2099 id.string(), enabled, strerror(-err), err);
2100 errorCode = ERROR_INVALID_OPERATION;
2101 }
2102 ALOGE("%s: %s", __FUNCTION__, msg.string());
Rucha Katakward9ea6452021-05-06 11:57:16 -07002103 logServiceError(msg,errorCode);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002104 return STATUS_ERROR(errorCode, msg.string());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002105 }
2106
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002107 {
2108 // update the link to client's death
2109 Mutex::Autolock al(mTorchClientMapMutex);
2110 ssize_t index = mTorchClientMap.indexOfKey(id);
2111 if (enabled) {
2112 if (index == NAME_NOT_FOUND) {
2113 mTorchClientMap.add(id, clientBinder);
2114 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07002115 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002116 mTorchClientMap.replaceValueAt(index, clientBinder);
2117 }
2118 clientBinder->linkToDeath(this);
2119 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07002120 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002121 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002122 }
2123
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002124 int clientPid = CameraThreadState::getCallingPid();
2125 const char *id_cstr = id.c_str();
2126 const char *torchState = enabled ? "on" : "off";
2127 ALOGI("Torch for camera id %s turned %s for client PID %d", id_cstr, torchState, clientPid);
2128 logTorchEvent(id_cstr, torchState , clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002129 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002130}
2131
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002132Status CameraService::notifySystemEvent(int32_t eventId,
2133 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002134 const int pid = CameraThreadState::getCallingPid();
2135 const int selfPid = getpid();
2136
2137 // Permission checks
2138 if (pid != selfPid) {
2139 // Ensure we're being called by system_server, or similar process with
2140 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002141 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002142 const int uid = CameraThreadState::getCallingUid();
2143 ALOGE("Permission Denial: cannot send updates to camera service about system"
2144 " events from pid=%d, uid=%d", pid, uid);
2145 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09002146 "No permission to send updates to camera service about system events"
2147 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002148 }
2149 }
2150
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002151 ATRACE_CALL();
2152
Ruben Brunk36597b22015-03-20 22:15:57 -07002153 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002154 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08002155 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002156 // from a system server crash
2157 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08002158 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002159 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07002160 break;
2161 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002162 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07002163 default: {
2164 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
2165 eventId);
2166 break;
2167 }
2168 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002169 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002170}
2171
Emilian Peev53722fa2019-02-22 17:47:20 -08002172void CameraService::notifyMonitoredUids() {
2173 Mutex::Autolock lock(mStatusListenerLock);
2174
2175 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002176 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Emilian Peev53722fa2019-02-22 17:47:20 -08002177 if (!ret.isOk()) {
2178 ALOGE("%s: Failed to trigger permission callback: %d", __FUNCTION__,
2179 ret.exceptionCode());
2180 }
2181 }
2182}
2183
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002184Status CameraService::notifyDeviceStateChange(int64_t newState) {
2185 const int pid = CameraThreadState::getCallingPid();
2186 const int selfPid = getpid();
2187
2188 // Permission checks
2189 if (pid != selfPid) {
2190 // Ensure we're being called by system_server, or similar process with
2191 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002192 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002193 const int uid = CameraThreadState::getCallingUid();
2194 ALOGE("Permission Denial: cannot send updates to camera service about device"
2195 " state changes from pid=%d, uid=%d", pid, uid);
2196 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2197 "No permission to send updates to camera service about device state"
2198 " changes from pid=%d, uid=%d", pid, uid);
2199 }
2200 }
2201
2202 ATRACE_CALL();
2203
2204 using hardware::camera::provider::V2_5::DeviceState;
2205 hardware::hidl_bitfield<DeviceState> newDeviceState{};
2206 if (newState & ICameraService::DEVICE_STATE_BACK_COVERED) {
2207 newDeviceState |= DeviceState::BACK_COVERED;
2208 }
2209 if (newState & ICameraService::DEVICE_STATE_FRONT_COVERED) {
2210 newDeviceState |= DeviceState::FRONT_COVERED;
2211 }
2212 if (newState & ICameraService::DEVICE_STATE_FOLDED) {
2213 newDeviceState |= DeviceState::FOLDED;
2214 }
2215 // Only map vendor bits directly
2216 uint64_t vendorBits = static_cast<uint64_t>(newState) & 0xFFFFFFFF00000000l;
2217 newDeviceState |= vendorBits;
2218
2219 ALOGV("%s: New device state 0x%" PRIx64, __FUNCTION__, newDeviceState);
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002220 mCameraProviderManager->notifyDeviceStateChange(newDeviceState);
2221
2222 return Status::ok();
2223}
2224
Emilian Peev8b64f282021-03-25 16:49:57 -07002225Status CameraService::notifyDisplayConfigurationChange() {
2226 ATRACE_CALL();
2227 const int callingPid = CameraThreadState::getCallingPid();
2228 const int selfPid = getpid();
2229
2230 // Permission checks
2231 if (callingPid != selfPid) {
2232 // Ensure we're being called by system_server, or similar process with
2233 // permissions to notify the camera service about system events
2234 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
2235 const int uid = CameraThreadState::getCallingUid();
2236 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
2237 " changes from pid=%d, uid=%d", callingPid, uid);
2238 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2239 "No permission to send updates to camera service about orientation"
2240 " changes from pid=%d, uid=%d", callingPid, uid);
2241 }
2242 }
2243
2244 Mutex::Autolock lock(mServiceLock);
2245
2246 // Don't do anything if rotate-and-crop override via cmd is active
2247 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
2248
2249 const auto clients = mActiveClientManager.getAll();
2250 for (auto& current : clients) {
2251 if (current != nullptr) {
2252 const auto basicClient = current->getValue();
Emilian Peeve23f1d92021-09-20 14:56:01 -07002253 if (basicClient.get() != nullptr && basicClient->canCastToApiClient(API_2)) {
Emilian Peev5368ebf2021-10-08 17:52:18 -07002254 basicClient->setRotateAndCropOverride(
2255 CameraServiceProxyWrapper::getRotateAndCropOverride(
2256 basicClient->getPackageName(), basicClient->getCameraFacing()));
Emilian Peev8b64f282021-03-25 16:49:57 -07002257 }
2258 }
2259 }
2260
2261 return Status::ok();
2262}
2263
2264Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002265 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
2266 ATRACE_CALL();
2267 if (!concurrentCameraIds) {
2268 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
2269 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
2270 }
2271
2272 if (!mInitialized) {
2273 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Rucha Katakward9ea6452021-05-06 11:57:16 -07002274 logServiceError(String8::format("Camera subsystem is not available"),ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002275 return STATUS_ERROR(ERROR_DISCONNECTED,
2276 "Camera subsystem is not available");
2277 }
2278 // First call into the provider and get the set of concurrent camera
2279 // combinations
2280 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07002281 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002282 for (auto &combination : concurrentCameraCombinations) {
2283 std::vector<std::string> validCombination;
2284 for (auto &cameraId : combination) {
2285 // if the camera state is not present, skip
2286 String8 cameraIdStr(cameraId.c_str());
2287 auto state = getCameraState(cameraIdStr);
2288 if (state == nullptr) {
2289 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
2290 continue;
2291 }
2292 StatusInternal status = state->getStatus();
2293 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
2294 continue;
2295 }
2296 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
2297 continue;
2298 }
2299 validCombination.push_back(cameraId);
2300 }
2301 if (validCombination.size() != 0) {
2302 concurrentCameraIds->push_back(std::move(validCombination));
2303 }
2304 }
2305 return Status::ok();
2306}
2307
2308Status CameraService::isConcurrentSessionConfigurationSupported(
2309 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002310 int targetSdkVersion, /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002311 if (!isSupported) {
2312 ALOGE("%s: isSupported is NULL", __FUNCTION__);
2313 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
2314 }
2315
2316 if (!mInitialized) {
2317 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2318 return STATUS_ERROR(ERROR_DISCONNECTED,
2319 "Camera subsystem is not available");
2320 }
2321
2322 // Check for camera permissions
2323 int callingPid = CameraThreadState::getCallingPid();
2324 int callingUid = CameraThreadState::getCallingUid();
2325 if ((callingPid != getpid()) && !checkPermission(sCameraPermission, callingPid, callingUid)) {
2326 ALOGE("%s: pid %d doesn't have camera permissions", __FUNCTION__, callingPid);
2327 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2328 "android.permission.CAMERA needed to call"
2329 "isConcurrentSessionConfigurationSupported");
2330 }
2331
2332 status_t res =
2333 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002334 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
2335 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002336 if (res != OK) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07002337 logServiceError(String8::format("Unable to query session configuration support"),
2338 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002339 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
2340 "support %s (%d)", strerror(-res), res);
2341 }
2342 return Status::ok();
2343}
2344
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002345Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
2346 /*out*/
2347 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002348 return addListenerHelper(listener, cameraStatuses);
2349}
2350
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002351binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
2352 std::vector<hardware::CameraStatus>* cameraStatuses) {
2353 return addListenerHelper(listener, cameraStatuses, false, true);
2354}
2355
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002356Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
2357 /*out*/
2358 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002359 bool isVendorListener, bool isProcessLocalTest) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002360
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002361 ATRACE_CALL();
2362
Igor Murashkinbfc99152013-02-27 12:55:20 -08002363 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08002364
Ruben Brunk3450ba72015-06-16 11:00:37 -07002365 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002366 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002367 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002368 }
2369
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002370 auto clientUid = CameraThreadState::getCallingUid();
2371 auto clientPid = CameraThreadState::getCallingPid();
Shuzhen Wang695044d2020-03-06 09:02:23 -08002372 bool openCloseCallbackAllowed = checkPermission(sCameraOpenCloseListenerPermission,
Jayant Chowdharyc3198c32021-07-28 20:59:14 +00002373 clientPid, clientUid, /*logPermissionFailure*/false);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002374
Igor Murashkinbfc99152013-02-27 12:55:20 -08002375 Mutex::Autolock lock(mServiceLock);
2376
Ruben Brunkcc776712015-02-17 20:18:47 -08002377 {
2378 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08002379 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002380 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002381 ALOGW("%s: Tried to add listener %p which was already subscribed",
2382 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002383 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08002384 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002385 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002386
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002387 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08002388 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
2389 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002390 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08002391 if (ret != NO_ERROR) {
2392 String8 msg = String8::format("Failed to initialize service listener: %s (%d)",
2393 strerror(-ret), ret);
Rucha Katakward9ea6452021-05-06 11:57:16 -07002394 logServiceError(msg,ERROR_ILLEGAL_ARGUMENT);
Emilian Peev53722fa2019-02-22 17:47:20 -08002395 ALOGE("%s: %s", __FUNCTION__, msg.string());
2396 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
2397 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002398 // The listener still needs to be added to the list of listeners, regardless of what
2399 // permissions the listener process has / whether it is a vendor listener. Since it might be
2400 // eligible to listen to other camera ids.
2401 mListenerList.emplace_back(serviceListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08002402 mUidPolicy->registerMonitorUid(clientUid);
Igor Murashkinbfc99152013-02-27 12:55:20 -08002403 }
2404
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002405 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07002406 {
Ruben Brunkcc776712015-02-17 20:18:47 -08002407 Mutex::Autolock lock(mCameraStatesLock);
2408 for (auto& i : mCameraStates) {
Shuzhen Wang43858162020-01-10 13:42:15 -08002409 cameraStatuses->emplace_back(i.first,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07002410 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
2411 openCloseCallbackAllowed ? i.second->getClientPackage() : String8::empty());
Igor Murashkincba2c162013-03-20 15:56:31 -07002412 }
2413 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002414 // Remove the camera statuses that should be hidden from the client, we do
2415 // this after collecting the states in order to avoid holding
2416 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
2417 // the same time.
2418 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
2419 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
2420 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
2421 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
2422 ALOGE("%s: Invalid camera id %s, skipping status update",
2423 __FUNCTION__, s.cameraId.c_str());
2424 return true;
2425 }
2426 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
2427 clientUid);}), cameraStatuses->end());
2428
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002429 //cameraStatuses will have non-eligible camera ids removed.
2430 std::set<String16> idsChosenForCallback;
2431 for (const auto &s : *cameraStatuses) {
2432 idsChosenForCallback.insert(String16(s.cameraId));
2433 }
Igor Murashkincba2c162013-03-20 15:56:31 -07002434
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002435 /*
2436 * Immediately signal current torch status to this listener only
2437 * This may be a subset of all the devices, so don't include it in the response directly
2438 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002439 {
2440 Mutex::Autolock al(mTorchStatusMutex);
2441 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002442 String16 id = String16(mTorchStatusMap.keyAt(i).string());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002443 // The camera id is visible to the client. Fine to send torch
2444 // callback.
2445 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
2446 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
2447 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002448 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002449 }
2450
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002451 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08002452}
Ruben Brunkcc776712015-02-17 20:18:47 -08002453
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002454Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002455 ATRACE_CALL();
2456
Igor Murashkinbfc99152013-02-27 12:55:20 -08002457 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
2458
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002459 if (listener == 0) {
2460 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002461 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002462 }
2463
Igor Murashkinbfc99152013-02-27 12:55:20 -08002464 Mutex::Autolock lock(mServiceLock);
2465
Ruben Brunkcc776712015-02-17 20:18:47 -08002466 {
2467 Mutex::Autolock lock(mStatusListenerLock);
2468 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002469 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
2470 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid());
2471 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08002472 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002473 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002474 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002475 }
2476 }
2477
2478 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
2479 __FUNCTION__, listener.get());
2480
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002481 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08002482}
2483
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002484Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002485
2486 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002487 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
2488
2489 if (parameters == NULL) {
2490 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002491 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07002492 }
2493
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002494 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002495
2496 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002497 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07002498 // Error logged by caller
2499 return ret;
2500 }
2501
2502 String8 shimParamsString8 = shimParams.flatten();
2503 String16 shimParamsString16 = String16(shimParamsString8);
2504
2505 *parameters = shimParamsString16;
2506
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002507 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07002508}
2509
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002510Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
2511 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002512 ATRACE_CALL();
2513
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002514 const String8 id = String8(cameraId);
2515
2516 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002517
2518 switch (apiVersion) {
2519 case API_VERSION_1:
2520 case API_VERSION_2:
2521 break;
2522 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002523 String8 msg = String8::format("Unknown API version %d", apiVersion);
2524 ALOGE("%s: %s", __FUNCTION__, msg.string());
2525 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002526 }
2527
Emilian Peev28ad2ea2017-02-07 16:14:32 +00002528 int deviceVersion = getDeviceVersion(id);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002529 switch (deviceVersion) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002530 case CAMERA_DEVICE_API_VERSION_1_0:
2531 case CAMERA_DEVICE_API_VERSION_3_0:
2532 case CAMERA_DEVICE_API_VERSION_3_1:
2533 if (apiVersion == API_VERSION_2) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002534 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without shim",
2535 __FUNCTION__, id.string(), deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002536 *isSupported = false;
2537 } else { // if (apiVersion == API_VERSION_1) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002538 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always supported",
2539 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002540 *isSupported = true;
2541 }
2542 break;
2543 case CAMERA_DEVICE_API_VERSION_3_2:
2544 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -07002545 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002546 case CAMERA_DEVICE_API_VERSION_3_5:
Yin-Chia Yeh56d98ba2020-01-16 16:57:14 -08002547 case CAMERA_DEVICE_API_VERSION_3_6:
Shuzhen Wang83bff122020-11-20 15:51:39 -08002548 case CAMERA_DEVICE_API_VERSION_3_7:
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002549 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
2550 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002551 *isSupported = true;
2552 break;
2553 case -1: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002554 String8 msg = String8::format("Unknown camera ID %s", id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002555 ALOGE("%s: %s", __FUNCTION__, msg.string());
2556 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002557 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002558 default: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002559 String8 msg = String8::format("Unknown device version %x for device %s",
2560 deviceVersion, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002561 ALOGE("%s: %s", __FUNCTION__, msg.string());
2562 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
2563 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07002564 }
2565
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002566 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002567}
2568
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002569Status CameraService::isHiddenPhysicalCamera(const String16& cameraId,
2570 /*out*/ bool *isSupported) {
2571 ATRACE_CALL();
2572
2573 const String8 id = String8(cameraId);
2574
2575 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
2576 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(id.string());
2577
2578 return Status::ok();
2579}
2580
Cliff Wud8cae102021-03-11 01:37:42 +08002581Status CameraService::injectCamera(
2582 const String16& packageName, const String16& internalCamId,
2583 const String16& externalCamId,
2584 const sp<ICameraInjectionCallback>& callback,
2585 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08002586 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08002587 ATRACE_CALL();
2588
2589 if (!checkCallingPermission(sCameraInjectExternalCameraPermission)) {
2590 const int pid = CameraThreadState::getCallingPid();
2591 const int uid = CameraThreadState::getCallingUid();
2592 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
2593 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2594 "Permission Denial: no permission to inject camera");
2595 }
2596
2597 ALOGV(
2598 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
2599 "%s",
2600 __FUNCTION__, String8(packageName).string(),
2601 String8(internalCamId).string(), String8(externalCamId).string());
2602
Cliff Wud3a05312021-04-26 23:07:31 +08002603 {
2604 Mutex::Autolock lock(mInjectionParametersLock);
2605 mInjectionInternalCamId = String8(internalCamId);
2606 mInjectionExternalCamId = String8(externalCamId);
2607 status_t res = NO_ERROR;
2608 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2609 // If the client already exists, we can directly connect to the camera device through the
2610 // client's injectCamera(), otherwise we need to wait until the client is established
2611 // (execute connectHelper()) before injecting the camera to the camera device.
2612 if (clientDescriptor != nullptr) {
2613 mInjectionInitPending = false;
2614 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
2615 res = baseClientPtr->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
2616 if(res != OK) {
2617 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2618 }
2619 } else {
2620 mInjectionInitPending = true;
2621 }
2622 }
Cliff Wud8cae102021-03-11 01:37:42 +08002623 mInjectionStatusListener->addListener(callback);
2624 *cameraInjectionSession = new CameraInjectionSession(this);
2625
Cliff Wud3a05312021-04-26 23:07:31 +08002626 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08002627}
2628
Ruben Brunkcc776712015-02-17 20:18:47 -08002629void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002630 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002631 for (auto& i : mActiveClientManager.getAll()) {
2632 auto clientSp = i->getValue();
2633 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002634 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08002635 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08002636 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07002637 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002638 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08002639}
2640
Ruben Brunkcc776712015-02-17 20:18:47 -08002641bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002642 bool ret = false;
2643 {
2644 // Acquire mServiceLock and prevent other clients from connecting
2645 std::unique_ptr<AutoConditionLock> lock =
2646 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08002647
Igor Murashkin634a5152013-02-20 17:15:11 -08002648
Ruben Brunkcc776712015-02-17 20:18:47 -08002649 std::vector<sp<BasicClient>> evicted;
2650 for (auto& i : mActiveClientManager.getAll()) {
2651 auto clientSp = i->getValue();
2652 if (clientSp.get() == nullptr) {
2653 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2654 mActiveClientManager.remove(i);
2655 continue;
2656 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08002657 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002658 mActiveClientManager.remove(i);
2659 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08002660
Ruben Brunkcc776712015-02-17 20:18:47 -08002661 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002662 clientSp->notifyError(
2663 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002664 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08002665 }
2666 }
2667
Ruben Brunkcc776712015-02-17 20:18:47 -08002668 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2669 // other clients from connecting in mServiceLockWrapper if held
2670 mServiceLock.unlock();
2671
Ruben Brunk36597b22015-03-20 22:15:57 -07002672 // Do not clear caller identity, remote caller should be client proccess
2673
Ruben Brunkcc776712015-02-17 20:18:47 -08002674 for (auto& i : evicted) {
2675 if (i.get() != nullptr) {
2676 i->disconnect();
2677 ret = true;
2678 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002679 }
2680
Ruben Brunkcc776712015-02-17 20:18:47 -08002681 // Reacquire mServiceLock
2682 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08002683
Ruben Brunkcc776712015-02-17 20:18:47 -08002684 } // lock is destroyed, allow further connect calls
2685
2686 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07002687}
2688
Ruben Brunkcc776712015-02-17 20:18:47 -08002689std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
2690 const String8& cameraId) const {
2691 std::shared_ptr<CameraState> state;
2692 {
2693 Mutex::Autolock lock(mCameraStatesLock);
2694 auto iter = mCameraStates.find(cameraId);
2695 if (iter != mCameraStates.end()) {
2696 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002697 }
2698 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002699 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002700}
2701
Ruben Brunkcc776712015-02-17 20:18:47 -08002702sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
2703 // Remove from active clients list
2704 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
2705 if (clientDescriptorPtr == nullptr) {
2706 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
2707 cameraId.string());
2708 return sp<BasicClient>{nullptr};
2709 }
2710
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002711 sp<BasicClient> client = clientDescriptorPtr->getValue();
2712 if (client.get() != nullptr) {
2713 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
2714 }
2715 return client;
Keun young Parkd8973a72012-03-28 14:13:09 -07002716}
2717
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002718void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07002719 // Acquire mServiceLock and prevent other clients from connecting
2720 std::unique_ptr<AutoConditionLock> lock =
2721 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
2722
Ruben Brunk6267b532015-04-30 17:44:07 -07002723 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002724 for (size_t i = 0; i < newUserIds.size(); i++) {
2725 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07002726 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002727 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07002728 return;
2729 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002730 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07002731 }
2732
Ruben Brunka8ca9152015-04-07 14:23:40 -07002733
Ruben Brunk6267b532015-04-30 17:44:07 -07002734 if (newAllowedUsers == mAllowedUsers) {
2735 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
2736 return;
2737 }
2738
2739 logUserSwitch(mAllowedUsers, newAllowedUsers);
2740
2741 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07002742
2743 // Current user has switched, evict all current clients.
2744 std::vector<sp<BasicClient>> evicted;
2745 for (auto& i : mActiveClientManager.getAll()) {
2746 auto clientSp = i->getValue();
2747
2748 if (clientSp.get() == nullptr) {
2749 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2750 continue;
2751 }
2752
Ruben Brunk6267b532015-04-30 17:44:07 -07002753 // Don't evict clients that are still allowed.
2754 uid_t clientUid = clientSp->getClientUid();
2755 userid_t clientUserId = multiuser_get_user_id(clientUid);
2756 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
2757 continue;
2758 }
2759
Ruben Brunk36597b22015-03-20 22:15:57 -07002760 evicted.push_back(clientSp);
2761
2762 String8 curTime = getFormattedCurrentTime();
2763
2764 ALOGE("Evicting conflicting client for camera ID %s due to user change",
2765 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07002766
Ruben Brunk36597b22015-03-20 22:15:57 -07002767 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002768 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00002769 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
2770 " to user switch.", i->getKey().string(),
2771 String8{clientSp->getPackageName()}.string(),
2772 i->getOwnerId(), i->getPriority().getScore(),
2773 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07002774
2775 }
2776
2777 // Do not hold mServiceLock while disconnecting clients, but retain the condition
2778 // blocking other clients from connecting in mServiceLockWrapper if held.
2779 mServiceLock.unlock();
2780
2781 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07002782 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07002783
2784 for (auto& i : evicted) {
2785 i->disconnect();
2786 }
2787
Jayant Chowdhary12361932018-08-27 14:46:13 -07002788 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07002789
2790 // Reacquire mServiceLock
2791 mServiceLock.lock();
2792}
Ruben Brunkcc776712015-02-17 20:18:47 -08002793
Ruben Brunka8ca9152015-04-07 14:23:40 -07002794void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002795 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07002796 Mutex::Autolock l(mLogLock);
Rucha Katakward9ea6452021-05-06 11:57:16 -07002797 String8 msg = String8::format("%s : %s", curTime.string(), event);
2798 // For service error events, print the msg only once.
2799 if(!msg.contains("SERVICE ERROR")) {
2800 mEventLog.add(msg);
2801 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
2802 // Error event not added to the dumpsys log before
2803 mEventLog.add(msg);
2804 sServiceErrorEventSet.insert(msg);
2805 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002806}
2807
Ruben Brunka8ca9152015-04-07 14:23:40 -07002808void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002809 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002810 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002811 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002812 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002813}
2814
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002815void CameraService::logDisconnectedOffline(const char* cameraId, int clientPid,
2816 const char* clientPackage) {
2817 // Log the clients evicted
2818 logEvent(String8::format("DISCONNECT offline device %s client for package %s (PID %d)",
2819 cameraId, clientPackage, clientPid));
2820}
2821
Ruben Brunka8ca9152015-04-07 14:23:40 -07002822void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002823 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002824 // Log the clients evicted
2825 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002826 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002827}
2828
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002829void CameraService::logConnectedOffline(const char* cameraId, int clientPid,
2830 const char* clientPackage) {
2831 // Log the clients evicted
2832 logEvent(String8::format("CONNECT offline device %s client for package %s (PID %d)", cameraId,
2833 clientPackage, clientPid));
2834}
2835
Ruben Brunka8ca9152015-04-07 14:23:40 -07002836void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002837 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002838 // Log the client rejected
2839 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002840 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002841}
2842
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002843void CameraService::logTorchEvent(const char* cameraId, const char *torchState, int clientPid) {
2844 // Log torch event
2845 logEvent(String8::format("Torch for camera id %s turned %s for client PID %d", cameraId,
2846 torchState, clientPid));
2847}
2848
Ruben Brunk6267b532015-04-30 17:44:07 -07002849void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
2850 const std::set<userid_t>& newUserIds) {
2851 String8 newUsers = toString(newUserIds);
2852 String8 oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002853 if (oldUsers.size() == 0) {
2854 oldUsers = "<None>";
2855 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07002856 // Log the new and old users
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002857 logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
Ruben Brunk6267b532015-04-30 17:44:07 -07002858 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002859}
2860
2861void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
2862 // Log the device removal
2863 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
2864}
2865
2866void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
2867 // Log the device removal
2868 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
2869}
2870
2871void CameraService::logClientDied(int clientPid, const char* reason) {
2872 // Log the device removal
2873 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07002874}
2875
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002876void CameraService::logServiceError(const char* msg, int errorCode) {
2877 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002878 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002879}
2880
Ruben Brunk36597b22015-03-20 22:15:57 -07002881status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
2882 uint32_t flags) {
2883
Mathias Agopian65ab4712010-07-14 17:59:35 -07002884 // Permission checks
2885 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002886 case SHELL_COMMAND_TRANSACTION: {
2887 int in = data.readFileDescriptor();
2888 int out = data.readFileDescriptor();
2889 int err = data.readFileDescriptor();
2890 int argc = data.readInt32();
2891 Vector<String16> args;
2892 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
2893 args.add(data.readString16());
2894 }
2895 sp<IBinder> unusedCallback;
2896 sp<IResultReceiver> resultReceiver;
2897 status_t status;
2898 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
2899 return status;
2900 }
2901 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
2902 return status;
2903 }
2904 status = shellCommand(in, out, err, args);
2905 if (resultReceiver != nullptr) {
2906 resultReceiver->send(status);
2907 }
2908 return NO_ERROR;
2909 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002910 }
2911
2912 return BnCameraService::onTransact(code, data, reply, flags);
2913}
2914
Mathias Agopian65ab4712010-07-14 17:59:35 -07002915// We share the media players for shutter and recording sound for all clients.
2916// A reference count is kept to determine when we will actually release the
2917// media players.
2918
Jaekyun Seokef498052018-03-23 13:09:44 +09002919sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
2920 sp<MediaPlayer> mp = new MediaPlayer();
2921 status_t error;
2922 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08002923 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09002924 error = mp->prepare();
2925 }
2926 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00002927 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09002928 mp->disconnect();
2929 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002930 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002931 }
2932 return mp;
2933}
2934
username5755fea2018-12-27 09:48:08 +08002935void CameraService::increaseSoundRef() {
2936 Mutex::Autolock lock(mSoundLock);
2937 mSoundRef++;
2938}
2939
2940void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002941 ATRACE_CALL();
2942
username5755fea2018-12-27 09:48:08 +08002943 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
2944 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
2945 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
2946 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
2947 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
2948 }
2949 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
2950 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
2951 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
2952 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002953 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08002954 }
2955 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
2956 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
2957 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
2958 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
2959 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002960 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002961}
2962
username5755fea2018-12-27 09:48:08 +08002963void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002964 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002965 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002966 if (--mSoundRef) return;
2967
2968 for (int i = 0; i < NUM_SOUNDS; i++) {
2969 if (mSoundPlayer[i] != 0) {
2970 mSoundPlayer[i]->disconnect();
2971 mSoundPlayer[i].clear();
2972 }
2973 }
2974}
2975
2976void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002977 ATRACE_CALL();
2978
Mathias Agopian65ab4712010-07-14 17:59:35 -07002979 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07002980 if (kind < 0 || kind >= NUM_SOUNDS) {
2981 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
2982 return;
2983 }
2984
Mathias Agopian65ab4712010-07-14 17:59:35 -07002985 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002986 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002987 sp<MediaPlayer> player = mSoundPlayer[kind];
2988 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08002989 player->seekTo(0);
2990 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002991 }
2992}
2993
2994// ----------------------------------------------------------------------------
2995
2996CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07002997 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002998 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09002999 const std::optional<String16>& clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003000 const String8& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07003001 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003002 int clientPid, uid_t clientUid,
3003 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08003004 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08003005 IInterface::asBinder(cameraClient),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08003006 clientPackageName, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07003007 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003008 clientPid, clientUid,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003009 servicePid),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003010 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08003011{
Jayant Chowdhary12361932018-08-27 14:46:13 -07003012 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003013 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003014
Igor Murashkin44cfcf02013-03-01 16:22:28 -08003015 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003016
username5755fea2018-12-27 09:48:08 +08003017 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003018
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003019 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003020}
3021
Mathias Agopian65ab4712010-07-14 17:59:35 -07003022// tear down the client
3023CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003024 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08003025 mDestructionStarted = true;
3026
username5755fea2018-12-27 09:48:08 +08003027 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003028 // unconditionally disconnect. function is idempotent
3029 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003030}
3031
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003032sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
3033
Igor Murashkin634a5152013-02-20 17:15:11 -08003034CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003035 const sp<IBinder>& remoteCallback,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09003036 const String16& clientPackageName, const std::optional<String16>& clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07003037 const String8& cameraIdStr, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003038 int clientPid, uid_t clientUid,
3039 int servicePid):
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003040 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07003041 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09003042 mClientPackageName(clientPackageName), mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08003043 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003044 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07003045 mDisconnected(false), mUidIsTrusted(false),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003046 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003047 mRemoteBinder(remoteCallback),
3048 mOpsActive(false),
3049 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08003050{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003051 if (sCameraService == nullptr) {
3052 sCameraService = cameraService;
3053 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08003054
3055 // In some cases the calling code has no access to the package it runs under.
3056 // For example, NDK camera API.
3057 // In this case we will get the packages for the calling UID and pick the first one
3058 // for attributing the app op. This will work correctly for runtime permissions
3059 // as for legacy apps we will toggle the app op for all packages in the UID.
3060 // The caveat is that the operation may be attributed to the wrong package and
3061 // stats based on app ops may be slightly off.
3062 if (mClientPackageName.size() <= 0) {
3063 sp<IServiceManager> sm = defaultServiceManager();
3064 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
3065 if (binder == 0) {
3066 ALOGE("Cannot get permission service");
3067 // Leave mClientPackageName unchanged (empty) and the further interaction
3068 // with camera will fail in BasicClient::startCameraOps
3069 return;
3070 }
3071
3072 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
3073 Vector<String16> packages;
3074
3075 permCtrl->getPackagesForUid(mClientUid, packages);
3076
3077 if (packages.isEmpty()) {
3078 ALOGE("No packages for calling UID");
3079 // Leave mClientPackageName unchanged (empty) and the further interaction
3080 // with camera will fail in BasicClient::startCameraOps
3081 return;
3082 }
3083 mClientPackageName = packages[0];
3084 }
Steven Moreland89a2c5c2020-01-31 15:02:25 -08003085 if (getCurrentServingCall() != BinderCallType::HWBINDER) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003086 mAppOpsManager = std::make_unique<AppOpsManager>();
3087 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07003088
3089 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08003090}
3091
3092CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003093 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08003094 mDestructionStarted = true;
3095}
3096
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003097binder::Status CameraService::BasicClient::disconnect() {
3098 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003099 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003100 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07003101 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07003102 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08003103
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003104 sCameraService->removeByClient(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003105 sCameraService->logDisconnected(mCameraIdStr, mClientPid, String8(mClientPackageName));
Peter Kalauskasa29c1352018-10-10 12:05:42 -07003106 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
3107 mCameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003108
3109 sp<IBinder> remote = getRemote();
3110 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003111 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08003112 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003113
3114 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07003115 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003116 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
3117 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
3118 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003119
Igor Murashkincba2c162013-03-20 15:56:31 -07003120 // client shouldn't be able to call into us anymore
3121 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003122
3123 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08003124}
3125
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08003126status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
3127 // No dumping of clients directly over Binder,
3128 // must go through CameraService::dump
3129 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07003130 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08003131 return OK;
3132}
3133
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07003134status_t CameraService::BasicClient::startWatchingTags(const String8&, int) {
3135 // Can't watch tags directly, must go through CameraService::startWatchingTags
3136 return OK;
3137}
3138
3139status_t CameraService::BasicClient::stopWatchingTags(int) {
3140 // Can't watch tags directly, must go through CameraService::stopWatchingTags
3141 return OK;
3142}
3143
3144status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
3145 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
3146 return OK;
3147}
3148
Ruben Brunkcc776712015-02-17 20:18:47 -08003149String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003150 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08003151}
3152
Emilian Peev8b64f282021-03-25 16:49:57 -07003153int CameraService::BasicClient::getCameraFacing() const {
3154 return mCameraFacing;
3155}
3156
3157int CameraService::BasicClient::getCameraOrientation() const {
3158 return mOrientation;
3159}
Ruben Brunkcc776712015-02-17 20:18:47 -08003160
3161int CameraService::BasicClient::getClientPid() const {
3162 return mClientPid;
3163}
3164
Ruben Brunk6267b532015-04-30 17:44:07 -07003165uid_t CameraService::BasicClient::getClientUid() const {
3166 return mClientUid;
3167}
3168
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003169bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
3170 // Defaults to API2.
3171 return level == API_2;
3172}
3173
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07003174status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003175 {
3176 Mutex::Autolock l(mAudioRestrictionLock);
3177 mAudioRestriction = mode;
3178 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07003179 sCameraService->updateAudioRestriction();
3180 return OK;
3181}
3182
3183int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003184 return sCameraService->updateAudioRestriction();
3185}
3186
3187int32_t CameraService::BasicClient::getAudioRestriction() const {
3188 Mutex::Autolock l(mAudioRestrictionLock);
3189 return mAudioRestriction;
3190}
3191
3192bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
3193 switch (mode) {
3194 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
3195 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
3196 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
3197 return true;
3198 default:
3199 return false;
3200 }
3201}
3202
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003203status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
3204 if (mode == AppOpsManager::MODE_ERRORED) {
3205 ALOGI("Camera %s: Access for \"%s\" has been revoked",
3206 mCameraIdStr.string(), String8(mClientPackageName).string());
3207 return PERMISSION_DENIED;
3208 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
3209 // If the calling Uid is trusted (a native service), the AppOpsManager could
3210 // return MODE_IGNORED. Do not treat such case as error.
3211 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
3212 mClientPackageName);
3213 bool isCameraPrivacyEnabled =
3214 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled(
3215 multiuser_get_user_id(mClientUid));
3216 if (!isUidActive || !isCameraPrivacyEnabled) {
3217 ALOGI("Camera %s: Access for \"%s\" has been restricted",
3218 mCameraIdStr.string(), String8(mClientPackageName).string());
3219 // Return the same error as for device policy manager rejection
3220 return -EACCES;
3221 }
3222 }
3223 return OK;
3224}
3225
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003226status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003227 ATRACE_CALL();
3228
Igor Murashkine6800ce2013-03-04 17:25:57 -08003229 {
3230 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003231 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08003232 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003233 if (mAppOpsManager != nullptr) {
3234 // Notify app ops that the camera is not available
3235 mOpsCallback = new OpsCallback(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003236 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
3237 mClientPackageName, mOpsCallback);
Igor Murashkine6800ce2013-03-04 17:25:57 -08003238
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003239 // Just check for camera acccess here on open - delay startOp until
3240 // camera frames start streaming in startCameraStreamingOps
3241 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
3242 mClientPackageName);
3243 status_t res = handleAppOpMode(mode);
3244 if (res != OK) {
3245 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003246 }
Svetoslav28e8ef72015-05-11 19:21:31 -07003247 }
3248
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003249 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003250
3251 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003252 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003253
Emilian Peev53722fa2019-02-22 17:47:20 -08003254 sCameraService->mUidPolicy->registerMonitorUid(mClientUid);
3255
Shuzhen Wang695044d2020-03-06 09:02:23 -08003256 // Notify listeners of camera open/close status
3257 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
3258
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003259 return OK;
3260}
3261
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003262status_t CameraService::BasicClient::startCameraStreamingOps() {
3263 ATRACE_CALL();
3264
3265 if (!mOpsActive) {
3266 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
3267 return INVALID_OPERATION;
3268 }
3269 if (mOpsStreaming) {
3270 ALOGV("%s: Streaming already active!", __FUNCTION__);
3271 return OK;
3272 }
3273
3274 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
3275 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
3276
3277 if (mAppOpsManager != nullptr) {
3278 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
3279 mClientPackageName, /*startIfModeDefault*/ false, mClientFeatureId,
3280 String16("start camera ") + String16(mCameraIdStr));
3281 status_t res = handleAppOpMode(mode);
3282 if (res != OK) {
3283 return res;
3284 }
3285 }
3286
3287 mOpsStreaming = true;
3288
3289 return OK;
3290}
3291
Valentin Iftimec0b8d472021-07-23 20:21:06 +02003292status_t CameraService::BasicClient::noteAppOp() {
3293 ATRACE_CALL();
3294
3295 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d",
3296 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
3297
3298 // noteAppOp is only used for when camera mute is not supported, in order
3299 // to trigger the sensor privacy "Unblock" dialog
3300 if (mAppOpsManager != nullptr) {
3301 int32_t mode = mAppOpsManager->noteOp(AppOpsManager::OP_CAMERA, mClientUid,
3302 mClientPackageName, mClientFeatureId,
3303 String16("start camera ") + String16(mCameraIdStr));
3304 status_t res = handleAppOpMode(mode);
3305 if (res != OK) {
3306 return res;
3307 }
3308 }
3309
3310 return OK;
3311}
3312
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003313status_t CameraService::BasicClient::finishCameraStreamingOps() {
3314 ATRACE_CALL();
3315
3316 if (!mOpsActive) {
3317 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
3318 return INVALID_OPERATION;
3319 }
3320 if (!mOpsStreaming) {
3321 ALOGV("%s: Streaming not active!", __FUNCTION__);
3322 return OK;
3323 }
3324
3325 if (mAppOpsManager != nullptr) {
3326 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
3327 mClientPackageName, mClientFeatureId);
3328 mOpsStreaming = false;
3329 }
3330
3331 return OK;
3332}
3333
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003334status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003335 ATRACE_CALL();
3336
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003337 if (mOpsStreaming) {
3338 // Make sure we've notified everyone about camera stopping
3339 finishCameraStreamingOps();
3340 }
3341
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003342 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003343 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003344 mOpsActive = false;
3345
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01003346 // This function is called when a client disconnects. This should
3347 // release the camera, but actually only if it was in a proper
3348 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003349 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01003350 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003351
Ruben Brunkcc776712015-02-17 20:18:47 -08003352 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003353 sCameraService->updateStatus(StatusInternal::PRESENT,
3354 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003355 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003356 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003357 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
3358 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08003359 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003360 mOpsCallback.clear();
3361
Emilian Peev53722fa2019-02-22 17:47:20 -08003362 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid);
3363
Shuzhen Wang695044d2020-03-06 09:02:23 -08003364 // Notify listeners of camera open/close status
3365 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
3366
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003367 return OK;
3368}
3369
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003370void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003371 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003372 if (mAppOpsManager == nullptr) {
3373 return;
3374 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003375 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003376 if (op != AppOpsManager::OP_CAMERA) {
3377 ALOGW("Unexpected app ops notification received: %d", op);
3378 return;
3379 }
3380
3381 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003382 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003383 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003384 ALOGV("checkOp returns: %d, %s ", res,
3385 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
3386 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
3387 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
3388 "UNKNOWN");
3389
Shuzhen Wang64900852021-02-05 09:03:29 -08003390 if (res == AppOpsManager::MODE_ERRORED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003391 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003392 String8(mClientPackageName).string());
Svet Ganova453d0d2018-01-11 15:37:58 -08003393 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08003394 } else if (res == AppOpsManager::MODE_IGNORED) {
3395 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Evan Severson09ab4002021-02-10 14:15:19 -08003396 bool isCameraPrivacyEnabled =
3397 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled(
3398 multiuser_get_user_id(mClientUid));
Shuzhen Wang64900852021-02-05 09:03:29 -08003399 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d",
3400 mCameraIdStr.string(), String8(mClientPackageName).string(),
3401 mUidIsTrusted, isUidActive);
3402 // If the calling Uid is trusted (a native service), or the client Uid is active (WAR for
3403 // b/175320666), the AppOpsManager could return MODE_IGNORED. Do not treat such cases as
3404 // error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02003405 if (!mUidIsTrusted) {
3406 if (isUidActive && isCameraPrivacyEnabled && supportsCameraMute()) {
3407 setCameraMute(true);
3408 } else if (!isUidActive
3409 || (isCameraPrivacyEnabled && !supportsCameraMute())) {
3410 block();
3411 }
Shuzhen Wang64900852021-02-05 09:03:29 -08003412 }
Evan Severson09ab4002021-02-10 14:15:19 -08003413 } else if (res == AppOpsManager::MODE_ALLOWED) {
3414 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003415 }
3416}
3417
Svet Ganova453d0d2018-01-11 15:37:58 -08003418void CameraService::BasicClient::block() {
3419 ATRACE_CALL();
3420
3421 // Reset the client PID to allow server-initiated disconnect,
3422 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003423 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08003424 CaptureResultExtras resultExtras; // a dummy result (invalid)
3425 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
3426 disconnect();
3427}
3428
Mathias Agopian65ab4712010-07-14 17:59:35 -07003429// ----------------------------------------------------------------------------
3430
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003431void CameraService::Client::notifyError(int32_t errorCode,
Jianing Weicb0652e2014-03-12 18:29:36 -07003432 const CaptureResultExtras& resultExtras) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08003433 (void) resultExtras;
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003434 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07003435 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
3436 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
3437 api1ErrorCode = CAMERA_ERROR_DISABLED;
3438 }
3439 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003440 } else {
3441 ALOGE("mRemoteCallback is NULL!!");
3442 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003443}
3444
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003445// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003446binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003447 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003448 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08003449}
3450
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003451bool CameraService::Client::canCastToApiClient(apiLevel level) const {
3452 return level == API_1;
3453}
3454
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003455CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
3456 mClient(client) {
3457}
3458
3459void CameraService::Client::OpsCallback::opChanged(int32_t op,
3460 const String16& packageName) {
3461 sp<BasicClient> client = mClient.promote();
3462 if (client != NULL) {
3463 client->opChanged(op, packageName);
3464 }
3465}
3466
Mathias Agopian65ab4712010-07-14 17:59:35 -07003467// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08003468// UidPolicy
3469// ----------------------------------------------------------------------------
3470
3471void CameraService::UidPolicy::registerSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003472 Mutex::Autolock _l(mUidLock);
3473
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003474 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07003475 status_t res = mAm.linkToDeath(this);
3476 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08003477 | ActivityManager::UID_OBSERVER_IDLE
Emilian Peev53722fa2019-02-22 17:47:20 -08003478 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganova453d0d2018-01-11 15:37:58 -08003479 ActivityManager::PROCESS_STATE_UNKNOWN,
3480 String16("cameraserver"));
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003481 if (res == OK) {
3482 mRegistered = true;
3483 ALOGV("UidPolicy: Registered with ActivityManager");
3484 }
Svet Ganova453d0d2018-01-11 15:37:58 -08003485}
3486
3487void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003488 Mutex::Autolock _l(mUidLock);
3489
Steven Moreland2f348142019-07-02 15:59:07 -07003490 mAm.unregisterUidObserver(this);
3491 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003492 mRegistered = false;
3493 mActiveUids.clear();
3494 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08003495}
3496
3497void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
3498 onUidIdle(uid, disabled);
3499}
3500
3501void CameraService::UidPolicy::onUidActive(uid_t uid) {
3502 Mutex::Autolock _l(mUidLock);
3503 mActiveUids.insert(uid);
3504}
3505
3506void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
3507 bool deleted = false;
3508 {
3509 Mutex::Autolock _l(mUidLock);
3510 if (mActiveUids.erase(uid) > 0) {
3511 deleted = true;
3512 }
3513 }
3514 if (deleted) {
3515 sp<CameraService> service = mService.promote();
3516 if (service != nullptr) {
3517 service->blockClientsForUid(uid);
3518 }
3519 }
3520}
3521
Emilian Peev53722fa2019-02-22 17:47:20 -08003522void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07003523 int64_t procStateSeq __unused, int32_t capability __unused) {
Emilian Peev53722fa2019-02-22 17:47:20 -08003524 bool procStateChange = false;
3525 {
3526 Mutex::Autolock _l(mUidLock);
3527 if ((mMonitoredUids.find(uid) != mMonitoredUids.end()) &&
3528 (mMonitoredUids[uid].first != procState)) {
3529 mMonitoredUids[uid].first = procState;
3530 procStateChange = true;
3531 }
3532 }
3533
3534 if (procStateChange) {
3535 sp<CameraService> service = mService.promote();
3536 if (service != nullptr) {
3537 service->notifyMonitoredUids();
3538 }
3539 }
3540}
3541
3542void CameraService::UidPolicy::registerMonitorUid(uid_t uid) {
3543 Mutex::Autolock _l(mUidLock);
3544 auto it = mMonitoredUids.find(uid);
3545 if (it != mMonitoredUids.end()) {
3546 it->second.second++;
3547 } else {
3548 mMonitoredUids.emplace(
3549 std::pair<uid_t, std::pair<int32_t, size_t>> (uid,
3550 std::pair<int32_t, size_t> (ActivityManager::PROCESS_STATE_NONEXISTENT, 1)));
3551 }
3552}
3553
3554void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid) {
3555 Mutex::Autolock _l(mUidLock);
3556 auto it = mMonitoredUids.find(uid);
3557 if (it != mMonitoredUids.end()) {
3558 it->second.second--;
3559 if (it->second.second == 0) {
3560 mMonitoredUids.erase(it);
3561 }
3562 } else {
3563 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
3564 }
3565}
3566
Svet Ganov7b4ab782018-03-25 12:48:10 -07003567bool CameraService::UidPolicy::isUidActive(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003568 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003569 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003570}
3571
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003572static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
3573static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003574
Svet Ganov7b4ab782018-03-25 12:48:10 -07003575bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003576 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003577 // If activity manager is unreachable, assume everything is active
3578 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003579 return true;
3580 }
3581 auto it = mOverrideUids.find(uid);
3582 if (it != mOverrideUids.end()) {
3583 return it->second;
3584 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003585 bool active = mActiveUids.find(uid) != mActiveUids.end();
3586 if (!active) {
3587 // We want active UIDs to always access camera with their first attempt since
3588 // there is no guarantee the app is robustly written and would retry getting
3589 // the camera on failure. The inverse case is not a problem as we would take
3590 // camera away soon once we get the callback that the uid is no longer active.
3591 ActivityManager am;
3592 // Okay to access with a lock held as UID changes are dispatched without
3593 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07003594 int64_t startTimeMillis = 0;
3595 do {
3596 // TODO: Fix this b/109950150!
3597 // Okay this is a hack. There is a race between the UID turning active and
3598 // activity being resumed. The proper fix is very risky, so we temporary add
3599 // some polling which should happen pretty rarely anyway as the race is hard
3600 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003601 active = mActiveUids.find(uid) != mActiveUids.end();
Hui Yu12c7ec72020-05-04 17:40:52 +00003602 if (!active) active = am.isUidActive(uid, callingPackage);
Svet Ganov94ec46f2018-06-08 15:03:46 -07003603 if (active) {
3604 break;
3605 }
3606 if (startTimeMillis <= 0) {
3607 startTimeMillis = uptimeMillis();
3608 }
3609 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003610 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003611 if (remainingTimeMillis <= 0) {
3612 break;
3613 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003614 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
3615
3616 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003617 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003618 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003619 } while (true);
3620
Svet Ganov7b4ab782018-03-25 12:48:10 -07003621 if (active) {
3622 // Now that we found out the UID is actually active, cache that
3623 mActiveUids.insert(uid);
3624 }
3625 }
3626 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08003627}
3628
Varun Shahb42f1eb2019-04-16 14:45:13 -07003629int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
3630 Mutex::Autolock _l(mUidLock);
3631 return getProcStateLocked(uid);
3632}
3633
3634int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
3635 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
3636 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
3637 procState = mMonitoredUids[uid].first;
3638 }
3639 return procState;
3640}
3641
Svet Ganov7b4ab782018-03-25 12:48:10 -07003642void CameraService::UidPolicy::UidPolicy::addOverrideUid(uid_t uid,
3643 String16 callingPackage, bool active) {
3644 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08003645}
3646
Svet Ganov7b4ab782018-03-25 12:48:10 -07003647void CameraService::UidPolicy::removeOverrideUid(uid_t uid, String16 callingPackage) {
3648 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08003649}
3650
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003651void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
3652 Mutex::Autolock _l(mUidLock);
3653 ALOGV("UidPolicy: ActivityManager has died");
3654 mRegistered = false;
3655 mActiveUids.clear();
3656}
3657
Svet Ganov7b4ab782018-03-25 12:48:10 -07003658void CameraService::UidPolicy::updateOverrideUid(uid_t uid, String16 callingPackage,
3659 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003660 bool wasActive = false;
3661 bool isActive = false;
3662 {
3663 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003664 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003665 mOverrideUids.erase(uid);
3666 if (insert) {
3667 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
3668 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003669 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003670 }
3671 if (wasActive != isActive && !isActive) {
3672 sp<CameraService> service = mService.promote();
3673 if (service != nullptr) {
3674 service->blockClientsForUid(uid);
3675 }
3676 }
3677}
3678
3679// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08003680// SensorPrivacyPolicy
3681// ----------------------------------------------------------------------------
3682void CameraService::SensorPrivacyPolicy::registerSelf() {
3683 Mutex::Autolock _l(mSensorPrivacyLock);
3684 if (mRegistered) {
3685 return;
3686 }
Evan Severson09ab4002021-02-10 14:15:19 -08003687 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08003688 mSpm.addSensorPrivacyListener(this);
3689 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
3690 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003691 if (res == OK) {
3692 mRegistered = true;
3693 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
3694 }
3695}
3696
3697void CameraService::SensorPrivacyPolicy::unregisterSelf() {
3698 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08003699 mSpm.removeSensorPrivacyListener(this);
3700 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003701 mRegistered = false;
3702 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
3703}
3704
3705bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
3706 Mutex::Autolock _l(mSensorPrivacyLock);
3707 return mSensorPrivacyEnabled;
3708}
3709
Evan Severson09ab4002021-02-10 14:15:19 -08003710bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled(userid_t userId) {
3711 if (!hasCameraPrivacyFeature()) {
3712 return false;
3713 }
3714 return mSpm.isIndividualSensorPrivacyEnabled(userId,
3715 SensorPrivacyManager::INDIVIDUAL_SENSOR_CAMERA);
3716}
3717
Michael Grooverd1d435a2018-12-18 17:39:42 -08003718binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
3719 {
3720 Mutex::Autolock _l(mSensorPrivacyLock);
3721 mSensorPrivacyEnabled = enabled;
3722 }
3723 // if sensor privacy is enabled then block all clients from accessing the camera
Evan Severson09ab4002021-02-10 14:15:19 -08003724 if (enabled) {
3725 sp<CameraService> service = mService.promote();
3726 if (service != nullptr) {
3727 service->blockAllClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08003728 }
3729 }
3730 return binder::Status::ok();
3731}
3732
3733void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
3734 Mutex::Autolock _l(mSensorPrivacyLock);
3735 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
3736 mRegistered = false;
3737}
3738
Evan Severson09ab4002021-02-10 14:15:19 -08003739bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Severson671806e2021-04-20 16:44:53 -07003740 return mSpm.supportsSensorToggle(SensorPrivacyManager::INDIVIDUAL_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08003741}
3742
Michael Grooverd1d435a2018-12-18 17:39:42 -08003743// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003744// CameraState
3745// ----------------------------------------------------------------------------
3746
3747CameraService::CameraState::CameraState(const String8& id, int cost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003748 const std::set<String8>& conflicting, SystemCameraKind systemCameraKind) : mId(id),
3749 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
3750 mSystemCameraKind(systemCameraKind) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08003751
3752CameraService::CameraState::~CameraState() {}
3753
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003754CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003755 Mutex::Autolock lock(mStatusLock);
3756 return mStatus;
3757}
3758
Shuzhen Wang43858162020-01-10 13:42:15 -08003759std::vector<String8> CameraService::CameraState::getUnavailablePhysicalIds() const {
3760 Mutex::Autolock lock(mStatusLock);
3761 std::vector<String8> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
3762 return res;
3763}
3764
Ruben Brunkcc776712015-02-17 20:18:47 -08003765CameraParameters CameraService::CameraState::getShimParams() const {
3766 return mShimParams;
3767}
3768
3769void CameraService::CameraState::setShimParams(const CameraParameters& params) {
3770 mShimParams = params;
3771}
3772
3773int CameraService::CameraState::getCost() const {
3774 return mCost;
3775}
3776
3777std::set<String8> CameraService::CameraState::getConflicting() const {
3778 return mConflicting;
3779}
3780
3781String8 CameraService::CameraState::getId() const {
3782 return mId;
3783}
3784
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003785SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
3786 return mSystemCameraKind;
3787}
3788
Shuzhen Wang43858162020-01-10 13:42:15 -08003789bool CameraService::CameraState::addUnavailablePhysicalId(const String8& physicalId) {
3790 Mutex::Autolock lock(mStatusLock);
3791 auto result = mUnavailablePhysicalIds.insert(physicalId);
3792 return result.second;
3793}
3794
3795bool CameraService::CameraState::removeUnavailablePhysicalId(const String8& physicalId) {
3796 Mutex::Autolock lock(mStatusLock);
3797 auto count = mUnavailablePhysicalIds.erase(physicalId);
3798 return count > 0;
3799}
3800
Shuzhen Wange7aa0342021-08-03 11:29:47 -07003801void CameraService::CameraState::setClientPackage(const String8& clientPackage) {
3802 Mutex::Autolock lock(mStatusLock);
3803 mClientPackage = clientPackage;
3804}
3805
3806String8 CameraService::CameraState::getClientPackage() const {
3807 Mutex::Autolock lock(mStatusLock);
3808 return mClientPackage;
3809}
3810
Ruben Brunkcc776712015-02-17 20:18:47 -08003811// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07003812// ClientEventListener
3813// ----------------------------------------------------------------------------
3814
3815void CameraService::ClientEventListener::onClientAdded(
3816 const resource_policy::ClientDescriptor<String8,
3817 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003818 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003819 if (basicClient.get() != nullptr) {
3820 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3821 notifier.noteStartCamera(descriptor.getKey(),
3822 static_cast<int>(basicClient->getClientUid()));
3823 }
3824}
3825
3826void CameraService::ClientEventListener::onClientRemoved(
3827 const resource_policy::ClientDescriptor<String8,
3828 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003829 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003830 if (basicClient.get() != nullptr) {
3831 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3832 notifier.noteStopCamera(descriptor.getKey(),
3833 static_cast<int>(basicClient->getClientUid()));
3834 }
3835}
3836
3837
3838// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003839// CameraClientManager
3840// ----------------------------------------------------------------------------
3841
Ruben Brunk99e69712015-05-26 17:25:07 -07003842CameraService::CameraClientManager::CameraClientManager() {
3843 setListener(std::make_shared<ClientEventListener>());
3844}
3845
Ruben Brunkcc776712015-02-17 20:18:47 -08003846CameraService::CameraClientManager::~CameraClientManager() {}
3847
3848sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
3849 const String8& id) const {
3850 auto descriptor = get(id);
3851 if (descriptor == nullptr) {
3852 return sp<BasicClient>{nullptr};
3853 }
3854 return descriptor->getValue();
3855}
3856
3857String8 CameraService::CameraClientManager::toString() const {
3858 auto all = getAll();
3859 String8 ret("[");
3860 bool hasAny = false;
3861 for (auto& i : all) {
3862 hasAny = true;
3863 String8 key = i->getKey();
3864 int32_t cost = i->getCost();
3865 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00003866 int32_t score = i->getPriority().getScore();
3867 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08003868 auto conflicting = i->getConflicting();
3869 auto clientSp = i->getValue();
3870 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07003871 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08003872 if (clientSp.get() != nullptr) {
3873 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07003874 uid_t clientUid = clientSp->getClientUid();
3875 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003876 }
Emilian Peev8131a262017-02-01 12:33:43 +00003877 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
3878 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08003879
Ruben Brunk6267b532015-04-30 17:44:07 -07003880 if (clientSp.get() != nullptr) {
3881 ret.appendFormat("User Id: %d, ", clientUserId);
3882 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003883 if (packageName.size() != 0) {
3884 ret.appendFormat("Client Package Name: %s", packageName.string());
3885 }
3886
3887 ret.append(", Conflicting Client Devices: {");
3888 for (auto& j : conflicting) {
3889 ret.appendFormat("%s, ", j.string());
3890 }
3891 ret.append("})");
3892 }
3893 if (hasAny) ret.append("\n");
3894 ret.append("]\n");
3895 return ret;
3896}
3897
3898CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3899 const String8& key, const sp<BasicClient>& value, int32_t cost,
Emilian Peev8131a262017-02-01 12:33:43 +00003900 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00003901 int32_t state, int32_t oomScoreOffset) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003902
Steven Moreland89a2c5c2020-01-31 15:02:25 -08003903 bool isVendorClient = getCurrentServingCall() == BinderCallType::HWBINDER;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003904 int32_t score_adj = isVendorClient ? kVendorClientScore : score;
3905 int32_t state_adj = isVendorClient ? kVendorClientState: state;
3906
Ruben Brunkcc776712015-02-17 20:18:47 -08003907 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00003908 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj, isVendorClient,
3909 oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08003910}
3911
3912CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00003913 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
3914 int32_t oomScoreOffset) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003915 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00003916 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00003917 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08003918}
3919
3920// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08003921// InjectionStatusListener
3922// ----------------------------------------------------------------------------
3923
3924void CameraService::InjectionStatusListener::addListener(
3925 const sp<ICameraInjectionCallback>& callback) {
3926 Mutex::Autolock lock(mListenerLock);
3927 if (mCameraInjectionCallback) return;
3928 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
3929 if (res == OK) {
3930 mCameraInjectionCallback = callback;
3931 }
3932}
3933
3934void CameraService::InjectionStatusListener::removeListener() {
3935 Mutex::Autolock lock(mListenerLock);
3936 if (mCameraInjectionCallback == nullptr) {
3937 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
3938 return;
3939 }
3940 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
3941 mCameraInjectionCallback = nullptr;
3942}
3943
3944void CameraService::InjectionStatusListener::notifyInjectionError(
Cliff Wud3a05312021-04-26 23:07:31 +08003945 String8 injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08003946 if (mCameraInjectionCallback == nullptr) {
3947 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
3948 return;
3949 }
Cliff Wud3a05312021-04-26 23:07:31 +08003950
3951 switch (err) {
3952 case -ENODEV:
3953 mCameraInjectionCallback->onInjectionError(
3954 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
3955 ALOGE("No camera device with ID \"%s\" currently available!",
3956 injectedCamId.string());
3957 break;
3958 case -EBUSY:
3959 mCameraInjectionCallback->onInjectionError(
3960 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
3961 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
3962 injectedCamId.string());
3963 break;
3964 case DEAD_OBJECT:
3965 mCameraInjectionCallback->onInjectionError(
3966 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
3967 ALOGE("Camera ID \"%s\" object is dead!",
3968 injectedCamId.string());
3969 break;
3970 case INVALID_OPERATION:
3971 mCameraInjectionCallback->onInjectionError(
3972 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
3973 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
3974 injectedCamId.string());
3975 break;
3976 case UNKNOWN_TRANSACTION:
3977 mCameraInjectionCallback->onInjectionError(
3978 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
3979 ALOGE("Camera ID \"%s\" method doesn't support!",
3980 injectedCamId.string());
3981 break;
3982 default:
3983 mCameraInjectionCallback->onInjectionError(
3984 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
3985 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
3986 strerror(-err), err, injectedCamId.string());
3987 }
Cliff Wud8cae102021-03-11 01:37:42 +08003988}
3989
3990void CameraService::InjectionStatusListener::binderDied(
3991 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08003992 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
3993 auto parent = mParent.promote();
3994 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08003995 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
3996 if (clientDescriptor != nullptr) {
3997 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
3998 baseClientPtr->stopInjection();
3999 }
Cliff Wu3b268182021-07-06 15:44:43 +08004000 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08004001 }
4002}
4003
4004// ----------------------------------------------------------------------------
4005// CameraInjectionSession
4006// ----------------------------------------------------------------------------
4007
4008binder::Status CameraService::CameraInjectionSession::stopInjection() {
4009 Mutex::Autolock lock(mInjectionSessionLock);
4010 auto parent = mParent.promote();
4011 if (parent == nullptr) {
4012 ALOGE("CameraInjectionSession: Parent is gone");
4013 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
4014 "Camera service encountered error");
4015 }
Cliff Wud3a05312021-04-26 23:07:31 +08004016
4017 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08004018 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
4019 if (clientDescriptor != nullptr) {
4020 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
4021 res = baseClientPtr->stopInjection();
4022 if (res != OK) {
4023 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
4024 " ret != NO_ERROR: %d", res);
4025 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
4026 "Camera session encountered error");
4027 }
4028 }
Cliff Wu3b268182021-07-06 15:44:43 +08004029 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08004030 return binder::Status::ok();
4031}
4032
4033// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07004034
4035static const int kDumpLockRetries = 50;
4036static const int kDumpLockSleep = 60000;
4037
4038static bool tryLock(Mutex& mutex)
4039{
4040 bool locked = false;
4041 for (int i = 0; i < kDumpLockRetries; ++i) {
4042 if (mutex.tryLock() == NO_ERROR) {
4043 locked = true;
4044 break;
4045 }
4046 usleep(kDumpLockSleep);
4047 }
4048 return locked;
4049}
4050
Rucha Katakwardf223072021-06-15 10:21:00 -07004051void CameraService::cacheDump() {
4052 if (mMemFd != -1) {
4053 const Vector<String16> args;
4054 ATRACE_CALL();
4055 // Acquiring service lock here will avoid the deadlock since
4056 // cacheDump will not be called during the second disconnect.
4057 Mutex::Autolock lock(mServiceLock);
4058
4059 Mutex::Autolock l(mCameraStatesLock);
4060 // Start collecting the info for open sessions and store it in temp file.
4061 for (const auto& state : mCameraStates) {
4062 String8 cameraId = state.first;
4063 auto clientDescriptor = mActiveClientManager.get(cameraId);
4064 if (clientDescriptor != nullptr) {
4065 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.string());
4066 // Log the current open session info before device is disconnected.
4067 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
4068 }
4069 }
4070 }
4071}
4072
Mathias Agopian65ab4712010-07-14 17:59:35 -07004073status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004074 ATRACE_CALL();
4075
Jayant Chowdhary5216b212019-07-17 09:26:23 -07004076 if (checkCallingPermission(sDumpPermission) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004077 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07004078 CameraThreadState::getCallingPid(),
4079 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004080 return NO_ERROR;
4081 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004082 bool locked = tryLock(mServiceLock);
4083 // failed to lock - CameraService is probably deadlocked
4084 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004085 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004086 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004087
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004088 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004089 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07004090
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004091 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004092 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08004093
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004094 if (locked) mServiceLock.unlock();
4095 return NO_ERROR;
4096 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004097 dprintf(fd, "\n== Service global info: ==\n\n");
4098 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004099 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07004100 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
4101 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004102 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
4103 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
4104 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004105 String8 activeClientString = mActiveClientManager.toString();
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004106 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
4107 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004108
4109 dumpEventLog(fd);
4110
4111 bool stateLocked = tryLock(mCameraStatesLock);
4112 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004113 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004114 }
4115
Emilian Peevbd8c5032018-02-14 23:05:40 +00004116 int argSize = args.size();
4117 for (int i = 0; i < argSize; i++) {
4118 if (args[i] == TagMonitor::kMonitorOption) {
4119 if (i + 1 < argSize) {
4120 mMonitorTags = String8(args[i + 1]);
4121 }
4122 break;
4123 }
4124 }
4125
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004126 for (auto& state : mCameraStates) {
4127 String8 cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004128
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004129 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004130
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004131 CameraParameters p = state.second->getShimParams();
4132 if (!p.isEmpty()) {
4133 dprintf(fd, " Camera1 API shim is using parameters:\n ");
4134 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004135 }
4136
4137 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08004138 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07004139 // log the current open session info
4140 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08004141 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07004142 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004143 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004144
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004145 }
4146
4147 if (stateLocked) mCameraStatesLock.unlock();
4148
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004149 if (locked) mServiceLock.unlock();
4150
Emilian Peevf53f66e2017-04-11 14:29:43 +01004151 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004152
4153 dprintf(fd, "\n== Vendor tags: ==\n\n");
4154
4155 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
4156 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00004157 sp<VendorTagDescriptorCache> cache =
4158 VendorTagDescriptorCache::getGlobalVendorTagCache();
4159 if (cache == NULL) {
4160 dprintf(fd, "No vendor tags.\n");
4161 } else {
4162 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
4163 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004164 } else {
4165 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
4166 }
4167
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004168 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004169 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004170 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004171
4172 // Process dump arguments, if any
4173 int n = args.size();
4174 String16 verboseOption("-v");
4175 String16 unreachableOption("--unreachable");
4176 for (int i = 0; i < n; i++) {
4177 if (args[i] == verboseOption) {
4178 // change logging level
4179 if (i + 1 >= n) continue;
4180 String8 levelStr(args[i+1]);
4181 int level = atoi(levelStr.string());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004182 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004183 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004184 } else if (args[i] == unreachableOption) {
4185 // Dump memory analysis
4186 // TODO - should limit be an argument parameter?
4187 UnreachableMemoryInfo info;
4188 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
4189 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004190 dprintf(fd, "\n== Unable to dump unreachable memory. "
4191 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004192 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004193 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004194 std::string s = info.ToString(/*log_contents*/ true);
4195 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004196 }
4197 }
4198 }
Rucha Katakwardf223072021-06-15 10:21:00 -07004199
4200 bool serviceLocked = tryLock(mServiceLock);
4201
4202 // Dump info from previous open sessions.
4203 // Reposition the offset to beginning of the file before reading
4204
4205 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
4206 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
4207 ssize_t size_read;
4208 char buf[4096];
4209 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
4210 // Read data from file to a small buffer and write it to fd.
4211 write(fd, buf, size_read);
4212 if (size_read == -1) {
4213 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
4214 break;
4215 }
4216 }
4217 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
4218 } else {
4219 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
4220 }
4221
4222 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004223 return NO_ERROR;
4224}
4225
Rucha Katakwardf223072021-06-15 10:21:00 -07004226void CameraService::dumpOpenSessionClientLogs(int fd,
4227 const Vector<String16>& args, const String8& cameraId) {
4228 auto clientDescriptor = mActiveClientManager.get(cameraId);
4229 dprintf(fd, " Device %s is open. Client instance dump:\n",
4230 cameraId.string());
4231 dprintf(fd, " Client priority score: %d state: %d\n",
4232 clientDescriptor->getPriority().getScore(),
4233 clientDescriptor->getPriority().getState());
4234 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
4235
4236 auto client = clientDescriptor->getValue();
4237 dprintf(fd, " Client package: %s\n",
4238 String8(client->getPackageName()).string());
4239
4240 client->dumpClient(fd, args);
4241}
4242
4243void CameraService::dumpClosedSessionClientLogs(int fd, const String8& cameraId) {
4244 dprintf(fd, " Device %s is closed, no client instance\n",
4245 cameraId.string());
4246}
4247
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004248void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004249 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004250
4251 Mutex::Autolock l(mLogLock);
4252 for (const auto& msg : mEventLog) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004253 dprintf(fd, " %s\n", msg.string());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004254 }
4255
4256 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004257 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004258 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004259 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004260 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004261 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004262}
4263
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004264void CameraService::cacheClientTagDumpIfNeeded(const char *cameraId, BasicClient* client) {
4265 Mutex::Autolock lock(mLogLock);
4266 if (!isClientWatchedLocked(client)) { return; }
4267
4268 std::vector<std::string> dumpVector;
4269 client->dumpWatchedEventsToVector(dumpVector);
4270
4271 if (dumpVector.empty()) { return; }
4272
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08004273 const String16 &packageName = client->getPackageName();
4274
4275 String8 packageName8 = String8(packageName);
4276 const char *printablePackageName = packageName8.lockBuffer(packageName.size());
4277
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004278 std::string dumpString;
4279 size_t i = dumpVector.size();
4280
4281 // Store the string in reverse order (latest last)
4282 while (i > 0) {
4283 i--;
4284 dumpString += cameraId;
4285 dumpString += ":";
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08004286 dumpString += printablePackageName;
4287 dumpString += " ";
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004288 dumpString += dumpVector[i]; // implicitly ends with '\n'
4289 }
4290
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08004291 packageName8.unlockBuffer();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004292 mWatchedClientsDumpCache[packageName] = dumpString;
4293}
4294
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004295void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004296 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004297 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
4298 if (mTorchClientMap[i] == who) {
4299 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004300 String8 cameraId = mTorchClientMap.keyAt(i);
4301 status_t res = mFlashlight->setTorchMode(cameraId, false);
4302 if (res) {
4303 ALOGE("%s: torch client died but couldn't turn off torch: "
4304 "%s (%d)", __FUNCTION__, strerror(-res), res);
4305 return;
4306 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004307 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004308 break;
4309 }
4310 }
4311}
4312
Ruben Brunkcc776712015-02-17 20:18:47 -08004313/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07004314
Igor Murashkin294d0ec2012-10-05 10:44:57 -07004315 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07004316 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
4317 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07004318 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08004319 // PID here is approximate and can be wrong.
Jayant Chowdhary12361932018-08-27 14:46:13 -07004320 logClientDied(CameraThreadState::getCallingPid(), String8("Binder died unexpectedly"));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004321
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004322 // check torch client
4323 handleTorchClientBinderDied(who);
4324
4325 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08004326 if(!evictClientIdByRemote(who)) {
4327 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07004328 return;
4329 }
4330
Ruben Brunkcc776712015-02-17 20:18:47 -08004331 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
4332 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07004333}
4334
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004335void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004336 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08004337}
4338
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004339void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
4340 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004341 // Do not lock mServiceLock here or can get into a deadlock from
4342 // connect() -> disconnect -> updateStatus
4343
4344 auto state = getCameraState(cameraId);
4345
4346 if (state == nullptr) {
4347 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
4348 cameraId.string());
4349 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07004350 }
4351
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004352 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
4353 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
4354 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
4355 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
4356 return;
4357 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004358
4359 // Collect the logical cameras without holding mStatusLock in updateStatus
4360 // as that can lead to a deadlock(b/162192331).
4361 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08004362 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08004363 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07004364 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004365 &logicalCameraIds]
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004366 (const String8& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004367
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004368 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004369 // Update torch status if it has a flash unit.
4370 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004371 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004372 if (getTorchStatusLocked(cameraId, &torchStatus) !=
4373 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004374 TorchModeStatus newTorchStatus =
4375 status == StatusInternal::PRESENT ?
4376 TorchModeStatus::AVAILABLE_OFF :
4377 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004378 if (torchStatus != newTorchStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07004379 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004380 }
4381 }
Ruben Brunkcc776712015-02-17 20:18:47 -08004382 }
4383
4384 Mutex::Autolock lock(mStatusListenerLock);
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004385 notifyPhysicalCameraStatusLocked(mapToInterface(status), String16(cameraId),
4386 logicalCameraIds, deviceKind);
Shuzhen Wang43858162020-01-10 13:42:15 -08004387
Ruben Brunkcc776712015-02-17 20:18:47 -08004388 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07004389 bool isVendorListener = listener->isVendorListener();
4390 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
4391 listener->getListenerPid(), listener->getListenerUid()) ||
Shuzhen Wangb8259792021-05-27 09:27:06 -07004392 isVendorListener) {
4393 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07004394 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08004395 continue;
4396 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07004397 listener->getListener()->onStatusChanged(mapToInterface(status),
Emilian Peev53722fa2019-02-22 17:47:20 -08004398 String16(cameraId));
Ruben Brunkcc776712015-02-17 20:18:47 -08004399 }
4400 });
Igor Murashkincba2c162013-03-20 15:56:31 -07004401}
4402
Shuzhen Wang695044d2020-03-06 09:02:23 -08004403void CameraService::updateOpenCloseStatus(const String8& cameraId, bool open,
4404 const String16& clientPackageName) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07004405 auto state = getCameraState(cameraId);
4406 if (state == nullptr) {
4407 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
4408 cameraId.string());
4409 return;
4410 }
4411 if (open) {
4412 state->setClientPackage(String8(clientPackageName));
4413 } else {
4414 state->setClientPackage(String8::empty());
4415 }
4416
Shuzhen Wang695044d2020-03-06 09:02:23 -08004417 Mutex::Autolock lock(mStatusListenerLock);
4418
4419 for (const auto& it : mListenerList) {
4420 if (!it->isOpenCloseCallbackAllowed()) {
4421 continue;
4422 }
4423
4424 binder::Status ret;
4425 String16 cameraId64(cameraId);
4426 if (open) {
4427 ret = it->getListener()->onCameraOpened(cameraId64, clientPackageName);
4428 } else {
4429 ret = it->getListener()->onCameraClosed(cameraId64);
4430 }
4431 if (!ret.isOk()) {
4432 ALOGE("%s: Failed to trigger onCameraOpened/onCameraClosed callback: %d", __FUNCTION__,
4433 ret.exceptionCode());
4434 }
4435 }
4436}
4437
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004438template<class Func>
4439void CameraService::CameraState::updateStatus(StatusInternal status,
4440 const String8& cameraId,
4441 std::initializer_list<StatusInternal> rejectSourceStates,
4442 Func onStatusUpdatedLocked) {
4443 Mutex::Autolock lock(mStatusLock);
4444 StatusInternal oldStatus = mStatus;
4445 mStatus = status;
4446
4447 if (oldStatus == status) {
4448 return;
4449 }
4450
4451 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
4452 cameraId.string(), oldStatus, status);
4453
4454 if (oldStatus == StatusInternal::NOT_PRESENT &&
4455 (status != StatusInternal::PRESENT &&
4456 status != StatusInternal::ENUMERATING)) {
4457
4458 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
4459 __FUNCTION__);
4460 mStatus = oldStatus;
4461 return;
4462 }
4463
4464 /**
4465 * Sometimes we want to conditionally do a transition.
4466 * For example if a client disconnects, we want to go to PRESENT
4467 * only if we weren't already in NOT_PRESENT or ENUMERATING.
4468 */
4469 for (auto& rejectStatus : rejectSourceStates) {
4470 if (oldStatus == rejectStatus) {
4471 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
4472 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
4473 mStatus = oldStatus;
4474 return;
4475 }
4476 }
4477
4478 onStatusUpdatedLocked(cameraId, status);
4479}
4480
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004481status_t CameraService::getTorchStatusLocked(
4482 const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004483 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004484 if (!status) {
4485 return BAD_VALUE;
4486 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004487 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
4488 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004489 // invalid camera ID or the camera doesn't have a flash unit
4490 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004491 }
4492
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004493 *status = mTorchStatusMap.valueAt(index);
4494 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004495}
4496
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004497status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004498 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004499 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
4500 if (index == NAME_NOT_FOUND) {
4501 return BAD_VALUE;
4502 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004503 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004504
4505 return OK;
4506}
4507
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004508std::list<String16> CameraService::getLogicalCameras(
4509 const String8& physicalCameraId) {
4510 std::list<String16> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08004511 Mutex::Autolock lock(mCameraStatesLock);
4512 for (const auto& state : mCameraStates) {
4513 std::vector<std::string> physicalCameraIds;
4514 if (!mCameraProviderManager->isLogicalCamera(state.first.c_str(), &physicalCameraIds)) {
4515 // This is not a logical multi-camera.
4516 continue;
4517 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004518 if (std::find(physicalCameraIds.begin(), physicalCameraIds.end(), physicalCameraId.c_str())
Shuzhen Wang43858162020-01-10 13:42:15 -08004519 == physicalCameraIds.end()) {
4520 // cameraId is not a physical camera of this logical multi-camera.
4521 continue;
4522 }
4523
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004524 retList.emplace_back(String16(state.first));
4525 }
4526 return retList;
4527}
4528
4529void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
4530 const String16& physicalCameraId, const std::list<String16>& logicalCameraIds,
4531 SystemCameraKind deviceKind) {
4532 // mStatusListenerLock is expected to be locked
4533 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08004534 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004535 // Note: we check only the deviceKind of the physical camera id
4536 // since, logical camera ids and their physical camera ids are
4537 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07004538 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
4539 listener->getListenerPid(), listener->getListenerUid())) {
4540 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004541 String8(physicalCameraId).c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07004542 continue;
4543 }
Shuzhen Wang43858162020-01-10 13:42:15 -08004544 listener->getListener()->onPhysicalCameraStatusChanged(status,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004545 logicalCameraId, physicalCameraId);
Shuzhen Wang43858162020-01-10 13:42:15 -08004546 }
4547 }
4548}
4549
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004550
Svet Ganova453d0d2018-01-11 15:37:58 -08004551void CameraService::blockClientsForUid(uid_t uid) {
4552 const auto clients = mActiveClientManager.getAll();
4553 for (auto& current : clients) {
4554 if (current != nullptr) {
4555 const auto basicClient = current->getValue();
4556 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
4557 basicClient->block();
4558 }
4559 }
4560 }
4561}
4562
Michael Grooverd1d435a2018-12-18 17:39:42 -08004563void CameraService::blockAllClients() {
4564 const auto clients = mActiveClientManager.getAll();
4565 for (auto& current : clients) {
4566 if (current != nullptr) {
4567 const auto basicClient = current->getValue();
4568 if (basicClient.get() != nullptr) {
4569 basicClient->block();
4570 }
4571 }
4572 }
4573}
4574
Svet Ganova453d0d2018-01-11 15:37:58 -08004575// NOTE: This is a remote API - make sure all args are validated
4576status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
4577 if (!checkCallingPermission(sManageCameraPermission, nullptr, nullptr)) {
4578 return PERMISSION_DENIED;
4579 }
4580 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
4581 return BAD_VALUE;
4582 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004583 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004584 return handleSetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07004585 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004586 return handleResetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07004587 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004588 return handleGetUidState(args, out, err);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004589 } else if (args.size() >= 2 && args[0] == String16("set-rotate-and-crop")) {
4590 return handleSetRotateAndCrop(args);
4591 } else if (args.size() >= 1 && args[0] == String16("get-rotate-and-crop")) {
4592 return handleGetRotateAndCrop(out);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004593 } else if (args.size() >= 2 && args[0] == String16("set-image-dump-mask")) {
4594 return handleSetImageDumpMask(args);
4595 } else if (args.size() >= 1 && args[0] == String16("get-image-dump-mask")) {
4596 return handleGetImageDumpMask(out);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004597 } else if (args.size() >= 2 && args[0] == String16("set-camera-mute")) {
4598 return handleSetCameraMute(args);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004599 } else if (args.size() >= 2 && args[0] == String16("watch")) {
Avichal Rakesh84147132021-11-11 17:47:11 -08004600 return handleWatchCommand(args, in, out);
Svet Ganova453d0d2018-01-11 15:37:58 -08004601 } else if (args.size() == 1 && args[0] == String16("help")) {
4602 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004603 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08004604 }
4605 printHelp(err);
4606 return BAD_VALUE;
4607}
4608
4609status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004610 String16 packageName = args[1];
4611
Svet Ganova453d0d2018-01-11 15:37:58 -08004612 bool active = false;
4613 if (args[2] == String16("active")) {
4614 active = true;
4615 } else if ((args[2] != String16("idle"))) {
4616 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
4617 return BAD_VALUE;
4618 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004619
4620 int userId = 0;
4621 if (args.size() >= 5 && args[3] == String16("--user")) {
4622 userId = atoi(String8(args[4]));
4623 }
4624
4625 uid_t uid;
4626 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
4627 return BAD_VALUE;
4628 }
4629
4630 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08004631 return NO_ERROR;
4632}
4633
4634status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004635 String16 packageName = args[1];
4636
4637 int userId = 0;
4638 if (args.size() >= 4 && args[2] == String16("--user")) {
4639 userId = atoi(String8(args[3]));
4640 }
4641
4642 uid_t uid;
4643 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004644 return BAD_VALUE;
4645 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004646
4647 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08004648 return NO_ERROR;
4649}
4650
4651status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004652 String16 packageName = args[1];
4653
4654 int userId = 0;
4655 if (args.size() >= 4 && args[2] == String16("--user")) {
4656 userId = atoi(String8(args[3]));
4657 }
4658
4659 uid_t uid;
4660 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004661 return BAD_VALUE;
4662 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004663
4664 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004665 return dprintf(out, "active\n");
4666 } else {
4667 return dprintf(out, "idle\n");
4668 }
4669}
4670
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004671status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
4672 int rotateValue = atoi(String8(args[1]));
4673 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
4674 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
4675 Mutex::Autolock lock(mServiceLock);
4676
4677 mOverrideRotateAndCropMode = rotateValue;
4678
4679 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
4680
4681 const auto clients = mActiveClientManager.getAll();
4682 for (auto& current : clients) {
4683 if (current != nullptr) {
4684 const auto basicClient = current->getValue();
4685 if (basicClient.get() != nullptr) {
4686 basicClient->setRotateAndCropOverride(rotateValue);
4687 }
4688 }
4689 }
4690
4691 return OK;
4692}
4693
4694status_t CameraService::handleGetRotateAndCrop(int out) {
4695 Mutex::Autolock lock(mServiceLock);
4696
4697 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
4698}
4699
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004700status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
4701 char *endPtr;
4702 errno = 0;
4703 String8 maskString8 = String8(args[1]);
4704 long maskValue = strtol(maskString8.c_str(), &endPtr, 10);
4705
4706 if (errno != 0) return BAD_VALUE;
4707 if (endPtr != maskString8.c_str() + maskString8.size()) return BAD_VALUE;
4708 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
4709
4710 Mutex::Autolock lock(mServiceLock);
4711
4712 mImageDumpMask = maskValue;
4713
4714 return OK;
4715}
4716
4717status_t CameraService::handleGetImageDumpMask(int out) {
4718 Mutex::Autolock lock(mServiceLock);
4719
4720 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
4721}
4722
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004723status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
4724 int muteValue = strtol(String8(args[1]), nullptr, 10);
4725 if (errno != 0) return BAD_VALUE;
4726
4727 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
4728 Mutex::Autolock lock(mServiceLock);
4729
4730 mOverrideCameraMuteMode = (muteValue == 1);
4731
4732 const auto clients = mActiveClientManager.getAll();
4733 for (auto& current : clients) {
4734 if (current != nullptr) {
4735 const auto basicClient = current->getValue();
4736 if (basicClient.get() != nullptr) {
4737 if (basicClient->supportsCameraMute()) {
4738 basicClient->setCameraMute(mOverrideCameraMuteMode);
4739 }
4740 }
4741 }
4742 }
4743
4744 return OK;
4745}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004746
Avichal Rakesh84147132021-11-11 17:47:11 -08004747status_t CameraService::handleWatchCommand(const Vector<String16>& args, int inFd, int outFd) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004748 if (args.size() >= 3 && args[1] == String16("start")) {
4749 return startWatchingTags(args, outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004750 } else if (args.size() == 2 && args[1] == String16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004751 return stopWatchingTags(outFd);
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08004752 } else if (args.size() == 2 && args[1] == String16("dump")) {
4753 return printWatchedTags(outFd);
4754 } else if (args.size() >= 2 && args[1] == String16("live")) {
4755 return printWatchedTagsUntilInterrupt(args, inFd, outFd);
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08004756 } else if (args.size() == 2 && args[1] == String16("clear")) {
4757 return clearCachedMonitoredTagDumps(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004758 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004759 dprintf(outFd, "Camera service watch commands:\n"
4760 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
4761 " starts watching the provided tags for clients with provided package\n"
4762 " recognizes tag shorthands like '3a'\n"
4763 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08004764 " dump dumps the monitoring information and exits\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004765 " stop stops watching all tags\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08004766 " live [-n <refresh_interval_ms>]\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004767 " prints the monitored information in real time\n"
Avichal Rakesh84147132021-11-11 17:47:11 -08004768 " Hit return to exit\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08004769 " clear clears all buffers storing information for watch command");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004770 return BAD_VALUE;
4771}
4772
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004773status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
4774 Mutex::Autolock lock(mLogLock);
4775 size_t tagsIdx; // index of '-m'
4776 String16 tags("");
4777 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != String16("-m"); tagsIdx++);
4778 if (tagsIdx < args.size() - 1) {
4779 tags = args[tagsIdx + 1];
4780 } else {
4781 dprintf(outFd, "No tags provided.\n");
4782 return BAD_VALUE;
4783 }
4784
4785 size_t clientsIdx; // index of '-c'
4786 String16 clients = kWatchAllClientsFlag; // watch all clients if no clients are provided
4787 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != String16("-c");
4788 clientsIdx++);
4789 if (clientsIdx < args.size() - 1) {
4790 clients = args[clientsIdx + 1];
4791 }
4792 parseClientsToWatchLocked(String8(clients));
4793
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004794 // track tags to initialize future clients with the monitoring information
4795 mMonitorTags = String8(tags);
4796
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004797 bool serviceLock = tryLock(mServiceLock);
4798 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004799 auto cameraClients = mActiveClientManager.getAll();
4800 for (const auto &clientDescriptor: cameraClients) {
4801 if (clientDescriptor == nullptr) { continue; }
4802 sp<BasicClient> client = clientDescriptor->getValue();
4803 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004804
4805 if (isClientWatchedLocked(client.get())) {
4806 client->startWatchingTags(mMonitorTags, outFd);
4807 numWatchedClients++;
4808 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004809 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004810 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
4811
4812 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004813 return OK;
4814}
4815
4816status_t CameraService::stopWatchingTags(int outFd) {
4817 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004818 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004819 mMonitorTags = String8::empty();
4820
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004821 mWatchedClientPackages.clear();
4822 mWatchedClientsDumpCache.clear();
4823
4824 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004825 auto cameraClients = mActiveClientManager.getAll();
4826 for (const auto &clientDescriptor : cameraClients) {
4827 if (clientDescriptor == nullptr) { continue; }
4828 sp<BasicClient> client = clientDescriptor->getValue();
4829 if (client.get() == nullptr) { continue; }
4830 client->stopWatchingTags(outFd);
4831 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004832 dprintf(outFd, "Stopped watching all clients.\n");
4833 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004834 return OK;
4835}
4836
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08004837status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
4838 Mutex::Autolock lock(mLogLock);
4839 size_t clearedSize = mWatchedClientsDumpCache.size();
4840 mWatchedClientsDumpCache.clear();
4841 dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
4842 return OK;
4843}
4844
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08004845status_t CameraService::printWatchedTags(int outFd) {
4846 Mutex::Autolock logLock(mLogLock);
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08004847 std::set<String16> connectedMonitoredClients;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004848
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08004849 bool printedSomething = false; // tracks if any monitoring information was printed
4850 // (from either cached or active clients)
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004851
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08004852 bool serviceLock = tryLock(mServiceLock);
4853 // get all watched clients that are currently connected
4854 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
4855 if (clientDescriptor == nullptr) { continue; }
4856
4857 sp<BasicClient> client = clientDescriptor->getValue();
4858 if (client.get() == nullptr) { continue; }
4859 if (!isClientWatchedLocked(client.get())) { continue; }
4860
4861 std::vector<std::string> dumpVector;
4862 client->dumpWatchedEventsToVector(dumpVector);
4863
4864 size_t printIdx = dumpVector.size();
4865 if (printIdx == 0) {
4866 continue;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004867 }
4868
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08004869 // Print tag dumps for active client
4870 const String8 &cameraId = clientDescriptor->getKey();
4871 String8 packageName8 = String8(client->getPackageName());
4872 const char *printablePackageName = packageName8.lockBuffer(packageName8.size());
4873 dprintf(outFd, "Client: %s (active)\n", printablePackageName);
4874 while(printIdx > 0) {
4875 printIdx--;
4876 dprintf(outFd, "%s:%s %s", cameraId.string(), printablePackageName,
4877 dumpVector[printIdx].c_str());
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08004878 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08004879 dprintf(outFd, "\n");
4880 packageName8.unlockBuffer();
4881 printedSomething = true;
4882
4883 connectedMonitoredClients.emplace(client->getPackageName());
4884 }
4885 if (serviceLock) { mServiceLock.unlock(); }
4886
4887 // Print entries in mWatchedClientsDumpCache for clients that are not connected
4888 for (const auto &kv: mWatchedClientsDumpCache) {
4889 const String16 &package = kv.first;
4890 if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
4891 continue;
4892 }
4893
4894 dprintf(outFd, "Client: %s (cached)\n", String8(package).string());
4895 dprintf(outFd, "%s\n", kv.second.c_str());
4896 printedSomething = true;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004897 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004898
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08004899 if (!printedSomething) {
4900 dprintf(outFd, "No monitoring information to print.\n");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004901 }
4902
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08004903 return OK;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004904}
4905
Avichal Rakesh84147132021-11-11 17:47:11 -08004906// Print all events in vector `events' that came after lastPrintedEvent
4907void printNewWatchedEvents(int outFd,
4908 const char *cameraId,
4909 const String16 &packageName,
4910 const std::vector<std::string> &events,
4911 const std::string &lastPrintedEvent) {
4912 if (events.empty()) { return; }
4913
4914 // index of lastPrintedEvent in events.
4915 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
4916 size_t lastPrintedIdx;
4917 for (lastPrintedIdx = 0;
4918 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
4919 lastPrintedIdx++);
4920
4921 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
4922
4923 String8 packageName8(packageName);
4924 const char *printablePackageName = packageName8.lockBuffer(packageName8.size());
4925
4926 // print events in chronological order (latest event last)
4927 size_t idxToPrint = lastPrintedIdx;
4928 do {
4929 idxToPrint--;
4930 dprintf(outFd, "%s:%s %s", cameraId, printablePackageName, events[idxToPrint].c_str());
4931 } while (idxToPrint != 0);
4932
4933 packageName8.unlockBuffer();
4934}
4935
4936// Returns true if adb shell cmd watch should be interrupted based on data in inFd. The watch
4937// command should be interrupted if the user presses the return key, or if user loses any way to
4938// signal interrupt.
4939// If timeoutMs == 0, this function will always return false
4940bool shouldInterruptWatchCommand(int inFd, int outFd, long timeoutMs) {
4941 struct timeval startTime;
4942 int startTimeError = gettimeofday(&startTime, nullptr);
4943 if (startTimeError) {
4944 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
4945 return true;
4946 }
4947
4948 const nfds_t numFds = 1;
4949 struct pollfd pollFd = { .fd = inFd, .events = POLLIN, .revents = 0 };
4950
4951 struct timeval currTime;
4952 char buffer[2];
4953 while(true) {
4954 int currTimeError = gettimeofday(&currTime, nullptr);
4955 if (currTimeError) {
4956 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
4957 return true;
4958 }
4959
4960 long elapsedTimeMs = ((currTime.tv_sec - startTime.tv_sec) * 1000L)
4961 + ((currTime.tv_usec - startTime.tv_usec) / 1000L);
4962 int remainingTimeMs = (int) (timeoutMs - elapsedTimeMs);
4963
4964 if (remainingTimeMs <= 0) {
4965 // No user interrupt within timeoutMs, don't interrupt watch command
4966 return false;
4967 }
4968
4969 int numFdsUpdated = poll(&pollFd, numFds, remainingTimeMs);
4970 if (numFdsUpdated < 0) {
4971 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
4972 return true;
4973 }
4974
4975 if (numFdsUpdated == 0) {
4976 // No user input within timeoutMs, don't interrupt watch command
4977 return false;
4978 }
4979
4980 if (!(pollFd.revents & POLLIN)) {
4981 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
4982 return true;
4983 }
4984
4985 ssize_t sizeRead = read(inFd, buffer, sizeof(buffer) - 1);
4986 if (sizeRead < 0) {
4987 dprintf(outFd, "Error reading user input. Exiting.\n");
4988 return true;
4989 }
4990
4991 if (sizeRead == 0) {
4992 // Reached end of input fd (can happen if input is piped)
4993 // User has no way to signal an interrupt, so interrupt here
4994 return true;
4995 }
4996
4997 if (buffer[0] == '\n') {
4998 // User pressed return, interrupt watch command.
4999 return true;
5000 }
5001 }
5002}
5003
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005004status_t CameraService::printWatchedTagsUntilInterrupt(const Vector<String16> &args,
5005 int inFd, int outFd) {
5006 // Figure out refresh interval, if present in args
5007 long refreshTimeoutMs = 1000L; // refresh every 1s by default
5008 if (args.size() > 2) {
5009 size_t intervalIdx; // index of '-n'
5010 for (intervalIdx = 2; intervalIdx < args.size() && String16("-n") != args[intervalIdx];
5011 intervalIdx++);
5012
5013 size_t intervalValIdx = intervalIdx + 1;
5014 if (intervalValIdx < args.size()) {
5015 refreshTimeoutMs = strtol(String8(args[intervalValIdx].string()), nullptr, 10);
5016 if (errno) { return BAD_VALUE; }
5017 }
5018 }
5019
5020 // Set min timeout of 10ms. This prevents edge cases in polling when timeout of 0 is passed.
5021 refreshTimeoutMs = refreshTimeoutMs < 10 ? 10 : refreshTimeoutMs;
5022
Avichal Rakesh84147132021-11-11 17:47:11 -08005023 dprintf(outFd, "Press return to exit...\n\n");
Avichal Rakesha14d9832021-11-11 01:41:55 -08005024 std::map<String16, std::string> packageNameToLastEvent;
5025
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005026 while (true) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08005027 bool serviceLock = tryLock(mServiceLock);
5028 auto cameraClients = mActiveClientManager.getAll();
5029 if (serviceLock) { mServiceLock.unlock(); }
5030
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005031 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005032 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005033 if (clientDescriptor == nullptr) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005034
5035 sp<BasicClient> client = clientDescriptor->getValue();
5036 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005037 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005038
Avichal Rakesha14d9832021-11-11 01:41:55 -08005039 const String16 &packageName = client->getPackageName();
5040 // This also initializes the map entries with an empty string
5041 const std::string& lastPrintedEvent = packageNameToLastEvent[packageName];
5042
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005043 std::vector<std::string> latestEvents;
5044 client->dumpWatchedEventsToVector(latestEvents);
5045
5046 if (!latestEvents.empty()) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08005047 String8 cameraId = clientDescriptor->getKey();
5048 const char *printableCameraId = cameraId.lockBuffer(cameraId.size());
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005049 printNewWatchedEvents(outFd,
Avichal Rakesha14d9832021-11-11 01:41:55 -08005050 printableCameraId,
5051 packageName,
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005052 latestEvents,
5053 lastPrintedEvent);
Avichal Rakesha14d9832021-11-11 01:41:55 -08005054 packageNameToLastEvent[packageName] = latestEvents[0];
5055 cameraId.unlockBuffer();
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005056 }
5057 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005058 if (shouldInterruptWatchCommand(inFd, outFd, refreshTimeoutMs)) {
Avichal Rakesh84147132021-11-11 17:47:11 -08005059 break;
5060 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005061 }
5062 return OK;
5063}
5064
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005065void CameraService::parseClientsToWatchLocked(String8 clients) {
5066 mWatchedClientPackages.clear();
5067
5068 const char *allSentinel = String8(kWatchAllClientsFlag).string();
5069
5070 char *tokenized = clients.lockBuffer(clients.size());
5071 char *savePtr;
5072 char *nextClient = strtok_r(tokenized, ",", &savePtr);
5073
5074 while (nextClient != nullptr) {
5075 if (strcmp(nextClient, allSentinel) == 0) {
5076 // Don't need to track any other package if 'all' is present
5077 mWatchedClientPackages.clear();
5078 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
5079 break;
5080 }
5081
5082 // track package names
5083 mWatchedClientPackages.emplace(nextClient);
5084 nextClient = strtok_r(nullptr, ",", &savePtr);
5085 }
5086 clients.unlockBuffer();
5087}
5088
Svet Ganova453d0d2018-01-11 15:37:58 -08005089status_t CameraService::printHelp(int out) {
5090 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07005091 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
5092 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
5093 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005094 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
5095 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
5096 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005097 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
5098 " Valid values 0=OFF, 1=ON for JPEG\n"
5099 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005100 " set-camera-mute <0/1> enable or disable camera muting\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005101 " watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08005102 " help print this message\n");
5103}
5104
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005105bool CameraService::isClientWatched(const BasicClient *client) {
5106 Mutex::Autolock lock(mLogLock);
5107 return isClientWatchedLocked(client);
5108}
5109
5110bool CameraService::isClientWatchedLocked(const BasicClient *client) {
5111 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
5112 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
5113}
5114
Yin-Chia Yehdba03232019-08-19 15:54:28 -07005115int32_t CameraService::updateAudioRestriction() {
5116 Mutex::Autolock lock(mServiceLock);
5117 return updateAudioRestrictionLocked();
5118}
5119
5120int32_t CameraService::updateAudioRestrictionLocked() {
5121 int32_t mode = 0;
5122 // iterate through all active client
5123 for (const auto& i : mActiveClientManager.getAll()) {
5124 const auto clientSp = i->getValue();
5125 mode |= clientSp->getAudioRestriction();
5126 }
5127
5128 bool modeChanged = (mAudioRestriction != mode);
5129 mAudioRestriction = mode;
5130 if (modeChanged) {
5131 mAppOps.setCameraAudioRestriction(mode);
5132 }
5133 return mode;
5134}
5135
Cliff Wud3a05312021-04-26 23:07:31 +08005136void CameraService::clearInjectionParameters() {
5137 {
5138 Mutex::Autolock lock(mInjectionParametersLock);
5139 mInjectionInitPending = true;
5140 mInjectionInternalCamId = "";
5141 }
5142 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08005143 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08005144}
5145
Mathias Agopian65ab4712010-07-14 17:59:35 -07005146}; // namespace android