blob: 024915325582818b942610e39a45d830780815b6 [file] [log] [blame]
Mathias Agopian65ab4712010-07-14 17:59:35 -07001/*
Ruben Brunkd1176ef2014-02-21 10:51:38 -08002 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Mathias Agopian65ab4712010-07-14 17:59:35 -070016
17#define LOG_TAG "CameraService"
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -070018#define ATRACE_TAG ATRACE_TAG_CAMERA
Iliyan Malchev8951a972011-04-14 16:55:59 -070019//#define LOG_NDEBUG 0
Mathias Agopian65ab4712010-07-14 17:59:35 -070020
Ruben Brunkcc776712015-02-17 20:18:47 -080021#include <algorithm>
22#include <climits>
Mathias Agopian65ab4712010-07-14 17:59:35 -070023#include <stdio.h>
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -080024#include <cstdlib>
Ruben Brunkcc776712015-02-17 20:18:47 -080025#include <cstring>
26#include <ctime>
27#include <string>
Mathias Agopian65ab4712010-07-14 17:59:35 -070028#include <sys/types.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080029#include <inttypes.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070030#include <pthread.h>
Avichal Rakesh84147132021-11-11 17:47:11 -080031#include <poll.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070032
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080033#include <android/hardware/ICamera.h>
34#include <android/hardware/ICameraClient.h>
35
Alex Deymo9c2a2c22016-08-25 11:59:14 -070036#include <android-base/macros.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080037#include <android-base/parseint.h>
Jayant Chowdharyb61526c2019-05-13 19:37:42 -070038#include <android-base/stringprintf.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080039#include <binder/ActivityManager.h>
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -080040#include <binder/AppOpsManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070041#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070042#include <binder/MemoryBase.h>
43#include <binder/MemoryHeapBase.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080044#include <binder/PermissionController.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080045#include <binder/IResultReceiver.h>
Steven Moreland89a2c5c2020-01-31 15:02:25 -080046#include <binderthreadstate/CallerUtils.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070047#include <cutils/atomic.h>
Nipun Kwatrab5ca4612010-09-11 19:31:10 -070048#include <cutils/properties.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080049#include <cutils/misc.h>
Mathias Agopiandf712ea2012-02-25 18:48:35 -080050#include <gui/Surface.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070051#include <hardware/hardware.h>
Jayant Chowdharybe543d42018-08-15 13:16:14 -070052#include "hidl/HidlCameraService.h"
53#include <hidl/HidlTransportSupport.h>
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -080054#include <hwbinder/IPCThreadState.h>
Eino-Ville Talvalad89821e2016-04-20 11:23:50 -070055#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070056#include <media/AudioSystem.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080057#include <media/IMediaHTTPService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070058#include <media/mediaplayer.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070059#include <mediautils/BatteryNotifier.h>
Steven Moreland886d7322021-04-02 04:19:45 +000060#include <processinfo/ProcessInfoService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070061#include <utils/Errors.h>
62#include <utils/Log.h>
63#include <utils/String16.h>
Svet Ganov94ec46f2018-06-08 15:03:46 -070064#include <utils/SystemClock.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080065#include <utils/Trace.h>
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080066#include <utils/CallStack.h>
Chien-Yu Chen98a668f2015-12-18 14:10:33 -080067#include <private/android_filesystem_config.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080068#include <system/camera_vendor_tags.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070069#include <system/camera_metadata.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080070
Ruben Brunkb2119af2014-05-09 19:57:56 -070071#include <system/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070072
73#include "CameraService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070074#include "api1/Camera2Client.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070075#include "api2/CameraDeviceClient.h"
Igor Murashkinff3e31d2013-10-23 16:40:06 -070076#include "utils/CameraTraces.h"
Emilian Peevbd8c5032018-02-14 23:05:40 +000077#include "utils/TagMonitor.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070078#include "utils/CameraThreadState.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070079#include "utils/CameraServiceProxyWrapper.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070080
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080081namespace {
82 const char* kPermissionServiceName = "permission";
83}; // namespace anonymous
84
Mathias Agopian65ab4712010-07-14 17:59:35 -070085namespace android {
86
Jayant Chowdharyb61526c2019-05-13 19:37:42 -070087using base::StringPrintf;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080088using binder::Status;
Austin Borgerea931242021-12-13 23:10:41 +000089using namespace camera3;
Jayant Chowdharybe543d42018-08-15 13:16:14 -070090using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -080091using hardware::ICamera;
92using hardware::ICameraClient;
93using hardware::ICameraServiceListener;
94using hardware::camera::common::V1_0::CameraDeviceStatus;
95using hardware::camera::common::V1_0::TorchModeStatus;
Cliff Wud8cae102021-03-11 01:37:42 +080096using hardware::camera2::ICameraInjectionCallback;
97using hardware::camera2::ICameraInjectionSession;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080098using hardware::camera2::utils::CameraIdAndSessionConfiguration;
99using hardware::camera2::utils::ConcurrentCameraIdCombination;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800100
Mathias Agopian65ab4712010-07-14 17:59:35 -0700101// ----------------------------------------------------------------------------
102// Logging support -- this is for debugging only
103// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700104volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700105
Steve Blockb8a80522011-12-20 16:23:08 +0000106#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
107#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700108
109static void setLogLevel(int level) {
110 android_atomic_write(level, &gLogLevel);
111}
112
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800113// Convenience methods for constructing binder::Status objects for error returns
114
115#define STATUS_ERROR(errorCode, errorString) \
116 binder::Status::fromServiceSpecificError(errorCode, \
117 String8::format("%s:%d: %s", __FUNCTION__, __LINE__, errorString))
118
119#define STATUS_ERROR_FMT(errorCode, errorString, ...) \
120 binder::Status::fromServiceSpecificError(errorCode, \
121 String8::format("%s:%d: " errorString, __FUNCTION__, __LINE__, \
122 __VA_ARGS__))
123
Mathias Agopian65ab4712010-07-14 17:59:35 -0700124// ----------------------------------------------------------------------------
125
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700126static const String16 sDumpPermission("android.permission.DUMP");
Svet Ganova453d0d2018-01-11 15:37:58 -0800127static const String16 sManageCameraPermission("android.permission.MANAGE_CAMERA");
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700128static const String16 sCameraPermission("android.permission.CAMERA");
129static const String16 sSystemCameraPermission("android.permission.SYSTEM_CAMERA");
130static const String16
131 sCameraSendSystemEventsPermission("android.permission.CAMERA_SEND_SYSTEM_EVENTS");
Shuzhen Wang695044d2020-03-06 09:02:23 -0800132static const String16 sCameraOpenCloseListenerPermission(
133 "android.permission.CAMERA_OPEN_CLOSE_LISTENER");
Cliff Wud8cae102021-03-11 01:37:42 +0800134static const String16
135 sCameraInjectExternalCameraPermission("android.permission.CAMERA_INJECT_EXTERNAL_CAMERA");
Rucha Katakwardf223072021-06-15 10:21:00 -0700136const char *sFileName = "lastOpenSessionDumpFile";
Eino-Ville Talvala7c602c32021-03-20 17:00:18 -0700137static constexpr int32_t kVendorClientScore = resource_policy::PERCEPTIBLE_APP_ADJ;
138static constexpr int32_t kVendorClientState = ActivityManager::PROCESS_STATE_PERSISTENT_UI;
139
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800140const String8 CameraService::kOfflineDevice("offline-");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -0700141const String16 CameraService::kWatchAllClientsFlag("all");
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700142
Rucha Katakward9ea6452021-05-06 11:57:16 -0700143// Set to keep track of logged service error events.
144static std::set<String8> sServiceErrorEventSet;
145
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800146CameraService::CameraService() :
147 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800148 mNumberOfCameras(0),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700149 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700150 mSoundRef(0), mInitialized(false),
151 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000152 ALOGI("CameraService started (pid=%d)", getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800153 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Rucha Katakwardf223072021-06-15 10:21:00 -0700154 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
155 if (mMemFd == -1) {
156 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
157 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700158}
159
Iliyan Malchev8951a972011-04-14 16:55:59 -0700160void CameraService::onFirstRef()
161{
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -0700162
Ruben Brunkcc776712015-02-17 20:18:47 -0800163 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800164
Iliyan Malchev8951a972011-04-14 16:55:59 -0700165 BnCameraService::onFirstRef();
166
Ruben Brunk99e69712015-05-26 17:25:07 -0700167 // Update battery life tracking if service is restarting
168 BatteryNotifier& notifier(BatteryNotifier::getInstance());
169 notifier.noteResetCamera();
170 notifier.noteResetFlashlight();
171
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800172 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800173
Emilian Peevf53f66e2017-04-11 14:29:43 +0100174 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800175 if (res == OK) {
176 mInitialized = true;
177 }
178
Svet Ganova453d0d2018-01-11 15:37:58 -0800179 mUidPolicy = new UidPolicy(this);
180 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800181 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
182 mSensorPrivacyPolicy->registerSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800183 mInjectionStatusListener = new InjectionStatusListener(this);
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700184 mAppOps.setCameraAudioRestriction(mAudioRestriction);
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700185 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
186 if (hcs->registerAsService() != android::OK) {
187 ALOGE("%s: Failed to register default android.frameworks.cameraservice.service@1.0",
188 __FUNCTION__);
189 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700190
191 // This needs to be last call in this function, so that it's as close to
192 // ServiceManager::addService() as possible.
Shuzhen Wang316781a2020-08-18 18:11:01 -0700193 CameraServiceProxyWrapper::pingCameraServiceProxy();
Shuzhen Wang24b44152019-09-20 10:38:11 -0700194 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800195}
196
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800197status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800198 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100199
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800200 std::vector<std::string> deviceIds;
201 {
202 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800203
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800204 if (nullptr == mCameraProviderManager.get()) {
205 mCameraProviderManager = new CameraProviderManager();
206 res = mCameraProviderManager->initialize(this);
207 if (res != OK) {
208 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
209 __FUNCTION__, strerror(-res), res);
Rucha Katakward9ea6452021-05-06 11:57:16 -0700210 logServiceError(String8::format("Unable to initialize camera provider manager"),
211 ERROR_DISCONNECTED);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800212 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100213 }
214 }
215
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800216
217 // Setup vendor tags before we call get_camera_info the first time
218 // because HAL might need to setup static vendor keys in get_camera_info
219 // TODO: maybe put this into CameraProviderManager::initialize()?
220 mCameraProviderManager->setUpVendorTags();
221
222 if (nullptr == mFlashlight.get()) {
223 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700224 }
225
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800226 res = mFlashlight->findFlashUnits();
227 if (res != OK) {
228 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
229 }
230
231 deviceIds = mCameraProviderManager->getCameraDeviceIds();
232 }
233
234
235 for (auto& cameraId : deviceIds) {
236 String8 id8 = String8(cameraId.c_str());
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800237 if (getCameraState(id8) == nullptr) {
238 onDeviceStatusChanged(id8, CameraDeviceStatus::PRESENT);
239 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800240 }
241
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700242 // Derive primary rear/front cameras, and filter their charactierstics.
243 // This needs to be done after all cameras are enumerated and camera ids are sorted.
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700244 if (SessionConfigurationUtils::IS_PERF_CLASS) {
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700245 // Assume internal cameras are advertised from the same
246 // provider. If multiple providers are registered at different time,
247 // and each provider contains multiple internal color cameras, the current
248 // logic may filter the characteristics of more than one front/rear color
249 // cameras.
250 Mutex::Autolock l(mServiceLock);
251 filterSPerfClassCharacteristicsLocked();
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700252 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700253
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800254 return OK;
255}
256
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700257void CameraService::broadcastTorchModeStatus(const String8& cameraId, TorchModeStatus status,
258 SystemCameraKind systemCameraKind) {
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800259 Mutex::Autolock lock(mStatusListenerLock);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800260 for (auto& i : mListenerList) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700261 if (shouldSkipStatusUpdates(systemCameraKind, i->isVendorListener(), i->getListenerPid(),
262 i->getListenerUid())) {
263 ALOGV("Skipping torch callback for system-only camera device %s",
264 cameraId.c_str());
265 continue;
266 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700267 i->getListener()->onTorchStatusChanged(mapToInterface(status), String16{cameraId});
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800268 }
269}
270
Mathias Agopian65ab4712010-07-14 17:59:35 -0700271CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800272 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800273 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800274 mSensorPrivacyPolicy->unregisterSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800275 mInjectionStatusListener->removeListener();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700276}
277
Emilian Peevaee727d2017-05-04 16:35:48 +0100278void CameraService::onNewProviderRegistered() {
279 enumerateProviders();
280}
281
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700282void CameraService::filterAPI1SystemCameraLocked(
283 const std::vector<std::string> &normalDeviceIds) {
284 mNormalDeviceIdsWithoutSystemCamera.clear();
285 for (auto &deviceId : normalDeviceIds) {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700286 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
287 if (getSystemCameraKind(String8(deviceId.c_str()), &deviceKind) != OK) {
288 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, deviceId.c_str());
289 continue;
290 }
291 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700292 // All system camera ids will necessarily come after public camera
293 // device ids as per the HAL interface contract.
294 break;
295 }
296 mNormalDeviceIdsWithoutSystemCamera.push_back(deviceId);
297 }
298 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
299 mNormalDeviceIdsWithoutSystemCamera.size());
300}
301
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700302status_t CameraService::getSystemCameraKind(const String8& cameraId, SystemCameraKind *kind) const {
303 auto state = getCameraState(cameraId);
304 if (state != nullptr) {
305 *kind = state->getSystemCameraKind();
306 return OK;
307 }
308 // Hidden physical camera ids won't have CameraState
309 return mCameraProviderManager->getSystemCameraKind(cameraId.c_str(), kind);
310}
311
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800312void CameraService::updateCameraNumAndIds() {
313 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700314 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
315 // Excludes hidden secure cameras
316 mNumberOfCameras =
317 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
318 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800319 mNormalDeviceIds =
320 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700321 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800322}
323
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700324void CameraService::filterSPerfClassCharacteristicsLocked() {
Shuzhen Wang89db2992021-05-20 13:09:48 -0700325 // To claim to be S Performance primary cameras, the cameras must be
326 // backward compatible. So performance class primary camera Ids must be API1
327 // compatible.
328 bool firstRearCameraSeen = false, firstFrontCameraSeen = false;
329 for (const auto& cameraId : mNormalDeviceIdsWithoutSystemCamera) {
330 int facing = -1;
331 int orientation = 0;
332 String8 cameraId8(cameraId.c_str());
333 getDeviceVersion(cameraId8, /*out*/&facing, /*out*/&orientation);
334 if (facing == -1) {
335 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
336 return;
337 }
338
339 if ((facing == hardware::CAMERA_FACING_BACK && !firstRearCameraSeen) ||
340 (facing == hardware::CAMERA_FACING_FRONT && !firstFrontCameraSeen)) {
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700341 status_t res = mCameraProviderManager->filterSmallJpegSizes(cameraId);
342 if (res == OK) {
343 mPerfClassPrimaryCameraIds.insert(cameraId);
344 } else {
345 ALOGE("%s: Failed to filter small JPEG sizes for performance class primary "
346 "camera %s: %s(%d)", __FUNCTION__, cameraId.c_str(), strerror(-res), res);
347 break;
348 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700349
350 if (facing == hardware::CAMERA_FACING_BACK) {
351 firstRearCameraSeen = true;
352 }
353 if (facing == hardware::CAMERA_FACING_FRONT) {
354 firstFrontCameraSeen = true;
355 }
356 }
357
358 if (firstRearCameraSeen && firstFrontCameraSeen) {
359 break;
360 }
361 }
362}
363
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100364void CameraService::addStates(const String8 id) {
365 std::string cameraId(id.c_str());
366 hardware::camera::common::V1_0::CameraResourceCost cost;
367 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700368 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100369 if (res != OK) {
370 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
371 return;
372 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700373 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
374 if (res != OK) {
375 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
376 return;
377 }
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100378 std::set<String8> conflicting;
379 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
380 conflicting.emplace(String8(cost.conflictingDevices[i].c_str()));
381 }
382
383 {
384 Mutex::Autolock lock(mCameraStatesLock);
385 mCameraStates.emplace(id, std::make_shared<CameraState>(id, cost.resourceCost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700386 conflicting, deviceKind));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100387 }
388
389 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100390 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100391 mTorchStatusMap.add(id, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800392
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700393 broadcastTorchModeStatus(id, TorchModeStatus::AVAILABLE_OFF, deviceKind);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100394 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800395
396 updateCameraNumAndIds();
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100397 logDeviceAdded(id, "Device added");
398}
399
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100400void CameraService::removeStates(const String8 id) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800401 updateCameraNumAndIds();
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100402 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100403 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100404 mTorchStatusMap.removeItem(id);
405 }
406
407 {
408 Mutex::Autolock lock(mCameraStatesLock);
409 mCameraStates.erase(id);
410 }
411}
412
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800413void CameraService::onDeviceStatusChanged(const String8& id,
414 CameraDeviceStatus newHalStatus) {
415 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
416 id.string(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700417
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800418 StatusInternal newStatus = mapToInternal(newHalStatus);
419
Ruben Brunkcc776712015-02-17 20:18:47 -0800420 std::shared_ptr<CameraState> state = getCameraState(id);
421
422 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700423 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100424 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700425 __FUNCTION__, id.string());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100426
427 // First add as absent to make sure clients are notified below
428 addStates(id);
429
430 updateStatus(newStatus, id);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700431 } else {
432 ALOGE("%s: Bad camera ID %s", __FUNCTION__, id.string());
433 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700434 return;
435 }
436
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800437 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800438
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800439 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800440 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700441 return;
442 }
443
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800444 if (newStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700445 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
446 newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800447
448 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
449 // to this device until the status changes
450 updateStatus(StatusInternal::NOT_PRESENT, id);
451
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800452 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700453 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800454 // Don't do this in updateStatus to avoid deadlock over mServiceLock
455 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700456
Ruben Brunkcc776712015-02-17 20:18:47 -0800457 // Remove cached shim parameters
458 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700459
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800460 // Remove online as well as offline client from the list of active clients,
461 // if they are present
462 clientToDisconnectOnline = removeClientLocked(id);
463 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + id);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700464 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800465
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800466 disconnectClient(id, clientToDisconnectOnline);
467 disconnectClient(kOfflineDevice + id, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700468
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100469 removeStates(id);
Ruben Brunkcc776712015-02-17 20:18:47 -0800470 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800471 if (oldStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700472 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
473 newStatus));
474 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800475 updateStatus(newStatus, id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700476 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800477}
Igor Murashkincba2c162013-03-20 15:56:31 -0700478
Shuzhen Wang43858162020-01-10 13:42:15 -0800479void CameraService::onDeviceStatusChanged(const String8& id,
480 const String8& physicalId,
481 CameraDeviceStatus newHalStatus) {
482 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
483 __FUNCTION__, id.string(), physicalId.string(), newHalStatus);
484
485 StatusInternal newStatus = mapToInternal(newHalStatus);
486
487 std::shared_ptr<CameraState> state = getCameraState(id);
488
489 if (state == nullptr) {
490 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
491 __FUNCTION__, id.string(), physicalId.string());
492 return;
493 }
494
495 StatusInternal logicalCameraStatus = state->getStatus();
496 if (logicalCameraStatus != StatusInternal::PRESENT &&
497 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
498 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
499 __FUNCTION__, physicalId.string(), newHalStatus, logicalCameraStatus);
500 return;
501 }
502
503 bool updated = false;
504 if (newStatus == StatusInternal::PRESENT) {
505 updated = state->removeUnavailablePhysicalId(physicalId);
506 } else {
507 updated = state->addUnavailablePhysicalId(physicalId);
508 }
509
510 if (updated) {
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800511 String8 idCombo = id + " : " + physicalId;
512 if (newStatus == StatusInternal::PRESENT) {
513 logDeviceAdded(idCombo,
514 String8::format("Device status changed to %d", newStatus));
515 } else {
516 logDeviceRemoved(idCombo,
517 String8::format("Device status changed to %d", newStatus));
518 }
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700519 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
520 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
521 if (getSystemCameraKind(id, &deviceKind) != OK) {
522 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.string());
523 return;
524 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800525 String16 id16(id), physicalId16(physicalId);
526 Mutex::Autolock lock(mStatusListenerLock);
527 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700528 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
529 listener->getListenerPid(), listener->getListenerUid())) {
530 ALOGV("Skipping discovery callback for system-only camera device %s",
531 id.c_str());
532 continue;
533 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800534 listener->getListener()->onPhysicalCameraStatusChanged(mapToInterface(newStatus),
535 id16, physicalId16);
536 }
537 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700538}
539
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800540void CameraService::disconnectClient(const String8& id, sp<BasicClient> clientToDisconnect) {
541 if (clientToDisconnect.get() != nullptr) {
542 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
543 __FUNCTION__, id.string());
544 // Notify the client of disconnection
545 clientToDisconnect->notifyError(
546 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
547 CaptureResultExtras{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800548 clientToDisconnect->disconnect();
549 }
550}
551
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800552void CameraService::onTorchStatusChanged(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800553 TorchModeStatus newStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700554 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
555 status_t res = getSystemCameraKind(cameraId, &systemCameraKind);
556 if (res != OK) {
557 ALOGE("%s: Could not get system camera kind for camera id %s", __FUNCTION__,
558 cameraId.string());
559 return;
560 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800561 Mutex::Autolock al(mTorchStatusMutex);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700562 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800563}
564
Jayant Chowdhary46ef0f52021-10-05 14:36:13 -0700565
566void CameraService::onTorchStatusChanged(const String8& cameraId,
567 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
568 Mutex::Autolock al(mTorchStatusMutex);
569 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
570}
571
Rucha Katakwar38284522021-11-10 11:25:21 -0800572void CameraService::broadcastTorchStrengthLevel(const String8& cameraId,
573 int32_t newStrengthLevel) {
574 Mutex::Autolock lock(mStatusListenerLock);
575 for (auto& i : mListenerList) {
576 i->getListener()->onTorchStrengthLevelChanged(String16{cameraId},
577 newStrengthLevel);
578 }
579}
580
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800581void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700582 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800583 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
584 __FUNCTION__, cameraId.string(), newStatus);
585
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800586 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800587 status_t res = getTorchStatusLocked(cameraId, &status);
588 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700589 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
590 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800591 return;
592 }
593 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800594 return;
595 }
596
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800597 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800598 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800599 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
600 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800601 return;
602 }
603
Ruben Brunkcc776712015-02-17 20:18:47 -0800604 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700605 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700606 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700607 auto iter = mTorchUidMap.find(cameraId);
608 if (iter != mTorchUidMap.end()) {
609 int oldUid = iter->second.second;
610 int newUid = iter->second.first;
611 BatteryNotifier& notifier(BatteryNotifier::getInstance());
612 if (oldUid != newUid) {
613 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800614 if (status == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700615 notifier.noteFlashlightOff(cameraId, oldUid);
616 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800617 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700618 notifier.noteFlashlightOn(cameraId, newUid);
619 }
620 iter->second.second = newUid;
621 } else {
622 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800623 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700624 notifier.noteFlashlightOn(cameraId, oldUid);
625 } else {
626 notifier.noteFlashlightOff(cameraId, oldUid);
627 }
628 }
629 }
630 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700631 broadcastTorchModeStatus(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800632}
633
Jayant Chowdharyc3198c32021-07-28 20:59:14 +0000634static bool hasPermissionsForSystemCamera(int callingPid, int callingUid,
635 bool logPermissionFailure = false) {
636 return checkPermission(sSystemCameraPermission, callingPid, callingUid,
637 logPermissionFailure) &&
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700638 checkPermission(sCameraPermission, callingPid, callingUid);
639}
640
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800641Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700642 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100643 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700644 bool hasSystemCameraPermissions =
645 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
646 CameraThreadState::getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700647 switch (type) {
648 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700649 if (hasSystemCameraPermissions) {
650 *numCameras = static_cast<int>(mNormalDeviceIds.size());
651 } else {
652 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
653 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800654 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700655 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700656 if (hasSystemCameraPermissions) {
657 *numCameras = mNumberOfCameras;
658 } else {
659 *numCameras = mNumberOfCamerasWithoutSystemCamera;
660 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800661 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700662 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800663 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700664 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800665 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
666 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700667 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800668 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700669}
670
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800671Status CameraService::getCameraInfo(int cameraId,
672 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700673 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100674 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700675 std::string cameraIdStr = cameraIdIntToStrLocked(cameraId);
676 if (shouldRejectSystemCameraConnection(String8(cameraIdStr.c_str()))) {
677 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
678 "characteristics for system only device %s: ", cameraIdStr.c_str());
679 }
Emilian Peevaee727d2017-05-04 16:35:48 +0100680
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800681 if (!mInitialized) {
Rucha Katakward9ea6452021-05-06 11:57:16 -0700682 logServiceError(String8::format("Camera subsystem is not available"),ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800683 return STATUS_ERROR(ERROR_DISCONNECTED,
684 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -0700685 }
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700686 bool hasSystemCameraPermissions =
687 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
688 CameraThreadState::getCallingUid());
689 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
690 if (hasSystemCameraPermissions) {
691 cameraIdBound = mNumberOfCameras;
692 }
693 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800694 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
695 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700696 }
697
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800698 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800699 status_t err = mCameraProviderManager->getCameraInfo(
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700700 cameraIdStr.c_str(), cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100701 if (err != OK) {
702 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
703 "Error retrieving camera info from device %d: %s (%d)", cameraId,
704 strerror(-err), err);
Rucha Katakward9ea6452021-05-06 11:57:16 -0700705 logServiceError(String8::format("Error retrieving camera info from device %d",cameraId),
706 ERROR_INVALID_OPERATION);
Ruben Brunkcc776712015-02-17 20:18:47 -0800707 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100708
Ruben Brunkcc776712015-02-17 20:18:47 -0800709 return ret;
710}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700711
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800712std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700713 const std::vector<std::string> *deviceIds = &mNormalDeviceIdsWithoutSystemCamera;
714 auto callingPid = CameraThreadState::getCallingPid();
715 auto callingUid = CameraThreadState::getCallingUid();
Jayant Chowdharyc3198c32021-07-28 20:59:14 +0000716 if (checkPermission(sSystemCameraPermission, callingPid, callingUid,
717 /*logPermissionFailure*/false) || getpid() == callingPid) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700718 deviceIds = &mNormalDeviceIds;
719 }
720 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(deviceIds->size())) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800721 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700722 __FUNCTION__, cameraIdInt, deviceIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800723 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800724 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800725
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700726 return (*deviceIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800727}
728
729String8 CameraService::cameraIdIntToStr(int cameraIdInt) {
730 Mutex::Autolock lock(mServiceLock);
731 return String8(cameraIdIntToStrLocked(cameraIdInt).c_str());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800732}
733
734Status CameraService::getCameraCharacteristics(const String16& cameraId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700735 int targetSdkVersion, CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700736 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700737 if (!cameraInfo) {
738 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800739 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -0700740 }
741
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800742 if (!mInitialized) {
743 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Rucha Katakward9ea6452021-05-06 11:57:16 -0700744 logServiceError(String8::format("Camera subsystem is not available"),ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800745 return STATUS_ERROR(ERROR_DISCONNECTED,
746 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -0700747 }
748
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700749 if (shouldRejectSystemCameraConnection(String8(cameraId))) {
750 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
751 "characteristics for system only device %s: ", String8(cameraId).string());
752 }
753
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800754 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800755
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700756
757 std::string cameraIdStr = String8(cameraId).string();
758 bool overrideForPerfClass =
759 SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
760 cameraIdStr, targetSdkVersion);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100761 status_t res = mCameraProviderManager->getCameraCharacteristics(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700762 cameraIdStr, overrideForPerfClass, cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100763 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700764 if (res == NAME_NOT_FOUND) {
765 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
766 "characteristics for unknown device %s: %s (%d)", String8(cameraId).string(),
767 strerror(-res), res);
768 } else {
Rucha Katakward9ea6452021-05-06 11:57:16 -0700769 logServiceError(String8::format("Unable to retrieve camera characteristics for "
770 "device %s.", String8(cameraId).string()),ERROR_INVALID_OPERATION);
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700771 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
772 "characteristics for device %s: %s (%d)", String8(cameraId).string(),
773 strerror(-res), res);
774 }
Ruben Brunkb2119af2014-05-09 19:57:56 -0700775 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700776 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
777 if (getSystemCameraKind(String8(cameraId), &deviceKind) != OK) {
778 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, String8(cameraId).string());
779 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera kind "
780 "for device %s", String8(cameraId).string());
781 }
Jayant Chowdhary12361932018-08-27 14:46:13 -0700782 int callingPid = CameraThreadState::getCallingPid();
783 int callingUid = CameraThreadState::getCallingUid();
Emilian Peeve20c6372018-08-14 18:45:53 +0100784 std::vector<int32_t> tagsRemoved;
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700785 // If it's not calling from cameraserver, check the permission only if
786 // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
787 // it would've already been checked in shouldRejectSystemCameraConnection.
Emilian Peeve20c6372018-08-14 18:45:53 +0100788 if ((callingPid != getpid()) &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700789 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700790 !checkPermission(sCameraPermission, callingPid, callingUid)) {
Emilian Peeve20c6372018-08-14 18:45:53 +0100791 res = cameraInfo->removePermissionEntries(
792 mCameraProviderManager->getProviderTagIdLocked(String8(cameraId).string()),
793 &tagsRemoved);
794 if (res != OK) {
795 cameraInfo->clear();
796 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
797 " characteristics needing camera permission for device %s: %s (%d)",
798 String8(cameraId).string(), strerror(-res), res);
799 }
800 }
801
802 if (!tagsRemoved.empty()) {
803 res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
804 tagsRemoved.data(), tagsRemoved.size());
805 if (res != OK) {
806 cameraInfo->clear();
807 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
808 "keys needing permission for device %s: %s (%d)", String8(cameraId).string(),
809 strerror(-res), res);
810 }
811 }
812
Zhijun He2b59be82013-09-25 10:14:30 -0700813 return ret;
814}
815
Rucha Katakwar38284522021-11-10 11:25:21 -0800816Status CameraService::getTorchStrengthLevel(const String16& cameraId,
817 int32_t* torchStrength) {
818 ATRACE_CALL();
819 Mutex::Autolock l(mServiceLock);
820 if (!mInitialized) {
821 ALOGE("%s: Camera HAL couldn't be initialized.", __FUNCTION__);
822 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera HAL couldn't be initialized.");
823 }
824
825 if(torchStrength == NULL) {
826 ALOGE("%s: strength level must not be null.", __FUNCTION__);
827 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Strength level should not be null.");
828 }
829
830 status_t res = mCameraProviderManager->getTorchStrengthLevel(String8(cameraId).string(),
831 torchStrength);
832 if (res != OK) {
833 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve torch "
834 "strength level for device %s: %s (%d)", String8(cameraId).string(),
835 strerror(-res), res);
836 }
837 ALOGI("%s: Torch strength level is: %d", __FUNCTION__, *torchStrength);
838 return Status::ok();
839}
840
Ruben Brunkcc776712015-02-17 20:18:47 -0800841String8 CameraService::getFormattedCurrentTime() {
842 time_t now = time(nullptr);
843 char formattedTime[64];
844 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
845 return String8(formattedTime);
846}
847
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800848Status CameraService::getCameraVendorTagDescriptor(
849 /*out*/
850 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700851 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800852 if (!mInitialized) {
853 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800854 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800855 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -0800856 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
857 if (globalDescriptor != nullptr) {
858 *desc = *(globalDescriptor.get());
859 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800860 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800861}
862
Emilian Peev71c73a22017-03-21 16:35:51 +0000863Status CameraService::getCameraVendorTagCache(
864 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
865 ATRACE_CALL();
866 if (!mInitialized) {
867 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
868 return STATUS_ERROR(ERROR_DISCONNECTED,
869 "Camera subsystem not available");
870 }
871 sp<VendorTagDescriptorCache> globalCache =
872 VendorTagDescriptorCache::getGlobalVendorTagCache();
873 if (globalCache != nullptr) {
874 *cache = *(globalCache.get());
875 }
876 return Status::ok();
877}
878
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -0700879void CameraService::clearCachedVariables() {
880 BasicClient::BasicClient::sCameraService = nullptr;
881}
882
Emilian Peevb91f1802021-03-23 14:50:28 -0700883int CameraService::getDeviceVersion(const String8& cameraId, int* facing, int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700884 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800885
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800886 int deviceVersion = 0;
887
Emilian Peevf53f66e2017-04-11 14:29:43 +0100888 status_t res;
889 hardware::hidl_version maxVersion{0,0};
890 res = mCameraProviderManager->getHighestSupportedVersion(cameraId.string(),
891 &maxVersion);
892 if (res != OK) return -1;
893 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800894
Emilian Peevf53f66e2017-04-11 14:29:43 +0100895 hardware::CameraInfo info;
896 if (facing) {
897 res = mCameraProviderManager->getCameraInfo(cameraId.string(), &info);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -0800898 if (res != OK) return -1;
Emilian Peevf53f66e2017-04-11 14:29:43 +0100899 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -0700900 if (orientation) {
901 *orientation = info.orientation;
902 }
Igor Murashkin634a5152013-02-20 17:15:11 -0800903 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100904
Igor Murashkin634a5152013-02-20 17:15:11 -0800905 return deviceVersion;
906}
907
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800908Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700909 switch(err) {
910 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800911 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800912 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800913 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
914 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800915 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800916 return STATUS_ERROR(ERROR_DISCONNECTED,
917 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700918 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800919 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
920 "Camera HAL encountered error %d: %s",
921 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700922 }
Igor Murashkinbfc99152013-02-27 12:55:20 -0800923}
924
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800925Status CameraService::makeClient(const sp<CameraService>& cameraService,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800926 const sp<IInterface>& cameraCb, const String16& packageName,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700927 const std::optional<String16>& featureId, const String8& cameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -0700928 int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700929 int servicePid, int deviceVersion, apiLevel effectiveApiLevel, bool overrideForPerfClass,
Ruben Brunkcc776712015-02-17 20:18:47 -0800930 /*out*/sp<BasicClient>* client) {
931
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700932 // Create CameraClient based on device version reported by the HAL.
933 switch(deviceVersion) {
934 case CAMERA_DEVICE_API_VERSION_1_0:
935 ALOGE("Camera using old HAL version: %d", deviceVersion);
936 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
937 "Camera device \"%s\" HAL version %d no longer supported",
938 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800939 break;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700940 case CAMERA_DEVICE_API_VERSION_3_0:
941 case CAMERA_DEVICE_API_VERSION_3_1:
942 case CAMERA_DEVICE_API_VERSION_3_2:
943 case CAMERA_DEVICE_API_VERSION_3_3:
944 case CAMERA_DEVICE_API_VERSION_3_4:
945 case CAMERA_DEVICE_API_VERSION_3_5:
946 case CAMERA_DEVICE_API_VERSION_3_6:
Shuzhen Wang83bff122020-11-20 15:51:39 -0800947 case CAMERA_DEVICE_API_VERSION_3_7:
Shuzhen Wang90708ea2021-11-04 11:40:49 -0700948 case CAMERA_DEVICE_API_VERSION_3_8:
Ruben Brunkcc776712015-02-17 20:18:47 -0800949 if (effectiveApiLevel == API_1) { // Camera1 API route
950 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800951 *client = new Camera2Client(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800952 cameraId, api1CameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -0700953 facing, sensorOrientation, clientPid, clientUid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700954 servicePid, overrideForPerfClass);
Ruben Brunkcc776712015-02-17 20:18:47 -0800955 } else { // Camera2 API route
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800956 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
957 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800958 *client = new CameraDeviceClient(cameraService, tmp, packageName, featureId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700959 cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid,
960 overrideForPerfClass);
Ruben Brunkcc776712015-02-17 20:18:47 -0800961 }
962 break;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700963 default:
Ruben Brunkcc776712015-02-17 20:18:47 -0800964 // Should not be reachable
965 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800966 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800967 "Camera device \"%s\" has unknown HAL version %d",
968 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800969 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800970 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800971}
972
Ruben Brunk6267b532015-04-30 17:44:07 -0700973String8 CameraService::toString(std::set<userid_t> intSet) {
974 String8 s("");
975 bool first = true;
976 for (userid_t i : intSet) {
977 if (first) {
978 s.appendFormat("%d", i);
979 first = false;
980 } else {
981 s.appendFormat(", %d", i);
982 }
983 }
984 return s;
985}
986
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800987int32_t CameraService::mapToInterface(TorchModeStatus status) {
988 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
989 switch (status) {
990 case TorchModeStatus::NOT_AVAILABLE:
991 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
992 break;
993 case TorchModeStatus::AVAILABLE_OFF:
994 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
995 break;
996 case TorchModeStatus::AVAILABLE_ON:
997 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
998 break;
999 default:
1000 ALOGW("Unknown new flash status: %d", status);
1001 }
1002 return serviceStatus;
1003}
1004
1005CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
1006 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
1007 switch (status) {
1008 case CameraDeviceStatus::NOT_PRESENT:
1009 serviceStatus = StatusInternal::NOT_PRESENT;
1010 break;
1011 case CameraDeviceStatus::PRESENT:
1012 serviceStatus = StatusInternal::PRESENT;
1013 break;
1014 case CameraDeviceStatus::ENUMERATING:
1015 serviceStatus = StatusInternal::ENUMERATING;
1016 break;
1017 default:
1018 ALOGW("Unknown new HAL device status: %d", status);
1019 }
1020 return serviceStatus;
1021}
1022
1023int32_t CameraService::mapToInterface(StatusInternal status) {
1024 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1025 switch (status) {
1026 case StatusInternal::NOT_PRESENT:
1027 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1028 break;
1029 case StatusInternal::PRESENT:
1030 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
1031 break;
1032 case StatusInternal::ENUMERATING:
1033 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
1034 break;
1035 case StatusInternal::NOT_AVAILABLE:
1036 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
1037 break;
1038 case StatusInternal::UNKNOWN:
1039 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
1040 break;
1041 default:
1042 ALOGW("Unknown new internal device status: %d", status);
1043 }
1044 return serviceStatus;
1045}
1046
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001047Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001048 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -07001049
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001050 String16 internalPackageName("cameraserver");
Ruben Brunkcc776712015-02-17 20:18:47 -08001051 String8 id = String8::format("%d", cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001052 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001053 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001054 if (!(ret = connectHelper<ICameraClient,Client>(
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001055 sp<ICameraClient>{nullptr}, id, cameraId,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001056 internalPackageName, {}, uid, USE_CALLING_PID,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001057 API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0,
1058 /*targetSdkVersion*/ __ANDROID_API_FUTURE__, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001059 ).isOk()) {
1060 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
Ruben Brunkb2119af2014-05-09 19:57:56 -07001061 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001062 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001063}
1064
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001065Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -07001066 /*out*/
1067 CameraParameters* parameters) {
1068
1069 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1070
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001071 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001072
1073 if (parameters == NULL) {
1074 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001075 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001076 }
1077
Ruben Brunkcc776712015-02-17 20:18:47 -08001078 String8 id = String8::format("%d", cameraId);
1079
1080 // Check if we already have parameters
1081 {
1082 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001083 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001084 auto cameraState = getCameraState(id);
1085 if (cameraState == nullptr) {
1086 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001087 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1088 "Invalid camera ID: %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001089 }
1090 CameraParameters p = cameraState->getShimParams();
1091 if (!p.isEmpty()) {
1092 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001093 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001094 }
1095 }
1096
Jayant Chowdhary12361932018-08-27 14:46:13 -07001097 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001098 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001099 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001100 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001101 // Error already logged by callee
1102 return ret;
1103 }
1104
1105 // Check for parameters again
1106 {
1107 // Scope for service lock
1108 Mutex::Autolock lock(mServiceLock);
1109 auto cameraState = getCameraState(id);
1110 if (cameraState == nullptr) {
1111 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001112 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1113 "Invalid camera ID: %s", id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001114 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001115 CameraParameters p = cameraState->getShimParams();
1116 if (!p.isEmpty()) {
1117 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001118 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001119 }
1120 }
1121
Ruben Brunkcc776712015-02-17 20:18:47 -08001122 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1123 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001124 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001125}
1126
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001127// Can camera service trust the caller based on the calling UID?
1128static bool isTrustedCallingUid(uid_t uid) {
1129 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001130 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001131 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001132 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001133 return true;
1134 default:
1135 return false;
1136 }
1137}
1138
Nicholas Sauera3620332019-04-03 14:05:17 -07001139static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1140 PermissionController pc;
1141 uid = pc.getPackageUid(packageName, 0);
1142 if (uid <= 0) {
1143 ALOGE("Unknown package: '%s'", String8(packageName).string());
1144 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
1145 return BAD_VALUE;
1146 }
1147
1148 if (userId < 0) {
1149 ALOGE("Invalid user: %d", userId);
1150 dprintf(err, "Invalid user: %d\n", userId);
1151 return BAD_VALUE;
1152 }
1153
1154 uid = multiuser_get_uid(userId, uid);
1155 return NO_ERROR;
1156}
1157
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001158Status CameraService::validateConnectLocked(const String8& cameraId,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001159 const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
1160 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001161
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001162#ifdef __BRILLO__
1163 UNUSED(clientName8);
1164 UNUSED(clientUid);
1165 UNUSED(clientPid);
1166 UNUSED(originalClientPid);
1167#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001168 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1169 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001170 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001171 return allowed;
1172 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001173#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001174
Jayant Chowdhary12361932018-08-27 14:46:13 -07001175 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001176
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001177 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001178 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1179 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001180 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1181 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001182 }
1183
Ruben Brunkcc776712015-02-17 20:18:47 -08001184 if (getCameraState(cameraId) == nullptr) {
1185 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1186 cameraId.string());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001187 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1188 "No camera device with ID \"%s\" available", cameraId.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001189 }
1190
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001191 status_t err = checkIfDeviceIsUsable(cameraId);
1192 if (err != NO_ERROR) {
1193 switch(err) {
1194 case -ENODEV:
1195 case -EBUSY:
1196 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1197 "No camera device with ID \"%s\" currently available", cameraId.string());
1198 default:
1199 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1200 "Unknown error connecting to ID \"%s\"", cameraId.string());
1201 }
1202 }
1203 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001204}
1205
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001206Status CameraService::validateClientPermissionsLocked(const String8& cameraId,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001207 const String8& clientName8, int& clientUid, int& clientPid,
1208 /*out*/int& originalClientPid) const {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001209 int callingPid = CameraThreadState::getCallingPid();
1210 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001211
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001212 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001213 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001214 clientUid = callingUid;
1215 } else if (!isTrustedCallingUid(callingUid)) {
1216 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1217 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001218 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1219 "Untrusted caller (calling PID %d, UID %d) trying to "
1220 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1221 callingPid, callingUid, cameraId.string(),
1222 clientName8.string(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001223 }
1224
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001225 // Check if we can trust clientPid
1226 if (clientPid == USE_CALLING_PID) {
1227 clientPid = callingPid;
1228 } else if (!isTrustedCallingUid(callingUid)) {
1229 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1230 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001231 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1232 "Untrusted caller (calling PID %d, UID %d) trying to "
1233 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1234 callingPid, callingUid, cameraId.string(),
1235 clientName8.string(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001236 }
1237
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001238 if (shouldRejectSystemCameraConnection(cameraId)) {
1239 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1240 cameraId.c_str());
1241 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
1242 "available", cameraId.string());
1243 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001244 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1245 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1246 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
1247 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
1248 "found while trying to query device kind", cameraId.string());
1249
1250 }
1251
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001252 // If it's not calling from cameraserver, check the permission if the
1253 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1254 // android.permission.SYSTEM_CAMERA for system only camera devices).
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001255 if (callingPid != getpid() &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001256 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001257 !checkPermission(sCameraPermission, clientPid, clientUid)) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001258 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001259 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1260 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
1261 clientName8.string(), clientUid, clientPid, cameraId.string());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001262 }
1263
Svet Ganova453d0d2018-01-11 15:37:58 -08001264 // Make sure the UID is in an active state to use the camera
Svet Ganov7b4ab782018-03-25 12:48:10 -07001265 if (!mUidPolicy->isUidActive(callingUid, String16(clientName8))) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001266 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001267 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1268 clientPid, clientUid);
1269 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001270 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1271 "calling UID %d proc state %" PRId32 ")",
1272 clientName8.string(), clientUid, clientPid, cameraId.string(),
1273 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001274 }
1275
Michael Grooverd1d435a2018-12-18 17:39:42 -08001276 // If sensor privacy is enabled then prevent access to the camera
1277 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1278 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1279 return STATUS_ERROR_FMT(ERROR_DISABLED,
1280 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
1281 "is enabled", clientName8.string(), clientUid, clientPid, cameraId.string());
1282 }
1283
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001284 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1285 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001286 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001287 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001288
Ruben Brunk6267b532015-04-30 17:44:07 -07001289 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001290
Ruben Brunka8ca9152015-04-07 14:23:40 -07001291 // Only allow clients who are being used by the current foreground device user, unless calling
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001292 // from our own process OR the caller is using the cameraserver's HIDL interface.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001293 if (getCurrentServingCall() != BinderCallType::HWBINDER && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001294 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001295 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1296 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
1297 toString(mAllowedUsers).string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001298 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1299 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
1300 clientUserId, cameraId.string());
Ruben Brunk36597b22015-03-20 22:15:57 -07001301 }
1302
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001303 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001304}
1305
1306status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
1307 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001308 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001309 if (cameraState == nullptr) {
1310 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1311 cameraId.string());
1312 return -ENODEV;
1313 }
1314
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001315 StatusInternal currentStatus = cameraState->getStatus();
1316 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001317 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
1318 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001319 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001320 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001321 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
1322 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001323 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001324 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001325
Ruben Brunkcc776712015-02-17 20:18:47 -08001326 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001327}
1328
Ruben Brunkcc776712015-02-17 20:18:47 -08001329void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001330 const CameraService::DescriptorPtr& desc, int oomScoreOffset) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001331
Ruben Brunkcc776712015-02-17 20:18:47 -08001332 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001333 auto clientDescriptor =
1334 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
1335 oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08001336 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1337
1338 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
1339 String8(client->getPackageName()));
1340
1341 if (evicted.size() > 0) {
1342 // This should never happen - clients should already have been removed in disconnect
1343 for (auto& i : evicted) {
1344 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
1345 __FUNCTION__, i->getKey().string());
1346 }
1347
1348 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1349 __FUNCTION__);
1350 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001351
1352 // And register a death notification for the client callback. Do
1353 // this last to avoid Binder policy where a nested Binder
1354 // transaction might be pre-empted to service the client death
1355 // notification if the client process dies before linkToDeath is
1356 // invoked.
1357 sp<IBinder> remoteCallback = client->getRemote();
1358 if (remoteCallback != nullptr) {
1359 remoteCallback->linkToDeath(this);
1360 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001361}
1362
1363status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
1364 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001365 int oomScoreOffset,
Ruben Brunkcc776712015-02-17 20:18:47 -08001366 /*out*/
1367 sp<BasicClient>* client,
1368 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001369 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001370 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001371 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001372 DescriptorPtr clientDescriptor;
1373 {
1374 if (effectiveApiLevel == API_1) {
1375 // If we are using API1, any existing client for this camera ID with the same remote
1376 // should be returned rather than evicted to allow MediaRecorder to work properly.
1377
1378 auto current = mActiveClientManager.get(cameraId);
1379 if (current != nullptr) {
1380 auto clientSp = current->getValue();
1381 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001382 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
Shuzhen Wangb2d43f62021-08-25 14:01:11 -07001383 ALOGW("CameraService connect called with a different"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001384 " API level, evicting prior client...");
1385 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001386 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001387 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001388 *client = clientSp;
1389 return NO_ERROR;
1390 }
1391 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001392 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001393 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001394
Ruben Brunkcc776712015-02-17 20:18:47 -08001395 // Get current active client PIDs
1396 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1397 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001398
Emilian Peev8131a262017-02-01 12:33:43 +00001399 std::vector<int> priorityScores(ownerPids.size());
1400 std::vector<int> states(ownerPids.size());
Igor Murashkine6800ce2013-03-04 17:25:57 -08001401
Emilian Peev8131a262017-02-01 12:33:43 +00001402 // Get priority scores of all active PIDs
1403 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1404 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1405 /*out*/&priorityScores[0]);
1406 if (err != OK) {
1407 ALOGE("%s: Priority score query failed: %d",
1408 __FUNCTION__, err);
1409 return err;
1410 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001411
Ruben Brunkcc776712015-02-17 20:18:47 -08001412 // Update all active clients' priorities
Emilian Peev8131a262017-02-01 12:33:43 +00001413 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
Ruben Brunkcc776712015-02-17 20:18:47 -08001414 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
Emilian Peev8131a262017-02-01 12:33:43 +00001415 pidToPriorityMap.emplace(ownerPids[i],
Jayant Chowdharyc578a502019-05-08 10:57:54 -07001416 resource_policy::ClientPriority(priorityScores[i], states[i],
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001417 /* isVendorClient won't get copied over*/ false,
1418 /* oomScoreOffset won't get copied over*/ 0));
Ruben Brunkcc776712015-02-17 20:18:47 -08001419 }
1420 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001421
Ruben Brunkcc776712015-02-17 20:18:47 -08001422 // Get state for the given cameraId
1423 auto state = getCameraState(cameraId);
1424 if (state == nullptr) {
1425 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1426 clientPid, cameraId.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001427 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001428 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001429 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001430
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001431 int32_t actualScore = priorityScores[priorityScores.size() - 1];
1432 int32_t actualState = states[states.size() - 1];
1433
1434 // Make descriptor for incoming client. We store the oomScoreOffset
1435 // since we might need it later on new handleEvictionsLocked and
1436 // ProcessInfoService would not take that into account.
Shuzhen Wang2db86ff2018-04-25 01:11:17 +00001437 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001438 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001439 state->getConflicting(), actualScore, clientPid, actualState,
1440 oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08001441
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001442 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1443
Ruben Brunkcc776712015-02-17 20:18:47 -08001444 // Find clients that would be evicted
1445 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1446
1447 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1448 // background, so we cannot do evictions
1449 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1450 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1451 " priority).", clientPid);
1452
1453 sp<BasicClient> clientSp = clientDescriptor->getValue();
1454 String8 curTime = getFormattedCurrentTime();
1455 auto incompatibleClients =
1456 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1457
1458 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Emilian Peev8131a262017-02-01 12:33:43 +00001459 "(PID %d, score %d state %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001460 cameraId.string(), packageName.string(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001461 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001462
1463 for (auto& i : incompatibleClients) {
1464 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001465 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
1466 i->getKey().string(),
1467 String8{i->getValue()->getPackageName()}.string(),
1468 i->getOwnerId(), i->getPriority().getScore(),
1469 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001470 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00001471 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(),
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001472 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001473 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001474 }
1475
1476 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001477 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001478 mEventLog.add(msg);
1479
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001480 auto current = mActiveClientManager.get(cameraId);
1481 if (current != nullptr) {
1482 return -EBUSY; // CAMERA_IN_USE
1483 } else {
1484 return -EUSERS; // MAX_CAMERAS_IN_USE
1485 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001486 }
1487
1488 for (auto& i : evicted) {
1489 sp<BasicClient> clientSp = i->getValue();
1490 if (clientSp.get() == nullptr) {
1491 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1492
1493 // TODO: Remove this
1494 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1495 __FUNCTION__);
1496 mActiveClientManager.remove(i);
1497 continue;
1498 }
1499
1500 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1501 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001502 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001503
Ruben Brunkcc776712015-02-17 20:18:47 -08001504 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001505 logEvent(String8::format("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00001506 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1507 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001508 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
Emilian Peev8131a262017-02-01 12:33:43 +00001509 i->getOwnerId(), i->getPriority().getScore(),
1510 i->getPriority().getState(), cameraId.string(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001511 packageName.string(), clientPid, clientPriority.getScore(),
1512 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08001513
1514 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001515 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001516 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001517 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001518 }
1519
Ruben Brunkcc776712015-02-17 20:18:47 -08001520 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1521 // other clients from connecting in mServiceLockWrapper if held
1522 mServiceLock.unlock();
1523
1524 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07001525 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001526
1527 // Destroy evicted clients
1528 for (auto& i : evictedClients) {
1529 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001530 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001531 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001532
Jayant Chowdhary12361932018-08-27 14:46:13 -07001533 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08001534
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001535 for (const auto& i : evictedClients) {
1536 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1537 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1538 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1539 if (ret == TIMED_OUT) {
1540 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1541 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1542 mActiveClientManager.toString().string());
1543 return -EBUSY;
1544 }
1545 if (ret != NO_ERROR) {
1546 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1547 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1548 ret, mActiveClientManager.toString().string());
1549 return ret;
1550 }
1551 }
1552
1553 evictedClients.clear();
1554
Ruben Brunkcc776712015-02-17 20:18:47 -08001555 // Once clients have been disconnected, relock
1556 mServiceLock.lock();
1557
1558 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1559 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1560 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001561 }
1562
Ruben Brunkcc776712015-02-17 20:18:47 -08001563 *partial = clientDescriptor;
1564 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001565}
1566
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001567Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001568 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001569 int api1CameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001570 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001571 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001572 int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001573 int targetSdkVersion,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001574 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001575 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001576
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001577 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001578 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001579
1580 String8 id = cameraIdIntToStr(api1CameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001581 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001582 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001583 clientPackageName, {}, clientUid, clientPid, API_1,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001584 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001585
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001586 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001587 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001588 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001589 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001590 }
1591
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001592 *device = client;
1593 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001594}
1595
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001596bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
1597 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001598 // If the client is not a vendor client, don't add listener if
1599 // a) the camera is a publicly hidden secure camera OR
1600 // b) the camera is a system only camera and the client doesn't
1601 // have android.permission.SYSTEM_CAMERA permissions.
1602 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
1603 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1604 !hasPermissionsForSystemCamera(clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001605 return true;
1606 }
1607 return false;
1608}
1609
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001610bool CameraService::shouldRejectSystemCameraConnection(const String8& cameraId) const {
1611 // Rules for rejection:
1612 // 1) If cameraserver tries to access this camera device, accept the
1613 // connection.
1614 // 2) The camera device is a publicly hidden secure camera device AND some
1615 // component is trying to access it on a non-hwbinder thread (generally a non HAL client),
1616 // reject it.
1617 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
1618 // and the serving thread is a non hwbinder thread, the client must have
1619 // android.permission.SYSTEM_CAMERA permissions to connect.
1620
1621 int cPid = CameraThreadState::getCallingPid();
1622 int cUid = CameraThreadState::getCallingUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001623 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
1624 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001625 // This isn't a known camera ID, so it's not a system camera
1626 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
1627 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001628 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001629
1630 // (1) Cameraserver trying to connect, accept.
1631 if (CameraThreadState::getCallingPid() == getpid()) {
1632 return false;
1633 }
1634 // (2)
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001635 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001636 systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
1637 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
1638 return true;
1639 }
1640 // (3) Here we only check for permissions if it is a system only camera device. This is since
1641 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
1642 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
1643 // same behavior for system camera devices.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001644 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001645 systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Jayant Chowdharyc3198c32021-07-28 20:59:14 +00001646 !hasPermissionsForSystemCamera(cPid, cUid, /*logPermissionFailure*/true)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001647 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
1648 cameraId.c_str());
1649 return true;
1650 }
1651
1652 return false;
1653}
1654
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001655Status CameraService::connectDevice(
1656 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001657 const String16& cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001658 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001659 const std::optional<String16>& clientFeatureId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001660 int clientUid, int oomScoreOffset, int targetSdkVersion,
Ruben Brunkcc776712015-02-17 20:18:47 -08001661 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001662 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001663
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001664 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001665 Status ret = Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001666 String8 id = String8(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001667 sp<CameraDeviceClient> client = nullptr;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001668 String16 clientPackageNameAdj = clientPackageName;
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001669 int callingPid = CameraThreadState::getCallingPid();
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001670
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001671 if (getCurrentServingCall() == BinderCallType::HWBINDER) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001672 std::string vendorClient =
1673 StringPrintf("vendor.client.pid<%d>", CameraThreadState::getCallingPid());
1674 clientPackageNameAdj = String16(vendorClient.c_str());
1675 }
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001676
1677 if (oomScoreOffset < 0) {
1678 String8 msg =
1679 String8::format("Cannot increase the priority of a client %s pid %d for "
1680 "camera id %s", String8(clientPackageNameAdj).string(), callingPid,
1681 id.string());
1682 ALOGE("%s: %s", __FUNCTION__, msg.string());
1683 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
1684 }
1685
1686 // enforce system camera permissions
1687 if (oomScoreOffset > 0 &&
1688 !hasPermissionsForSystemCamera(callingPid, CameraThreadState::getCallingUid())) {
1689 String8 msg =
1690 String8::format("Cannot change the priority of a client %s pid %d for "
1691 "camera id %s without SYSTEM_CAMERA permissions",
1692 String8(clientPackageNameAdj).string(), callingPid, id.string());
1693 ALOGE("%s: %s", __FUNCTION__, msg.string());
1694 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.string());
1695 }
1696
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001697 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001698 /*api1CameraId*/-1, clientPackageNameAdj, clientFeatureId,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001699 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, oomScoreOffset,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001700 targetSdkVersion, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08001701
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001702 if(!ret.isOk()) {
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001703 logRejected(id, callingPid, String8(clientPackageNameAdj), ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001704 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001705 }
1706
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001707 *device = client;
Rucha Katakwardf223072021-06-15 10:21:00 -07001708 Mutex::Autolock lock(mServiceLock);
1709
1710 // Clear the previous cached logs and reposition the
1711 // file offset to beginning of the file to log new data.
1712 // If either truncate or lseek fails, close the previous file and create a new one.
1713 if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
1714 ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
1715 // Close the previous memfd.
1716 close(mMemFd);
1717 // If failure to wipe the data, then create a new file and
1718 // assign the new value to mMemFd.
1719 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
1720 if (mMemFd == -1) {
1721 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
1722 }
1723 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001724 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001725}
1726
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001727template<class CALLBACK, class CLIENT>
1728Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001729 int api1CameraId, const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001730 const std::optional<String16>& clientFeatureId, int clientUid, int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001731 apiLevel effectiveApiLevel, bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001732 /*out*/sp<CLIENT>& device) {
1733 binder::Status ret = binder::Status::ok();
1734
1735 String8 clientName8(clientPackageName);
1736
1737 int originalClientPid = 0;
1738
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001739 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001740 "Camera API version %d", clientPid, clientName8.string(), cameraId.string(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001741 static_cast<int>(effectiveApiLevel));
1742
Shuzhen Wang316781a2020-08-18 18:11:01 -07001743 nsecs_t openTimeNs = systemTime();
1744
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001745 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001746 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07001747 int orientation = 0;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001748 bool isNdk = (clientPackageName.size() == 0);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001749 {
1750 // Acquire mServiceLock and prevent other clients from connecting
1751 std::unique_ptr<AutoConditionLock> lock =
1752 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1753
1754 if (lock == nullptr) {
1755 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
1756 , clientPid);
1757 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1758 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
1759 cameraId.string(), clientName8.string(), clientPid);
1760 }
1761
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07001762 // Enforce client permissions and do basic validity checks
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001763 if(!(ret = validateConnectLocked(cameraId, clientName8,
1764 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
1765 return ret;
1766 }
1767
1768 // Check the shim parameters after acquiring lock, if they have already been updated and
1769 // we were doing a shim update, return immediately
1770 if (shimUpdateOnly) {
1771 auto cameraState = getCameraState(cameraId);
1772 if (cameraState != nullptr) {
1773 if (!cameraState->getShimParams().isEmpty()) return ret;
1774 }
1775 }
1776
1777 status_t err;
1778
1779 sp<BasicClient> clientTmp = nullptr;
1780 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
1781 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001782 IInterface::asBinder(cameraCb), clientName8, oomScoreOffset, /*out*/&clientTmp,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001783 /*out*/&partial)) != NO_ERROR) {
1784 switch (err) {
1785 case -ENODEV:
1786 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1787 "No camera device with ID \"%s\" currently available",
1788 cameraId.string());
1789 case -EBUSY:
1790 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1791 "Higher-priority client using camera, ID \"%s\" currently unavailable",
1792 cameraId.string());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001793 case -EUSERS:
1794 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1795 "Too many cameras already open, cannot open camera \"%s\"",
1796 cameraId.string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001797 default:
1798 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1799 "Unexpected error %s (%d) opening camera \"%s\"",
1800 strerror(-err), err, cameraId.string());
1801 }
1802 }
1803
1804 if (clientTmp.get() != nullptr) {
1805 // Handle special case for API1 MediaRecorder where the existing client is returned
1806 device = static_cast<CLIENT*>(clientTmp.get());
1807 return ret;
1808 }
1809
1810 // give flashlight a chance to close devices if necessary.
1811 mFlashlight->prepareDeviceOpen(cameraId);
1812
Emilian Peevb91f1802021-03-23 14:50:28 -07001813 int deviceVersion = getDeviceVersion(cameraId, /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08001814 if (facing == -1) {
1815 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.string());
1816 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1817 "Unable to get camera device \"%s\" facing", cameraId.string());
1818 }
1819
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001820 sp<BasicClient> tmp = nullptr;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001821 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
1822 mPerfClassPrimaryCameraIds, cameraId.string(), targetSdkVersion);
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001823 if(!(ret = makeClient(this, cameraCb, clientPackageName, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07001824 cameraId, api1CameraId, facing, orientation,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001825 clientPid, clientUid, getpid(),
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001826 deviceVersion, effectiveApiLevel, overrideForPerfClass,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001827 /*out*/&tmp)).isOk()) {
1828 return ret;
1829 }
1830 client = static_cast<CLIENT*>(tmp.get());
1831
1832 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
1833 __FUNCTION__);
1834
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07001835 String8 monitorTags = isClientWatched(client.get()) ? mMonitorTags : String8("");
1836 err = client->initialize(mCameraProviderManager, monitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001837 if (err != OK) {
1838 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001839 // Errors could be from the HAL module open call or from AppOpsManager
1840 switch(err) {
1841 case BAD_VALUE:
1842 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1843 "Illegal argument to HAL module for camera \"%s\"", cameraId.string());
1844 case -EBUSY:
1845 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1846 "Camera \"%s\" is already open", cameraId.string());
1847 case -EUSERS:
1848 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1849 "Too many cameras already open, cannot open camera \"%s\"",
1850 cameraId.string());
1851 case PERMISSION_DENIED:
1852 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1853 "No permission to open camera \"%s\"", cameraId.string());
1854 case -EACCES:
1855 return STATUS_ERROR_FMT(ERROR_DISABLED,
1856 "Camera \"%s\" disabled by policy", cameraId.string());
1857 case -ENODEV:
1858 default:
1859 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1860 "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
1861 strerror(-err), err);
1862 }
1863 }
1864
1865 // Update shim paremeters for legacy clients
1866 if (effectiveApiLevel == API_1) {
1867 // Assume we have always received a Client subclass for API1
1868 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
1869 String8 rawParams = shimClient->getParameters();
1870 CameraParameters params(rawParams);
1871
1872 auto cameraState = getCameraState(cameraId);
1873 if (cameraState != nullptr) {
1874 cameraState->setShimParams(params);
1875 } else {
1876 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
1877 __FUNCTION__, cameraId.string());
1878 }
1879 }
1880
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001881 // Set rotate-and-crop override behavior
1882 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
1883 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
Emilian Peev5368ebf2021-10-08 17:52:18 -07001884 } else if (effectiveApiLevel == API_2) {
Emilian Peev065b2c12021-11-23 13:12:57 -08001885
1886 client->setRotateAndCropOverride(
1887 CameraServiceProxyWrapper::getRotateAndCropOverride(
1888 clientPackageName, facing, multiuser_get_user_id(clientUid)));
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001889 }
1890
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08001891 // Set camera muting behavior
Valentin Iftimec0b8d472021-07-23 20:21:06 +02001892 bool isCameraPrivacyEnabled =
1893 mSensorPrivacyPolicy->isCameraPrivacyEnabled(multiuser_get_user_id(clientUid));
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08001894 if (client->supportsCameraMute()) {
Valentin Iftimec0b8d472021-07-23 20:21:06 +02001895 client->setCameraMute(
1896 mOverrideCameraMuteMode || isCameraPrivacyEnabled);
1897 } else if (isCameraPrivacyEnabled) {
1898 // no camera mute supported, but privacy is on! => disconnect
1899 ALOGI("Camera mute not supported for package: %s, camera id: %s",
1900 String8(client->getPackageName()).string(), cameraId.string());
1901 // Do not hold mServiceLock while disconnecting clients, but
1902 // retain the condition blocking other clients from connecting
1903 // in mServiceLockWrapper if held.
1904 mServiceLock.unlock();
1905 // Clear caller identity temporarily so client disconnect PID
1906 // checks work correctly
1907 int64_t token = CameraThreadState::clearCallingIdentity();
1908 // Note AppOp to trigger the "Unblock" dialog
1909 client->noteAppOp();
1910 client->disconnect();
1911 CameraThreadState::restoreCallingIdentity(token);
1912 // Reacquire mServiceLock
1913 mServiceLock.lock();
1914
1915 return STATUS_ERROR_FMT(ERROR_DISABLED,
1916 "Camera \"%s\" disabled due to camera mute", cameraId.string());
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08001917 }
1918
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001919 if (shimUpdateOnly) {
1920 // If only updating legacy shim parameters, immediately disconnect client
1921 mServiceLock.unlock();
1922 client->disconnect();
1923 mServiceLock.lock();
1924 } else {
1925 // Otherwise, add client to active clients list
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001926 finishConnectLocked(client, partial, oomScoreOffset);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001927 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001928
1929 client->setImageDumpMask(mImageDumpMask);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001930 } // lock is destroyed, allow further connect calls
1931
1932 // Important: release the mutex here so the client can call back into the service from its
1933 // destructor (can be at the end of the call)
1934 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001935
1936 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
1937 CameraServiceProxyWrapper::logOpen(cameraId, facing, clientPackageName,
1938 effectiveApiLevel, isNdk, openLatencyMs);
1939
Cliff Wud3a05312021-04-26 23:07:31 +08001940 {
1941 Mutex::Autolock lock(mInjectionParametersLock);
1942 if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
1943 mInjectionInitPending = false;
1944 status_t res = NO_ERROR;
1945 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
1946 if (clientDescriptor != nullptr) {
Cliff Wu646bd612021-11-23 23:21:29 +08001947 sp<BasicClient> clientSp = clientDescriptor->getValue();
1948 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
1949 if(res != OK) {
1950 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1951 "No camera device with ID \"%s\" currently available",
1952 mInjectionExternalCamId.string());
1953 }
1954 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08001955 if (res != OK) {
1956 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
1957 }
1958 } else {
1959 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
1960 __FUNCTION__, mInjectionInternalCamId.string());
1961 res = NO_INIT;
1962 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
1963 }
1964 }
1965 }
1966
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001967 return ret;
1968}
1969
Emilian Peevb2bc5a42019-11-20 16:02:14 -08001970status_t CameraService::addOfflineClient(String8 cameraId, sp<BasicClient> offlineClient) {
1971 if (offlineClient.get() == nullptr) {
1972 return BAD_VALUE;
1973 }
1974
1975 {
1976 // Acquire mServiceLock and prevent other clients from connecting
1977 std::unique_ptr<AutoConditionLock> lock =
1978 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1979
1980 if (lock == nullptr) {
1981 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
1982 , __FUNCTION__, offlineClient->getClientPid());
1983 return TIMED_OUT;
1984 }
1985
1986 auto onlineClientDesc = mActiveClientManager.get(cameraId);
1987 if (onlineClientDesc.get() == nullptr) {
1988 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
1989 cameraId.c_str());
1990 return BAD_VALUE;
1991 }
1992
1993 // Offline clients do not evict or conflict with other online devices. Resource sharing
1994 // conflicts are handled by the camera provider which will either succeed or fail before
1995 // reaching this method.
1996 const auto& onlinePriority = onlineClientDesc->getPriority();
1997 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
1998 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
1999 /*conflictingKeys*/ std::set<String8>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002000 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
2001 /*ommScoreOffset*/ 0);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002002
2003 // Allow only one offline device per camera
2004 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
2005 if (!incompatibleClients.empty()) {
2006 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
2007 return BAD_VALUE;
2008 }
2009
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002010 String8 monitorTags = isClientWatched(offlineClient.get()) ? mMonitorTags : String8("");
2011 auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002012 if (err != OK) {
2013 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
2014 return err;
2015 }
2016
2017 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
2018 if (evicted.size() > 0) {
2019 for (auto& i : evicted) {
2020 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
2021 __FUNCTION__, i->getKey().string());
2022 }
2023
2024 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
2025 "properly", __FUNCTION__);
2026
2027 return BAD_VALUE;
2028 }
2029
2030 logConnectedOffline(offlineClientDesc->getKey(),
2031 static_cast<int>(offlineClientDesc->getOwnerId()),
2032 String8(offlineClient->getPackageName()));
2033
2034 sp<IBinder> remoteCallback = offlineClient->getRemote();
2035 if (remoteCallback != nullptr) {
2036 remoteCallback->linkToDeath(this);
2037 }
2038 } // lock is destroyed, allow further connect calls
2039
2040 return OK;
2041}
2042
Rucha Katakwar38284522021-11-10 11:25:21 -08002043Status CameraService::turnOnTorchWithStrengthLevel(const String16& cameraId, int32_t torchStrength,
2044 const sp<IBinder>& clientBinder) {
2045 Mutex::Autolock lock(mServiceLock);
2046
2047 ATRACE_CALL();
2048 if (clientBinder == nullptr) {
2049 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
2050 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2051 "Torch client binder in null.");
2052 }
2053
2054 String8 id = String8(cameraId.string());
2055 int uid = CameraThreadState::getCallingUid();
2056
2057 if (shouldRejectSystemCameraConnection(id)) {
2058 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to change the strength level"
2059 "for system only device %s: ", id.string());
2060 }
2061
2062 // verify id is valid
2063 auto state = getCameraState(id);
2064 if (state == nullptr) {
2065 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
2066 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2067 "Camera ID \"%s\" is a not valid camera ID", id.string());
2068 }
2069
2070 StatusInternal cameraStatus = state->getStatus();
2071 if (cameraStatus != StatusInternal::NOT_AVAILABLE &&
2072 cameraStatus != StatusInternal::PRESENT) {
2073 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(),
2074 (int)cameraStatus);
2075 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2076 "Camera ID \"%s\" is a not valid camera ID", id.string());
2077 }
2078
2079 {
2080 Mutex::Autolock al(mTorchStatusMutex);
2081 TorchModeStatus status;
2082 status_t err = getTorchStatusLocked(id, &status);
2083 if (err != OK) {
2084 if (err == NAME_NOT_FOUND) {
2085 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2086 "Camera \"%s\" does not have a flash unit", id.string());
2087 }
2088 ALOGE("%s: getting current torch status failed for camera %s",
2089 __FUNCTION__, id.string());
2090 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2091 "Error changing torch strength level for camera \"%s\": %s (%d)",
2092 id.string(), strerror(-err), err);
2093 }
2094
2095 if (status == TorchModeStatus::NOT_AVAILABLE) {
2096 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
2097 ALOGE("%s: torch mode of camera %s is not available because "
2098 "camera is in use.", __FUNCTION__, id.string());
2099 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2100 "Torch for camera \"%s\" is not available due to an existing camera user",
2101 id.string());
2102 } else {
2103 ALOGE("%s: torch mode of camera %s is not available due to "
2104 "insufficient resources", __FUNCTION__, id.string());
2105 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2106 "Torch for camera \"%s\" is not available due to insufficient resources",
2107 id.string());
2108 }
2109 }
2110 }
2111
2112 {
2113 Mutex::Autolock al(mTorchUidMapMutex);
2114 updateTorchUidMapLocked(cameraId, uid);
2115 }
2116 // Check if the current torch strength level is same as the new one.
2117 bool shouldSkipTorchStrengthUpdates = mCameraProviderManager->shouldSkipTorchStrengthUpdate(
2118 id.string(), torchStrength);
2119
2120 status_t err = mFlashlight->turnOnTorchWithStrengthLevel(id, torchStrength);
2121
2122 if (err != OK) {
2123 int32_t errorCode;
2124 String8 msg;
2125 switch (err) {
2126 case -ENOSYS:
2127 msg = String8::format("Camera \"%s\" has no flashlight.",
2128 id.string());
2129 errorCode = ERROR_ILLEGAL_ARGUMENT;
2130 break;
2131 case -EBUSY:
2132 msg = String8::format("Camera \"%s\" is in use",
2133 id.string());
2134 errorCode = ERROR_CAMERA_IN_USE;
2135 break;
2136 default:
2137 msg = String8::format("Changing torch strength level failed.");
2138 errorCode = ERROR_INVALID_OPERATION;
2139
2140 }
2141 ALOGE("%s: %s", __FUNCTION__, msg.string());
2142 return STATUS_ERROR(errorCode, msg.string());
2143 }
2144
2145 {
2146 // update the link to client's death
2147 // Store the last client that turns on each camera's torch mode.
2148 Mutex::Autolock al(mTorchClientMapMutex);
2149 ssize_t index = mTorchClientMap.indexOfKey(id);
2150 if (index == NAME_NOT_FOUND) {
2151 mTorchClientMap.add(id, clientBinder);
2152 } else {
2153 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
2154 mTorchClientMap.replaceValueAt(index, clientBinder);
2155 }
2156 clientBinder->linkToDeath(this);
2157 }
2158
2159 int clientPid = CameraThreadState::getCallingPid();
2160 const char *id_cstr = id.c_str();
2161 ALOGI("%s: Torch strength for camera id %s changed to %d for client PID %d",
2162 __FUNCTION__, id_cstr, torchStrength, clientPid);
2163 if (!shouldSkipTorchStrengthUpdates) {
2164 broadcastTorchStrengthLevel(id, torchStrength);
2165 }
2166 return Status::ok();
2167}
2168
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002169Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002170 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002171 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002172
2173 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07002174 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002175 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002176 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2177 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002178 }
2179
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002180 String8 id = String8(cameraId.string());
Jayant Chowdhary12361932018-08-27 14:46:13 -07002181 int uid = CameraThreadState::getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002182
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002183 if (shouldRejectSystemCameraConnection(id)) {
2184 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
2185 " for system only device %s: ", id.string());
2186 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002187 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08002188 auto state = getCameraState(id);
2189 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07002190 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002191 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2192 "Camera ID \"%s\" is a not valid camera ID", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08002193 }
2194
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002195 StatusInternal cameraStatus = state->getStatus();
2196 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002197 cameraStatus != StatusInternal::NOT_AVAILABLE) {
2198 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002199 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2200 "Camera ID \"%s\" is a not valid camera ID", id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002201 }
2202
2203 {
2204 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002205 TorchModeStatus status;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002206 status_t err = getTorchStatusLocked(id, &status);
2207 if (err != OK) {
2208 if (err == NAME_NOT_FOUND) {
2209 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2210 "Camera \"%s\" does not have a flash unit", id.string());
2211 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002212 ALOGE("%s: getting current torch status failed for camera %s",
2213 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002214 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2215 "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
2216 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002217 }
2218
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002219 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002220 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002221 ALOGE("%s: torch mode of camera %s is not available because "
2222 "camera is in use", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002223 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2224 "Torch for camera \"%s\" is not available due to an existing camera user",
2225 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002226 } else {
2227 ALOGE("%s: torch mode of camera %s is not available due to "
2228 "insufficient resources", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002229 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2230 "Torch for camera \"%s\" is not available due to insufficient resources",
2231 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002232 }
2233 }
2234 }
2235
Ruben Brunk99e69712015-05-26 17:25:07 -07002236 {
2237 // Update UID map - this is used in the torch status changed callbacks, so must be done
2238 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07002239 Mutex::Autolock al(mTorchUidMapMutex);
Rucha Katakwar38284522021-11-10 11:25:21 -08002240 updateTorchUidMapLocked(cameraId, uid);
Ruben Brunk99e69712015-05-26 17:25:07 -07002241 }
2242
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002243 status_t err = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07002244
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002245 if (err != OK) {
2246 int32_t errorCode;
2247 String8 msg;
2248 switch (err) {
2249 case -ENOSYS:
2250 msg = String8::format("Camera \"%s\" has no flashlight",
2251 id.string());
2252 errorCode = ERROR_ILLEGAL_ARGUMENT;
2253 break;
Dijack Dongc8a6f252021-09-17 16:21:16 +08002254 case -EBUSY:
2255 msg = String8::format("Camera \"%s\" is in use",
2256 id.string());
2257 errorCode = ERROR_CAMERA_IN_USE;
2258 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002259 default:
2260 msg = String8::format(
2261 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
2262 id.string(), enabled, strerror(-err), err);
2263 errorCode = ERROR_INVALID_OPERATION;
2264 }
2265 ALOGE("%s: %s", __FUNCTION__, msg.string());
Rucha Katakward9ea6452021-05-06 11:57:16 -07002266 logServiceError(msg,errorCode);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002267 return STATUS_ERROR(errorCode, msg.string());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002268 }
2269
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002270 {
2271 // update the link to client's death
2272 Mutex::Autolock al(mTorchClientMapMutex);
2273 ssize_t index = mTorchClientMap.indexOfKey(id);
2274 if (enabled) {
2275 if (index == NAME_NOT_FOUND) {
2276 mTorchClientMap.add(id, clientBinder);
2277 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07002278 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002279 mTorchClientMap.replaceValueAt(index, clientBinder);
2280 }
2281 clientBinder->linkToDeath(this);
2282 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07002283 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002284 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002285 }
2286
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002287 int clientPid = CameraThreadState::getCallingPid();
2288 const char *id_cstr = id.c_str();
2289 const char *torchState = enabled ? "on" : "off";
2290 ALOGI("Torch for camera id %s turned %s for client PID %d", id_cstr, torchState, clientPid);
2291 logTorchEvent(id_cstr, torchState , clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002292 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002293}
2294
Rucha Katakwar38284522021-11-10 11:25:21 -08002295void CameraService::updateTorchUidMapLocked(const String16& cameraId, int uid) {
2296 String8 id = String8(cameraId.string());
2297 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
2298 mTorchUidMap[id].first = uid;
2299 mTorchUidMap[id].second = uid;
2300 } else {
2301 // Set the pending UID
2302 mTorchUidMap[id].first = uid;
2303 }
2304}
2305
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002306Status CameraService::notifySystemEvent(int32_t eventId,
2307 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002308 const int pid = CameraThreadState::getCallingPid();
2309 const int selfPid = getpid();
2310
2311 // Permission checks
2312 if (pid != selfPid) {
2313 // Ensure we're being called by system_server, or similar process with
2314 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002315 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002316 const int uid = CameraThreadState::getCallingUid();
2317 ALOGE("Permission Denial: cannot send updates to camera service about system"
2318 " events from pid=%d, uid=%d", pid, uid);
2319 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09002320 "No permission to send updates to camera service about system events"
2321 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002322 }
2323 }
2324
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002325 ATRACE_CALL();
2326
Ruben Brunk36597b22015-03-20 22:15:57 -07002327 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002328 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08002329 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002330 // from a system server crash
2331 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08002332 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002333 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07002334 break;
2335 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002336 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07002337 default: {
2338 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
2339 eventId);
2340 break;
2341 }
2342 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002343 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002344}
2345
Emilian Peev53722fa2019-02-22 17:47:20 -08002346void CameraService::notifyMonitoredUids() {
2347 Mutex::Autolock lock(mStatusListenerLock);
2348
2349 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002350 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Emilian Peev53722fa2019-02-22 17:47:20 -08002351 if (!ret.isOk()) {
2352 ALOGE("%s: Failed to trigger permission callback: %d", __FUNCTION__,
2353 ret.exceptionCode());
2354 }
2355 }
2356}
2357
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002358Status CameraService::notifyDeviceStateChange(int64_t newState) {
2359 const int pid = CameraThreadState::getCallingPid();
2360 const int selfPid = getpid();
2361
2362 // Permission checks
2363 if (pid != selfPid) {
2364 // Ensure we're being called by system_server, or similar process with
2365 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002366 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002367 const int uid = CameraThreadState::getCallingUid();
2368 ALOGE("Permission Denial: cannot send updates to camera service about device"
2369 " state changes from pid=%d, uid=%d", pid, uid);
2370 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2371 "No permission to send updates to camera service about device state"
2372 " changes from pid=%d, uid=%d", pid, uid);
2373 }
2374 }
2375
2376 ATRACE_CALL();
2377
2378 using hardware::camera::provider::V2_5::DeviceState;
2379 hardware::hidl_bitfield<DeviceState> newDeviceState{};
2380 if (newState & ICameraService::DEVICE_STATE_BACK_COVERED) {
2381 newDeviceState |= DeviceState::BACK_COVERED;
2382 }
2383 if (newState & ICameraService::DEVICE_STATE_FRONT_COVERED) {
2384 newDeviceState |= DeviceState::FRONT_COVERED;
2385 }
2386 if (newState & ICameraService::DEVICE_STATE_FOLDED) {
2387 newDeviceState |= DeviceState::FOLDED;
2388 }
2389 // Only map vendor bits directly
2390 uint64_t vendorBits = static_cast<uint64_t>(newState) & 0xFFFFFFFF00000000l;
2391 newDeviceState |= vendorBits;
2392
2393 ALOGV("%s: New device state 0x%" PRIx64, __FUNCTION__, newDeviceState);
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002394 mCameraProviderManager->notifyDeviceStateChange(newDeviceState);
2395
2396 return Status::ok();
2397}
2398
Emilian Peev8b64f282021-03-25 16:49:57 -07002399Status CameraService::notifyDisplayConfigurationChange() {
2400 ATRACE_CALL();
2401 const int callingPid = CameraThreadState::getCallingPid();
2402 const int selfPid = getpid();
2403
2404 // Permission checks
2405 if (callingPid != selfPid) {
2406 // Ensure we're being called by system_server, or similar process with
2407 // permissions to notify the camera service about system events
2408 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
2409 const int uid = CameraThreadState::getCallingUid();
2410 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
2411 " changes from pid=%d, uid=%d", callingPid, uid);
2412 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2413 "No permission to send updates to camera service about orientation"
2414 " changes from pid=%d, uid=%d", callingPid, uid);
2415 }
2416 }
2417
2418 Mutex::Autolock lock(mServiceLock);
2419
2420 // Don't do anything if rotate-and-crop override via cmd is active
2421 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
2422
2423 const auto clients = mActiveClientManager.getAll();
2424 for (auto& current : clients) {
2425 if (current != nullptr) {
2426 const auto basicClient = current->getValue();
Emilian Peeve23f1d92021-09-20 14:56:01 -07002427 if (basicClient.get() != nullptr && basicClient->canCastToApiClient(API_2)) {
Emilian Peev065b2c12021-11-23 13:12:57 -08002428 basicClient->setRotateAndCropOverride(
2429 CameraServiceProxyWrapper::getRotateAndCropOverride(
2430 basicClient->getPackageName(),
2431 basicClient->getCameraFacing(),
2432 multiuser_get_user_id(basicClient->getClientUid())));
Emilian Peev8b64f282021-03-25 16:49:57 -07002433 }
2434 }
2435 }
2436
2437 return Status::ok();
2438}
2439
2440Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002441 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
2442 ATRACE_CALL();
2443 if (!concurrentCameraIds) {
2444 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
2445 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
2446 }
2447
2448 if (!mInitialized) {
2449 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Rucha Katakward9ea6452021-05-06 11:57:16 -07002450 logServiceError(String8::format("Camera subsystem is not available"),ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002451 return STATUS_ERROR(ERROR_DISCONNECTED,
2452 "Camera subsystem is not available");
2453 }
2454 // First call into the provider and get the set of concurrent camera
2455 // combinations
2456 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07002457 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002458 for (auto &combination : concurrentCameraCombinations) {
2459 std::vector<std::string> validCombination;
2460 for (auto &cameraId : combination) {
2461 // if the camera state is not present, skip
2462 String8 cameraIdStr(cameraId.c_str());
2463 auto state = getCameraState(cameraIdStr);
2464 if (state == nullptr) {
2465 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
2466 continue;
2467 }
2468 StatusInternal status = state->getStatus();
2469 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
2470 continue;
2471 }
2472 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
2473 continue;
2474 }
2475 validCombination.push_back(cameraId);
2476 }
2477 if (validCombination.size() != 0) {
2478 concurrentCameraIds->push_back(std::move(validCombination));
2479 }
2480 }
2481 return Status::ok();
2482}
2483
2484Status CameraService::isConcurrentSessionConfigurationSupported(
2485 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002486 int targetSdkVersion, /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002487 if (!isSupported) {
2488 ALOGE("%s: isSupported is NULL", __FUNCTION__);
2489 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
2490 }
2491
2492 if (!mInitialized) {
2493 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2494 return STATUS_ERROR(ERROR_DISCONNECTED,
2495 "Camera subsystem is not available");
2496 }
2497
2498 // Check for camera permissions
2499 int callingPid = CameraThreadState::getCallingPid();
2500 int callingUid = CameraThreadState::getCallingUid();
2501 if ((callingPid != getpid()) && !checkPermission(sCameraPermission, callingPid, callingUid)) {
2502 ALOGE("%s: pid %d doesn't have camera permissions", __FUNCTION__, callingPid);
2503 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2504 "android.permission.CAMERA needed to call"
2505 "isConcurrentSessionConfigurationSupported");
2506 }
2507
2508 status_t res =
2509 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002510 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
2511 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002512 if (res != OK) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07002513 logServiceError(String8::format("Unable to query session configuration support"),
2514 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002515 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
2516 "support %s (%d)", strerror(-res), res);
2517 }
2518 return Status::ok();
2519}
2520
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002521Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
2522 /*out*/
2523 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002524 return addListenerHelper(listener, cameraStatuses);
2525}
2526
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002527binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
2528 std::vector<hardware::CameraStatus>* cameraStatuses) {
2529 return addListenerHelper(listener, cameraStatuses, false, true);
2530}
2531
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002532Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
2533 /*out*/
2534 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002535 bool isVendorListener, bool isProcessLocalTest) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002536
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002537 ATRACE_CALL();
2538
Igor Murashkinbfc99152013-02-27 12:55:20 -08002539 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08002540
Ruben Brunk3450ba72015-06-16 11:00:37 -07002541 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002542 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002543 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002544 }
2545
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002546 auto clientUid = CameraThreadState::getCallingUid();
2547 auto clientPid = CameraThreadState::getCallingPid();
Shuzhen Wang695044d2020-03-06 09:02:23 -08002548 bool openCloseCallbackAllowed = checkPermission(sCameraOpenCloseListenerPermission,
Jayant Chowdharyc3198c32021-07-28 20:59:14 +00002549 clientPid, clientUid, /*logPermissionFailure*/false);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002550
Igor Murashkinbfc99152013-02-27 12:55:20 -08002551 Mutex::Autolock lock(mServiceLock);
2552
Ruben Brunkcc776712015-02-17 20:18:47 -08002553 {
2554 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08002555 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002556 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002557 ALOGW("%s: Tried to add listener %p which was already subscribed",
2558 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002559 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08002560 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002561 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002562
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002563 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08002564 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
2565 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002566 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08002567 if (ret != NO_ERROR) {
2568 String8 msg = String8::format("Failed to initialize service listener: %s (%d)",
2569 strerror(-ret), ret);
Rucha Katakward9ea6452021-05-06 11:57:16 -07002570 logServiceError(msg,ERROR_ILLEGAL_ARGUMENT);
Emilian Peev53722fa2019-02-22 17:47:20 -08002571 ALOGE("%s: %s", __FUNCTION__, msg.string());
2572 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
2573 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002574 // The listener still needs to be added to the list of listeners, regardless of what
2575 // permissions the listener process has / whether it is a vendor listener. Since it might be
2576 // eligible to listen to other camera ids.
2577 mListenerList.emplace_back(serviceListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08002578 mUidPolicy->registerMonitorUid(clientUid);
Igor Murashkinbfc99152013-02-27 12:55:20 -08002579 }
2580
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002581 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07002582 {
Ruben Brunkcc776712015-02-17 20:18:47 -08002583 Mutex::Autolock lock(mCameraStatesLock);
2584 for (auto& i : mCameraStates) {
Shuzhen Wang43858162020-01-10 13:42:15 -08002585 cameraStatuses->emplace_back(i.first,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07002586 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
2587 openCloseCallbackAllowed ? i.second->getClientPackage() : String8::empty());
Igor Murashkincba2c162013-03-20 15:56:31 -07002588 }
2589 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002590 // Remove the camera statuses that should be hidden from the client, we do
2591 // this after collecting the states in order to avoid holding
2592 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
2593 // the same time.
2594 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
2595 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
2596 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
2597 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
2598 ALOGE("%s: Invalid camera id %s, skipping status update",
2599 __FUNCTION__, s.cameraId.c_str());
2600 return true;
2601 }
2602 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
2603 clientUid);}), cameraStatuses->end());
2604
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002605 //cameraStatuses will have non-eligible camera ids removed.
2606 std::set<String16> idsChosenForCallback;
2607 for (const auto &s : *cameraStatuses) {
2608 idsChosenForCallback.insert(String16(s.cameraId));
2609 }
Igor Murashkincba2c162013-03-20 15:56:31 -07002610
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002611 /*
2612 * Immediately signal current torch status to this listener only
2613 * This may be a subset of all the devices, so don't include it in the response directly
2614 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002615 {
2616 Mutex::Autolock al(mTorchStatusMutex);
2617 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002618 String16 id = String16(mTorchStatusMap.keyAt(i).string());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002619 // The camera id is visible to the client. Fine to send torch
2620 // callback.
2621 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
2622 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
2623 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002624 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002625 }
2626
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002627 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08002628}
Ruben Brunkcc776712015-02-17 20:18:47 -08002629
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002630Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002631 ATRACE_CALL();
2632
Igor Murashkinbfc99152013-02-27 12:55:20 -08002633 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
2634
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002635 if (listener == 0) {
2636 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002637 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002638 }
2639
Igor Murashkinbfc99152013-02-27 12:55:20 -08002640 Mutex::Autolock lock(mServiceLock);
2641
Ruben Brunkcc776712015-02-17 20:18:47 -08002642 {
2643 Mutex::Autolock lock(mStatusListenerLock);
2644 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002645 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
2646 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid());
2647 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08002648 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002649 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002650 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002651 }
2652 }
2653
2654 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
2655 __FUNCTION__, listener.get());
2656
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002657 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08002658}
2659
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002660Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002661
2662 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002663 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
2664
2665 if (parameters == NULL) {
2666 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002667 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07002668 }
2669
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002670 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002671
2672 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002673 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07002674 // Error logged by caller
2675 return ret;
2676 }
2677
2678 String8 shimParamsString8 = shimParams.flatten();
2679 String16 shimParamsString16 = String16(shimParamsString8);
2680
2681 *parameters = shimParamsString16;
2682
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002683 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07002684}
2685
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002686Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
2687 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002688 ATRACE_CALL();
2689
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002690 const String8 id = String8(cameraId);
2691
2692 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002693
2694 switch (apiVersion) {
2695 case API_VERSION_1:
2696 case API_VERSION_2:
2697 break;
2698 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002699 String8 msg = String8::format("Unknown API version %d", apiVersion);
2700 ALOGE("%s: %s", __FUNCTION__, msg.string());
2701 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002702 }
2703
Emilian Peev28ad2ea2017-02-07 16:14:32 +00002704 int deviceVersion = getDeviceVersion(id);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002705 switch (deviceVersion) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002706 case CAMERA_DEVICE_API_VERSION_1_0:
2707 case CAMERA_DEVICE_API_VERSION_3_0:
2708 case CAMERA_DEVICE_API_VERSION_3_1:
2709 if (apiVersion == API_VERSION_2) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002710 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without shim",
2711 __FUNCTION__, id.string(), deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002712 *isSupported = false;
2713 } else { // if (apiVersion == API_VERSION_1) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002714 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always supported",
2715 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002716 *isSupported = true;
2717 }
2718 break;
2719 case CAMERA_DEVICE_API_VERSION_3_2:
2720 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -07002721 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002722 case CAMERA_DEVICE_API_VERSION_3_5:
Yin-Chia Yeh56d98ba2020-01-16 16:57:14 -08002723 case CAMERA_DEVICE_API_VERSION_3_6:
Shuzhen Wang83bff122020-11-20 15:51:39 -08002724 case CAMERA_DEVICE_API_VERSION_3_7:
Shuzhen Wang90708ea2021-11-04 11:40:49 -07002725 case CAMERA_DEVICE_API_VERSION_3_8:
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002726 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
2727 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002728 *isSupported = true;
2729 break;
2730 case -1: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002731 String8 msg = String8::format("Unknown camera ID %s", id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002732 ALOGE("%s: %s", __FUNCTION__, msg.string());
2733 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002734 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002735 default: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002736 String8 msg = String8::format("Unknown device version %x for device %s",
2737 deviceVersion, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002738 ALOGE("%s: %s", __FUNCTION__, msg.string());
2739 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
2740 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07002741 }
2742
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002743 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002744}
2745
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002746Status CameraService::isHiddenPhysicalCamera(const String16& cameraId,
2747 /*out*/ bool *isSupported) {
2748 ATRACE_CALL();
2749
2750 const String8 id = String8(cameraId);
2751
2752 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
2753 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(id.string());
2754
2755 return Status::ok();
2756}
2757
Cliff Wud8cae102021-03-11 01:37:42 +08002758Status CameraService::injectCamera(
2759 const String16& packageName, const String16& internalCamId,
2760 const String16& externalCamId,
2761 const sp<ICameraInjectionCallback>& callback,
2762 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08002763 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08002764 ATRACE_CALL();
2765
2766 if (!checkCallingPermission(sCameraInjectExternalCameraPermission)) {
2767 const int pid = CameraThreadState::getCallingPid();
2768 const int uid = CameraThreadState::getCallingUid();
2769 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
2770 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2771 "Permission Denial: no permission to inject camera");
2772 }
2773
2774 ALOGV(
2775 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
2776 "%s",
2777 __FUNCTION__, String8(packageName).string(),
2778 String8(internalCamId).string(), String8(externalCamId).string());
2779
Cliff Wud3a05312021-04-26 23:07:31 +08002780 {
2781 Mutex::Autolock lock(mInjectionParametersLock);
2782 mInjectionInternalCamId = String8(internalCamId);
2783 mInjectionExternalCamId = String8(externalCamId);
Cliff Wu646bd612021-11-23 23:21:29 +08002784 mInjectionStatusListener->addListener(callback);
2785 *cameraInjectionSession = new CameraInjectionSession(this);
Cliff Wud3a05312021-04-26 23:07:31 +08002786 status_t res = NO_ERROR;
2787 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2788 // If the client already exists, we can directly connect to the camera device through the
2789 // client's injectCamera(), otherwise we need to wait until the client is established
2790 // (execute connectHelper()) before injecting the camera to the camera device.
2791 if (clientDescriptor != nullptr) {
2792 mInjectionInitPending = false;
Cliff Wu646bd612021-11-23 23:21:29 +08002793 sp<BasicClient> clientSp = clientDescriptor->getValue();
2794 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2795 if(res != OK) {
2796 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2797 "No camera device with ID \"%s\" currently available",
2798 mInjectionExternalCamId.string());
2799 }
2800 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08002801 if(res != OK) {
2802 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2803 }
2804 } else {
2805 mInjectionInitPending = true;
2806 }
2807 }
Cliff Wud8cae102021-03-11 01:37:42 +08002808
Cliff Wud3a05312021-04-26 23:07:31 +08002809 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08002810}
2811
Ruben Brunkcc776712015-02-17 20:18:47 -08002812void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002813 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002814 for (auto& i : mActiveClientManager.getAll()) {
2815 auto clientSp = i->getValue();
2816 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002817 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08002818 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08002819 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07002820 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002821 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08002822}
2823
Ruben Brunkcc776712015-02-17 20:18:47 -08002824bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002825 bool ret = false;
2826 {
2827 // Acquire mServiceLock and prevent other clients from connecting
2828 std::unique_ptr<AutoConditionLock> lock =
2829 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08002830
Igor Murashkin634a5152013-02-20 17:15:11 -08002831
Ruben Brunkcc776712015-02-17 20:18:47 -08002832 std::vector<sp<BasicClient>> evicted;
2833 for (auto& i : mActiveClientManager.getAll()) {
2834 auto clientSp = i->getValue();
2835 if (clientSp.get() == nullptr) {
2836 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2837 mActiveClientManager.remove(i);
2838 continue;
2839 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08002840 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002841 mActiveClientManager.remove(i);
2842 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08002843
Ruben Brunkcc776712015-02-17 20:18:47 -08002844 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002845 clientSp->notifyError(
2846 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002847 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08002848 }
2849 }
2850
Ruben Brunkcc776712015-02-17 20:18:47 -08002851 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2852 // other clients from connecting in mServiceLockWrapper if held
2853 mServiceLock.unlock();
2854
Ruben Brunk36597b22015-03-20 22:15:57 -07002855 // Do not clear caller identity, remote caller should be client proccess
2856
Ruben Brunkcc776712015-02-17 20:18:47 -08002857 for (auto& i : evicted) {
2858 if (i.get() != nullptr) {
2859 i->disconnect();
2860 ret = true;
2861 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002862 }
2863
Ruben Brunkcc776712015-02-17 20:18:47 -08002864 // Reacquire mServiceLock
2865 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08002866
Ruben Brunkcc776712015-02-17 20:18:47 -08002867 } // lock is destroyed, allow further connect calls
2868
2869 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07002870}
2871
Ruben Brunkcc776712015-02-17 20:18:47 -08002872std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
2873 const String8& cameraId) const {
2874 std::shared_ptr<CameraState> state;
2875 {
2876 Mutex::Autolock lock(mCameraStatesLock);
2877 auto iter = mCameraStates.find(cameraId);
2878 if (iter != mCameraStates.end()) {
2879 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002880 }
2881 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002882 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002883}
2884
Ruben Brunkcc776712015-02-17 20:18:47 -08002885sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
2886 // Remove from active clients list
2887 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
2888 if (clientDescriptorPtr == nullptr) {
2889 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
2890 cameraId.string());
2891 return sp<BasicClient>{nullptr};
2892 }
2893
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002894 sp<BasicClient> client = clientDescriptorPtr->getValue();
2895 if (client.get() != nullptr) {
2896 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
2897 }
2898 return client;
Keun young Parkd8973a72012-03-28 14:13:09 -07002899}
2900
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002901void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07002902 // Acquire mServiceLock and prevent other clients from connecting
2903 std::unique_ptr<AutoConditionLock> lock =
2904 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
2905
Ruben Brunk6267b532015-04-30 17:44:07 -07002906 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002907 for (size_t i = 0; i < newUserIds.size(); i++) {
2908 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07002909 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002910 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07002911 return;
2912 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002913 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07002914 }
2915
Ruben Brunka8ca9152015-04-07 14:23:40 -07002916
Ruben Brunk6267b532015-04-30 17:44:07 -07002917 if (newAllowedUsers == mAllowedUsers) {
2918 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
2919 return;
2920 }
2921
2922 logUserSwitch(mAllowedUsers, newAllowedUsers);
2923
2924 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07002925
2926 // Current user has switched, evict all current clients.
2927 std::vector<sp<BasicClient>> evicted;
2928 for (auto& i : mActiveClientManager.getAll()) {
2929 auto clientSp = i->getValue();
2930
2931 if (clientSp.get() == nullptr) {
2932 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2933 continue;
2934 }
2935
Ruben Brunk6267b532015-04-30 17:44:07 -07002936 // Don't evict clients that are still allowed.
2937 uid_t clientUid = clientSp->getClientUid();
2938 userid_t clientUserId = multiuser_get_user_id(clientUid);
2939 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
2940 continue;
2941 }
2942
Ruben Brunk36597b22015-03-20 22:15:57 -07002943 evicted.push_back(clientSp);
2944
2945 String8 curTime = getFormattedCurrentTime();
2946
2947 ALOGE("Evicting conflicting client for camera ID %s due to user change",
2948 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07002949
Ruben Brunk36597b22015-03-20 22:15:57 -07002950 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002951 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00002952 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
2953 " to user switch.", i->getKey().string(),
2954 String8{clientSp->getPackageName()}.string(),
2955 i->getOwnerId(), i->getPriority().getScore(),
2956 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07002957
2958 }
2959
2960 // Do not hold mServiceLock while disconnecting clients, but retain the condition
2961 // blocking other clients from connecting in mServiceLockWrapper if held.
2962 mServiceLock.unlock();
2963
2964 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07002965 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07002966
2967 for (auto& i : evicted) {
2968 i->disconnect();
2969 }
2970
Jayant Chowdhary12361932018-08-27 14:46:13 -07002971 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07002972
2973 // Reacquire mServiceLock
2974 mServiceLock.lock();
2975}
Ruben Brunkcc776712015-02-17 20:18:47 -08002976
Ruben Brunka8ca9152015-04-07 14:23:40 -07002977void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002978 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07002979 Mutex::Autolock l(mLogLock);
Rucha Katakward9ea6452021-05-06 11:57:16 -07002980 String8 msg = String8::format("%s : %s", curTime.string(), event);
2981 // For service error events, print the msg only once.
2982 if(!msg.contains("SERVICE ERROR")) {
2983 mEventLog.add(msg);
2984 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
2985 // Error event not added to the dumpsys log before
2986 mEventLog.add(msg);
2987 sServiceErrorEventSet.insert(msg);
2988 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002989}
2990
Ruben Brunka8ca9152015-04-07 14:23:40 -07002991void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002992 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002993 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002994 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002995 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002996}
2997
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002998void CameraService::logDisconnectedOffline(const char* cameraId, int clientPid,
2999 const char* clientPackage) {
3000 // Log the clients evicted
3001 logEvent(String8::format("DISCONNECT offline device %s client for package %s (PID %d)",
3002 cameraId, clientPackage, clientPid));
3003}
3004
Ruben Brunka8ca9152015-04-07 14:23:40 -07003005void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003006 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003007 // Log the clients evicted
3008 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003009 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003010}
3011
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003012void CameraService::logConnectedOffline(const char* cameraId, int clientPid,
3013 const char* clientPackage) {
3014 // Log the clients evicted
3015 logEvent(String8::format("CONNECT offline device %s client for package %s (PID %d)", cameraId,
3016 clientPackage, clientPid));
3017}
3018
Ruben Brunka8ca9152015-04-07 14:23:40 -07003019void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003020 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003021 // Log the client rejected
3022 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003023 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003024}
3025
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003026void CameraService::logTorchEvent(const char* cameraId, const char *torchState, int clientPid) {
3027 // Log torch event
3028 logEvent(String8::format("Torch for camera id %s turned %s for client PID %d", cameraId,
3029 torchState, clientPid));
3030}
3031
Ruben Brunk6267b532015-04-30 17:44:07 -07003032void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
3033 const std::set<userid_t>& newUserIds) {
3034 String8 newUsers = toString(newUserIds);
3035 String8 oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003036 if (oldUsers.size() == 0) {
3037 oldUsers = "<None>";
3038 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07003039 // Log the new and old users
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003040 logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
Ruben Brunk6267b532015-04-30 17:44:07 -07003041 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003042}
3043
3044void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
3045 // Log the device removal
3046 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
3047}
3048
3049void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
3050 // Log the device removal
3051 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
3052}
3053
3054void CameraService::logClientDied(int clientPid, const char* reason) {
3055 // Log the device removal
3056 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07003057}
3058
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003059void CameraService::logServiceError(const char* msg, int errorCode) {
3060 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08003061 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003062}
3063
Ruben Brunk36597b22015-03-20 22:15:57 -07003064status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
3065 uint32_t flags) {
3066
Mathias Agopian65ab4712010-07-14 17:59:35 -07003067 // Permission checks
3068 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003069 case SHELL_COMMAND_TRANSACTION: {
3070 int in = data.readFileDescriptor();
3071 int out = data.readFileDescriptor();
3072 int err = data.readFileDescriptor();
3073 int argc = data.readInt32();
3074 Vector<String16> args;
3075 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
3076 args.add(data.readString16());
3077 }
3078 sp<IBinder> unusedCallback;
3079 sp<IResultReceiver> resultReceiver;
3080 status_t status;
3081 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
3082 return status;
3083 }
3084 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
3085 return status;
3086 }
3087 status = shellCommand(in, out, err, args);
3088 if (resultReceiver != nullptr) {
3089 resultReceiver->send(status);
3090 }
3091 return NO_ERROR;
3092 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003093 }
3094
3095 return BnCameraService::onTransact(code, data, reply, flags);
3096}
3097
Mathias Agopian65ab4712010-07-14 17:59:35 -07003098// We share the media players for shutter and recording sound for all clients.
3099// A reference count is kept to determine when we will actually release the
3100// media players.
3101
Jaekyun Seokef498052018-03-23 13:09:44 +09003102sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
3103 sp<MediaPlayer> mp = new MediaPlayer();
3104 status_t error;
3105 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08003106 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09003107 error = mp->prepare();
3108 }
3109 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00003110 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09003111 mp->disconnect();
3112 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003113 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003114 }
3115 return mp;
3116}
3117
username5755fea2018-12-27 09:48:08 +08003118void CameraService::increaseSoundRef() {
3119 Mutex::Autolock lock(mSoundLock);
3120 mSoundRef++;
3121}
3122
3123void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003124 ATRACE_CALL();
3125
username5755fea2018-12-27 09:48:08 +08003126 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
3127 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
3128 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
3129 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
3130 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
3131 }
3132 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
3133 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
3134 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
3135 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003136 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08003137 }
3138 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
3139 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
3140 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
3141 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
3142 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003143 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003144}
3145
username5755fea2018-12-27 09:48:08 +08003146void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003147 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08003148 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003149 if (--mSoundRef) return;
3150
3151 for (int i = 0; i < NUM_SOUNDS; i++) {
3152 if (mSoundPlayer[i] != 0) {
3153 mSoundPlayer[i]->disconnect();
3154 mSoundPlayer[i].clear();
3155 }
3156 }
3157}
3158
3159void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003160 ATRACE_CALL();
3161
Mathias Agopian65ab4712010-07-14 17:59:35 -07003162 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07003163 if (kind < 0 || kind >= NUM_SOUNDS) {
3164 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
3165 return;
3166 }
3167
Mathias Agopian65ab4712010-07-14 17:59:35 -07003168 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08003169 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003170 sp<MediaPlayer> player = mSoundPlayer[kind];
3171 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08003172 player->seekTo(0);
3173 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003174 }
3175}
3176
3177// ----------------------------------------------------------------------------
3178
3179CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07003180 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003181 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09003182 const std::optional<String16>& clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003183 const String8& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07003184 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003185 int clientPid, uid_t clientUid,
3186 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08003187 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08003188 IInterface::asBinder(cameraClient),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08003189 clientPackageName, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07003190 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003191 clientPid, clientUid,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003192 servicePid),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003193 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08003194{
Jayant Chowdhary12361932018-08-27 14:46:13 -07003195 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003196 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003197
Igor Murashkin44cfcf02013-03-01 16:22:28 -08003198 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003199
username5755fea2018-12-27 09:48:08 +08003200 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003201
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003202 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003203}
3204
Mathias Agopian65ab4712010-07-14 17:59:35 -07003205// tear down the client
3206CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003207 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08003208 mDestructionStarted = true;
3209
username5755fea2018-12-27 09:48:08 +08003210 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003211 // unconditionally disconnect. function is idempotent
3212 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003213}
3214
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003215sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
3216
Igor Murashkin634a5152013-02-20 17:15:11 -08003217CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003218 const sp<IBinder>& remoteCallback,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09003219 const String16& clientPackageName, const std::optional<String16>& clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07003220 const String8& cameraIdStr, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003221 int clientPid, uid_t clientUid,
3222 int servicePid):
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003223 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07003224 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09003225 mClientPackageName(clientPackageName), mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08003226 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003227 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07003228 mDisconnected(false), mUidIsTrusted(false),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003229 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003230 mRemoteBinder(remoteCallback),
3231 mOpsActive(false),
3232 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08003233{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003234 if (sCameraService == nullptr) {
3235 sCameraService = cameraService;
3236 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08003237
3238 // In some cases the calling code has no access to the package it runs under.
3239 // For example, NDK camera API.
3240 // In this case we will get the packages for the calling UID and pick the first one
3241 // for attributing the app op. This will work correctly for runtime permissions
3242 // as for legacy apps we will toggle the app op for all packages in the UID.
3243 // The caveat is that the operation may be attributed to the wrong package and
3244 // stats based on app ops may be slightly off.
3245 if (mClientPackageName.size() <= 0) {
3246 sp<IServiceManager> sm = defaultServiceManager();
3247 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
3248 if (binder == 0) {
3249 ALOGE("Cannot get permission service");
3250 // Leave mClientPackageName unchanged (empty) and the further interaction
3251 // with camera will fail in BasicClient::startCameraOps
3252 return;
3253 }
3254
3255 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
3256 Vector<String16> packages;
3257
3258 permCtrl->getPackagesForUid(mClientUid, packages);
3259
3260 if (packages.isEmpty()) {
3261 ALOGE("No packages for calling UID");
3262 // Leave mClientPackageName unchanged (empty) and the further interaction
3263 // with camera will fail in BasicClient::startCameraOps
3264 return;
3265 }
3266 mClientPackageName = packages[0];
3267 }
Steven Moreland89a2c5c2020-01-31 15:02:25 -08003268 if (getCurrentServingCall() != BinderCallType::HWBINDER) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003269 mAppOpsManager = std::make_unique<AppOpsManager>();
3270 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07003271
3272 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08003273}
3274
3275CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003276 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08003277 mDestructionStarted = true;
3278}
3279
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003280binder::Status CameraService::BasicClient::disconnect() {
3281 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003282 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003283 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07003284 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07003285 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08003286
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003287 sCameraService->removeByClient(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003288 sCameraService->logDisconnected(mCameraIdStr, mClientPid, String8(mClientPackageName));
Peter Kalauskasa29c1352018-10-10 12:05:42 -07003289 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
3290 mCameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003291
3292 sp<IBinder> remote = getRemote();
3293 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003294 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08003295 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003296
3297 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07003298 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003299 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
3300 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
3301 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003302
Igor Murashkincba2c162013-03-20 15:56:31 -07003303 // client shouldn't be able to call into us anymore
3304 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003305
3306 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08003307}
3308
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08003309status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
3310 // No dumping of clients directly over Binder,
3311 // must go through CameraService::dump
3312 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07003313 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08003314 return OK;
3315}
3316
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07003317status_t CameraService::BasicClient::startWatchingTags(const String8&, int) {
3318 // Can't watch tags directly, must go through CameraService::startWatchingTags
3319 return OK;
3320}
3321
3322status_t CameraService::BasicClient::stopWatchingTags(int) {
3323 // Can't watch tags directly, must go through CameraService::stopWatchingTags
3324 return OK;
3325}
3326
3327status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
3328 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
3329 return OK;
3330}
3331
Ruben Brunkcc776712015-02-17 20:18:47 -08003332String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003333 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08003334}
3335
Emilian Peev8b64f282021-03-25 16:49:57 -07003336int CameraService::BasicClient::getCameraFacing() const {
3337 return mCameraFacing;
3338}
3339
3340int CameraService::BasicClient::getCameraOrientation() const {
3341 return mOrientation;
3342}
Ruben Brunkcc776712015-02-17 20:18:47 -08003343
3344int CameraService::BasicClient::getClientPid() const {
3345 return mClientPid;
3346}
3347
Ruben Brunk6267b532015-04-30 17:44:07 -07003348uid_t CameraService::BasicClient::getClientUid() const {
3349 return mClientUid;
3350}
3351
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003352bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
3353 // Defaults to API2.
3354 return level == API_2;
3355}
3356
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07003357status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003358 {
3359 Mutex::Autolock l(mAudioRestrictionLock);
3360 mAudioRestriction = mode;
3361 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07003362 sCameraService->updateAudioRestriction();
3363 return OK;
3364}
3365
3366int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003367 return sCameraService->updateAudioRestriction();
3368}
3369
3370int32_t CameraService::BasicClient::getAudioRestriction() const {
3371 Mutex::Autolock l(mAudioRestrictionLock);
3372 return mAudioRestriction;
3373}
3374
3375bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
3376 switch (mode) {
3377 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
3378 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
3379 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
3380 return true;
3381 default:
3382 return false;
3383 }
3384}
3385
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003386status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
3387 if (mode == AppOpsManager::MODE_ERRORED) {
3388 ALOGI("Camera %s: Access for \"%s\" has been revoked",
3389 mCameraIdStr.string(), String8(mClientPackageName).string());
3390 return PERMISSION_DENIED;
3391 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
3392 // If the calling Uid is trusted (a native service), the AppOpsManager could
3393 // return MODE_IGNORED. Do not treat such case as error.
3394 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
3395 mClientPackageName);
3396 bool isCameraPrivacyEnabled =
3397 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled(
3398 multiuser_get_user_id(mClientUid));
3399 if (!isUidActive || !isCameraPrivacyEnabled) {
3400 ALOGI("Camera %s: Access for \"%s\" has been restricted",
3401 mCameraIdStr.string(), String8(mClientPackageName).string());
3402 // Return the same error as for device policy manager rejection
3403 return -EACCES;
3404 }
3405 }
3406 return OK;
3407}
3408
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003409status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003410 ATRACE_CALL();
3411
Igor Murashkine6800ce2013-03-04 17:25:57 -08003412 {
3413 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003414 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08003415 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003416 if (mAppOpsManager != nullptr) {
3417 // Notify app ops that the camera is not available
3418 mOpsCallback = new OpsCallback(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003419 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
3420 mClientPackageName, mOpsCallback);
Igor Murashkine6800ce2013-03-04 17:25:57 -08003421
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003422 // Just check for camera acccess here on open - delay startOp until
3423 // camera frames start streaming in startCameraStreamingOps
3424 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
3425 mClientPackageName);
3426 status_t res = handleAppOpMode(mode);
3427 if (res != OK) {
3428 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003429 }
Svetoslav28e8ef72015-05-11 19:21:31 -07003430 }
3431
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003432 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003433
3434 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003435 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003436
Emilian Peev53722fa2019-02-22 17:47:20 -08003437 sCameraService->mUidPolicy->registerMonitorUid(mClientUid);
3438
Shuzhen Wang695044d2020-03-06 09:02:23 -08003439 // Notify listeners of camera open/close status
3440 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
3441
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003442 return OK;
3443}
3444
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003445status_t CameraService::BasicClient::startCameraStreamingOps() {
3446 ATRACE_CALL();
3447
3448 if (!mOpsActive) {
3449 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
3450 return INVALID_OPERATION;
3451 }
3452 if (mOpsStreaming) {
3453 ALOGV("%s: Streaming already active!", __FUNCTION__);
3454 return OK;
3455 }
3456
3457 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
3458 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
3459
3460 if (mAppOpsManager != nullptr) {
3461 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
3462 mClientPackageName, /*startIfModeDefault*/ false, mClientFeatureId,
3463 String16("start camera ") + String16(mCameraIdStr));
3464 status_t res = handleAppOpMode(mode);
3465 if (res != OK) {
3466 return res;
3467 }
3468 }
3469
3470 mOpsStreaming = true;
3471
3472 return OK;
3473}
3474
Valentin Iftimec0b8d472021-07-23 20:21:06 +02003475status_t CameraService::BasicClient::noteAppOp() {
3476 ATRACE_CALL();
3477
3478 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d",
3479 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
3480
3481 // noteAppOp is only used for when camera mute is not supported, in order
3482 // to trigger the sensor privacy "Unblock" dialog
3483 if (mAppOpsManager != nullptr) {
3484 int32_t mode = mAppOpsManager->noteOp(AppOpsManager::OP_CAMERA, mClientUid,
3485 mClientPackageName, mClientFeatureId,
3486 String16("start camera ") + String16(mCameraIdStr));
3487 status_t res = handleAppOpMode(mode);
3488 if (res != OK) {
3489 return res;
3490 }
3491 }
3492
3493 return OK;
3494}
3495
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003496status_t CameraService::BasicClient::finishCameraStreamingOps() {
3497 ATRACE_CALL();
3498
3499 if (!mOpsActive) {
3500 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
3501 return INVALID_OPERATION;
3502 }
3503 if (!mOpsStreaming) {
3504 ALOGV("%s: Streaming not active!", __FUNCTION__);
3505 return OK;
3506 }
3507
3508 if (mAppOpsManager != nullptr) {
3509 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
3510 mClientPackageName, mClientFeatureId);
3511 mOpsStreaming = false;
3512 }
3513
3514 return OK;
3515}
3516
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003517status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003518 ATRACE_CALL();
3519
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003520 if (mOpsStreaming) {
3521 // Make sure we've notified everyone about camera stopping
3522 finishCameraStreamingOps();
3523 }
3524
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003525 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003526 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003527 mOpsActive = false;
3528
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01003529 // This function is called when a client disconnects. This should
3530 // release the camera, but actually only if it was in a proper
3531 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003532 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01003533 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003534
Ruben Brunkcc776712015-02-17 20:18:47 -08003535 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003536 sCameraService->updateStatus(StatusInternal::PRESENT,
3537 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003538 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003539 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003540 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
3541 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08003542 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003543 mOpsCallback.clear();
3544
Emilian Peev53722fa2019-02-22 17:47:20 -08003545 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid);
3546
Shuzhen Wang695044d2020-03-06 09:02:23 -08003547 // Notify listeners of camera open/close status
3548 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
3549
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003550 return OK;
3551}
3552
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003553void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003554 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003555 if (mAppOpsManager == nullptr) {
3556 return;
3557 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003558 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003559 if (op != AppOpsManager::OP_CAMERA) {
3560 ALOGW("Unexpected app ops notification received: %d", op);
3561 return;
3562 }
3563
3564 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003565 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003566 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003567 ALOGV("checkOp returns: %d, %s ", res,
3568 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
3569 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
3570 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
3571 "UNKNOWN");
3572
Shuzhen Wang64900852021-02-05 09:03:29 -08003573 if (res == AppOpsManager::MODE_ERRORED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003574 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003575 String8(mClientPackageName).string());
Svet Ganova453d0d2018-01-11 15:37:58 -08003576 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08003577 } else if (res == AppOpsManager::MODE_IGNORED) {
3578 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Evan Severson09ab4002021-02-10 14:15:19 -08003579 bool isCameraPrivacyEnabled =
3580 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled(
3581 multiuser_get_user_id(mClientUid));
Shuzhen Wang64900852021-02-05 09:03:29 -08003582 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d",
3583 mCameraIdStr.string(), String8(mClientPackageName).string(),
3584 mUidIsTrusted, isUidActive);
3585 // If the calling Uid is trusted (a native service), or the client Uid is active (WAR for
3586 // b/175320666), the AppOpsManager could return MODE_IGNORED. Do not treat such cases as
3587 // error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02003588 if (!mUidIsTrusted) {
3589 if (isUidActive && isCameraPrivacyEnabled && supportsCameraMute()) {
3590 setCameraMute(true);
3591 } else if (!isUidActive
3592 || (isCameraPrivacyEnabled && !supportsCameraMute())) {
3593 block();
3594 }
Shuzhen Wang64900852021-02-05 09:03:29 -08003595 }
Evan Severson09ab4002021-02-10 14:15:19 -08003596 } else if (res == AppOpsManager::MODE_ALLOWED) {
3597 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003598 }
3599}
3600
Svet Ganova453d0d2018-01-11 15:37:58 -08003601void CameraService::BasicClient::block() {
3602 ATRACE_CALL();
3603
3604 // Reset the client PID to allow server-initiated disconnect,
3605 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003606 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08003607 CaptureResultExtras resultExtras; // a dummy result (invalid)
3608 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
3609 disconnect();
3610}
3611
Mathias Agopian65ab4712010-07-14 17:59:35 -07003612// ----------------------------------------------------------------------------
3613
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003614void CameraService::Client::notifyError(int32_t errorCode,
Jianing Weicb0652e2014-03-12 18:29:36 -07003615 const CaptureResultExtras& resultExtras) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08003616 (void) resultExtras;
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003617 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07003618 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
3619 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
3620 api1ErrorCode = CAMERA_ERROR_DISABLED;
3621 }
3622 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003623 } else {
3624 ALOGE("mRemoteCallback is NULL!!");
3625 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003626}
3627
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003628// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003629binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003630 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003631 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08003632}
3633
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003634bool CameraService::Client::canCastToApiClient(apiLevel level) const {
3635 return level == API_1;
3636}
3637
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003638CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
3639 mClient(client) {
3640}
3641
3642void CameraService::Client::OpsCallback::opChanged(int32_t op,
3643 const String16& packageName) {
3644 sp<BasicClient> client = mClient.promote();
3645 if (client != NULL) {
3646 client->opChanged(op, packageName);
3647 }
3648}
3649
Mathias Agopian65ab4712010-07-14 17:59:35 -07003650// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08003651// UidPolicy
3652// ----------------------------------------------------------------------------
3653
3654void CameraService::UidPolicy::registerSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003655 Mutex::Autolock _l(mUidLock);
3656
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003657 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07003658 status_t res = mAm.linkToDeath(this);
3659 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08003660 | ActivityManager::UID_OBSERVER_IDLE
Emilian Peev53722fa2019-02-22 17:47:20 -08003661 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganova453d0d2018-01-11 15:37:58 -08003662 ActivityManager::PROCESS_STATE_UNKNOWN,
3663 String16("cameraserver"));
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003664 if (res == OK) {
3665 mRegistered = true;
3666 ALOGV("UidPolicy: Registered with ActivityManager");
3667 }
Svet Ganova453d0d2018-01-11 15:37:58 -08003668}
3669
3670void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003671 Mutex::Autolock _l(mUidLock);
3672
Steven Moreland2f348142019-07-02 15:59:07 -07003673 mAm.unregisterUidObserver(this);
3674 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003675 mRegistered = false;
3676 mActiveUids.clear();
3677 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08003678}
3679
3680void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
3681 onUidIdle(uid, disabled);
3682}
3683
3684void CameraService::UidPolicy::onUidActive(uid_t uid) {
3685 Mutex::Autolock _l(mUidLock);
3686 mActiveUids.insert(uid);
3687}
3688
3689void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
3690 bool deleted = false;
3691 {
3692 Mutex::Autolock _l(mUidLock);
3693 if (mActiveUids.erase(uid) > 0) {
3694 deleted = true;
3695 }
3696 }
3697 if (deleted) {
3698 sp<CameraService> service = mService.promote();
3699 if (service != nullptr) {
3700 service->blockClientsForUid(uid);
3701 }
3702 }
3703}
3704
Emilian Peev53722fa2019-02-22 17:47:20 -08003705void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07003706 int64_t procStateSeq __unused, int32_t capability __unused) {
Emilian Peev53722fa2019-02-22 17:47:20 -08003707 bool procStateChange = false;
3708 {
3709 Mutex::Autolock _l(mUidLock);
3710 if ((mMonitoredUids.find(uid) != mMonitoredUids.end()) &&
3711 (mMonitoredUids[uid].first != procState)) {
3712 mMonitoredUids[uid].first = procState;
3713 procStateChange = true;
3714 }
3715 }
3716
3717 if (procStateChange) {
3718 sp<CameraService> service = mService.promote();
3719 if (service != nullptr) {
3720 service->notifyMonitoredUids();
3721 }
3722 }
3723}
3724
3725void CameraService::UidPolicy::registerMonitorUid(uid_t uid) {
3726 Mutex::Autolock _l(mUidLock);
3727 auto it = mMonitoredUids.find(uid);
3728 if (it != mMonitoredUids.end()) {
3729 it->second.second++;
3730 } else {
3731 mMonitoredUids.emplace(
3732 std::pair<uid_t, std::pair<int32_t, size_t>> (uid,
3733 std::pair<int32_t, size_t> (ActivityManager::PROCESS_STATE_NONEXISTENT, 1)));
3734 }
3735}
3736
3737void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid) {
3738 Mutex::Autolock _l(mUidLock);
3739 auto it = mMonitoredUids.find(uid);
3740 if (it != mMonitoredUids.end()) {
3741 it->second.second--;
3742 if (it->second.second == 0) {
3743 mMonitoredUids.erase(it);
3744 }
3745 } else {
3746 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
3747 }
3748}
3749
Svet Ganov7b4ab782018-03-25 12:48:10 -07003750bool CameraService::UidPolicy::isUidActive(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003751 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003752 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003753}
3754
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003755static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
3756static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003757
Svet Ganov7b4ab782018-03-25 12:48:10 -07003758bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003759 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003760 // If activity manager is unreachable, assume everything is active
3761 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003762 return true;
3763 }
3764 auto it = mOverrideUids.find(uid);
3765 if (it != mOverrideUids.end()) {
3766 return it->second;
3767 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003768 bool active = mActiveUids.find(uid) != mActiveUids.end();
3769 if (!active) {
3770 // We want active UIDs to always access camera with their first attempt since
3771 // there is no guarantee the app is robustly written and would retry getting
3772 // the camera on failure. The inverse case is not a problem as we would take
3773 // camera away soon once we get the callback that the uid is no longer active.
3774 ActivityManager am;
3775 // Okay to access with a lock held as UID changes are dispatched without
3776 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07003777 int64_t startTimeMillis = 0;
3778 do {
3779 // TODO: Fix this b/109950150!
3780 // Okay this is a hack. There is a race between the UID turning active and
3781 // activity being resumed. The proper fix is very risky, so we temporary add
3782 // some polling which should happen pretty rarely anyway as the race is hard
3783 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003784 active = mActiveUids.find(uid) != mActiveUids.end();
Hui Yu12c7ec72020-05-04 17:40:52 +00003785 if (!active) active = am.isUidActive(uid, callingPackage);
Svet Ganov94ec46f2018-06-08 15:03:46 -07003786 if (active) {
3787 break;
3788 }
3789 if (startTimeMillis <= 0) {
3790 startTimeMillis = uptimeMillis();
3791 }
3792 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003793 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003794 if (remainingTimeMillis <= 0) {
3795 break;
3796 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003797 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
3798
3799 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003800 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003801 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003802 } while (true);
3803
Svet Ganov7b4ab782018-03-25 12:48:10 -07003804 if (active) {
3805 // Now that we found out the UID is actually active, cache that
3806 mActiveUids.insert(uid);
3807 }
3808 }
3809 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08003810}
3811
Varun Shahb42f1eb2019-04-16 14:45:13 -07003812int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
3813 Mutex::Autolock _l(mUidLock);
3814 return getProcStateLocked(uid);
3815}
3816
3817int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
3818 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
3819 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
3820 procState = mMonitoredUids[uid].first;
3821 }
3822 return procState;
3823}
3824
Svet Ganov7b4ab782018-03-25 12:48:10 -07003825void CameraService::UidPolicy::UidPolicy::addOverrideUid(uid_t uid,
3826 String16 callingPackage, bool active) {
3827 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08003828}
3829
Svet Ganov7b4ab782018-03-25 12:48:10 -07003830void CameraService::UidPolicy::removeOverrideUid(uid_t uid, String16 callingPackage) {
3831 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08003832}
3833
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003834void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
3835 Mutex::Autolock _l(mUidLock);
3836 ALOGV("UidPolicy: ActivityManager has died");
3837 mRegistered = false;
3838 mActiveUids.clear();
3839}
3840
Svet Ganov7b4ab782018-03-25 12:48:10 -07003841void CameraService::UidPolicy::updateOverrideUid(uid_t uid, String16 callingPackage,
3842 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003843 bool wasActive = false;
3844 bool isActive = false;
3845 {
3846 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003847 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003848 mOverrideUids.erase(uid);
3849 if (insert) {
3850 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
3851 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003852 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003853 }
3854 if (wasActive != isActive && !isActive) {
3855 sp<CameraService> service = mService.promote();
3856 if (service != nullptr) {
3857 service->blockClientsForUid(uid);
3858 }
3859 }
3860}
3861
3862// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08003863// SensorPrivacyPolicy
3864// ----------------------------------------------------------------------------
3865void CameraService::SensorPrivacyPolicy::registerSelf() {
3866 Mutex::Autolock _l(mSensorPrivacyLock);
3867 if (mRegistered) {
3868 return;
3869 }
Evan Severson09ab4002021-02-10 14:15:19 -08003870 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08003871 mSpm.addSensorPrivacyListener(this);
3872 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
3873 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003874 if (res == OK) {
3875 mRegistered = true;
3876 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
3877 }
3878}
3879
3880void CameraService::SensorPrivacyPolicy::unregisterSelf() {
3881 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08003882 mSpm.removeSensorPrivacyListener(this);
3883 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003884 mRegistered = false;
3885 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
3886}
3887
3888bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
3889 Mutex::Autolock _l(mSensorPrivacyLock);
3890 return mSensorPrivacyEnabled;
3891}
3892
Evan Severson09ab4002021-02-10 14:15:19 -08003893bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled(userid_t userId) {
3894 if (!hasCameraPrivacyFeature()) {
3895 return false;
3896 }
3897 return mSpm.isIndividualSensorPrivacyEnabled(userId,
3898 SensorPrivacyManager::INDIVIDUAL_SENSOR_CAMERA);
3899}
3900
Michael Grooverd1d435a2018-12-18 17:39:42 -08003901binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
3902 {
3903 Mutex::Autolock _l(mSensorPrivacyLock);
3904 mSensorPrivacyEnabled = enabled;
3905 }
3906 // if sensor privacy is enabled then block all clients from accessing the camera
Evan Severson09ab4002021-02-10 14:15:19 -08003907 if (enabled) {
3908 sp<CameraService> service = mService.promote();
3909 if (service != nullptr) {
3910 service->blockAllClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08003911 }
3912 }
3913 return binder::Status::ok();
3914}
3915
3916void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
3917 Mutex::Autolock _l(mSensorPrivacyLock);
3918 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
3919 mRegistered = false;
3920}
3921
Evan Severson09ab4002021-02-10 14:15:19 -08003922bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Severson671806e2021-04-20 16:44:53 -07003923 return mSpm.supportsSensorToggle(SensorPrivacyManager::INDIVIDUAL_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08003924}
3925
Michael Grooverd1d435a2018-12-18 17:39:42 -08003926// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003927// CameraState
3928// ----------------------------------------------------------------------------
3929
3930CameraService::CameraState::CameraState(const String8& id, int cost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003931 const std::set<String8>& conflicting, SystemCameraKind systemCameraKind) : mId(id),
3932 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
3933 mSystemCameraKind(systemCameraKind) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08003934
3935CameraService::CameraState::~CameraState() {}
3936
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003937CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003938 Mutex::Autolock lock(mStatusLock);
3939 return mStatus;
3940}
3941
Shuzhen Wang43858162020-01-10 13:42:15 -08003942std::vector<String8> CameraService::CameraState::getUnavailablePhysicalIds() const {
3943 Mutex::Autolock lock(mStatusLock);
3944 std::vector<String8> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
3945 return res;
3946}
3947
Ruben Brunkcc776712015-02-17 20:18:47 -08003948CameraParameters CameraService::CameraState::getShimParams() const {
3949 return mShimParams;
3950}
3951
3952void CameraService::CameraState::setShimParams(const CameraParameters& params) {
3953 mShimParams = params;
3954}
3955
3956int CameraService::CameraState::getCost() const {
3957 return mCost;
3958}
3959
3960std::set<String8> CameraService::CameraState::getConflicting() const {
3961 return mConflicting;
3962}
3963
3964String8 CameraService::CameraState::getId() const {
3965 return mId;
3966}
3967
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003968SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
3969 return mSystemCameraKind;
3970}
3971
Shuzhen Wang43858162020-01-10 13:42:15 -08003972bool CameraService::CameraState::addUnavailablePhysicalId(const String8& physicalId) {
3973 Mutex::Autolock lock(mStatusLock);
3974 auto result = mUnavailablePhysicalIds.insert(physicalId);
3975 return result.second;
3976}
3977
3978bool CameraService::CameraState::removeUnavailablePhysicalId(const String8& physicalId) {
3979 Mutex::Autolock lock(mStatusLock);
3980 auto count = mUnavailablePhysicalIds.erase(physicalId);
3981 return count > 0;
3982}
3983
Shuzhen Wange7aa0342021-08-03 11:29:47 -07003984void CameraService::CameraState::setClientPackage(const String8& clientPackage) {
3985 Mutex::Autolock lock(mStatusLock);
3986 mClientPackage = clientPackage;
3987}
3988
3989String8 CameraService::CameraState::getClientPackage() const {
3990 Mutex::Autolock lock(mStatusLock);
3991 return mClientPackage;
3992}
3993
Ruben Brunkcc776712015-02-17 20:18:47 -08003994// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07003995// ClientEventListener
3996// ----------------------------------------------------------------------------
3997
3998void CameraService::ClientEventListener::onClientAdded(
3999 const resource_policy::ClientDescriptor<String8,
4000 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07004001 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07004002 if (basicClient.get() != nullptr) {
4003 BatteryNotifier& notifier(BatteryNotifier::getInstance());
4004 notifier.noteStartCamera(descriptor.getKey(),
4005 static_cast<int>(basicClient->getClientUid()));
4006 }
4007}
4008
4009void CameraService::ClientEventListener::onClientRemoved(
4010 const resource_policy::ClientDescriptor<String8,
4011 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07004012 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07004013 if (basicClient.get() != nullptr) {
4014 BatteryNotifier& notifier(BatteryNotifier::getInstance());
4015 notifier.noteStopCamera(descriptor.getKey(),
4016 static_cast<int>(basicClient->getClientUid()));
4017 }
4018}
4019
4020
4021// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08004022// CameraClientManager
4023// ----------------------------------------------------------------------------
4024
Ruben Brunk99e69712015-05-26 17:25:07 -07004025CameraService::CameraClientManager::CameraClientManager() {
4026 setListener(std::make_shared<ClientEventListener>());
4027}
4028
Ruben Brunkcc776712015-02-17 20:18:47 -08004029CameraService::CameraClientManager::~CameraClientManager() {}
4030
4031sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
4032 const String8& id) const {
4033 auto descriptor = get(id);
4034 if (descriptor == nullptr) {
4035 return sp<BasicClient>{nullptr};
4036 }
4037 return descriptor->getValue();
4038}
4039
4040String8 CameraService::CameraClientManager::toString() const {
4041 auto all = getAll();
4042 String8 ret("[");
4043 bool hasAny = false;
4044 for (auto& i : all) {
4045 hasAny = true;
4046 String8 key = i->getKey();
4047 int32_t cost = i->getCost();
4048 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00004049 int32_t score = i->getPriority().getScore();
4050 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08004051 auto conflicting = i->getConflicting();
4052 auto clientSp = i->getValue();
4053 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07004054 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08004055 if (clientSp.get() != nullptr) {
4056 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07004057 uid_t clientUid = clientSp->getClientUid();
4058 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08004059 }
Emilian Peev8131a262017-02-01 12:33:43 +00004060 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
4061 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08004062
Ruben Brunk6267b532015-04-30 17:44:07 -07004063 if (clientSp.get() != nullptr) {
4064 ret.appendFormat("User Id: %d, ", clientUserId);
4065 }
Ruben Brunkcc776712015-02-17 20:18:47 -08004066 if (packageName.size() != 0) {
4067 ret.appendFormat("Client Package Name: %s", packageName.string());
4068 }
4069
4070 ret.append(", Conflicting Client Devices: {");
4071 for (auto& j : conflicting) {
4072 ret.appendFormat("%s, ", j.string());
4073 }
4074 ret.append("})");
4075 }
4076 if (hasAny) ret.append("\n");
4077 ret.append("]\n");
4078 return ret;
4079}
4080
4081CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
4082 const String8& key, const sp<BasicClient>& value, int32_t cost,
Emilian Peev8131a262017-02-01 12:33:43 +00004083 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00004084 int32_t state, int32_t oomScoreOffset) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004085
Steven Moreland89a2c5c2020-01-31 15:02:25 -08004086 bool isVendorClient = getCurrentServingCall() == BinderCallType::HWBINDER;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07004087 int32_t score_adj = isVendorClient ? kVendorClientScore : score;
4088 int32_t state_adj = isVendorClient ? kVendorClientState: state;
4089
Ruben Brunkcc776712015-02-17 20:18:47 -08004090 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00004091 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj, isVendorClient,
4092 oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08004093}
4094
4095CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00004096 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
4097 int32_t oomScoreOffset) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004098 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00004099 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00004100 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08004101}
4102
4103// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08004104// InjectionStatusListener
4105// ----------------------------------------------------------------------------
4106
4107void CameraService::InjectionStatusListener::addListener(
4108 const sp<ICameraInjectionCallback>& callback) {
4109 Mutex::Autolock lock(mListenerLock);
4110 if (mCameraInjectionCallback) return;
4111 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
4112 if (res == OK) {
4113 mCameraInjectionCallback = callback;
4114 }
4115}
4116
4117void CameraService::InjectionStatusListener::removeListener() {
4118 Mutex::Autolock lock(mListenerLock);
4119 if (mCameraInjectionCallback == nullptr) {
4120 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
4121 return;
4122 }
4123 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
4124 mCameraInjectionCallback = nullptr;
4125}
4126
4127void CameraService::InjectionStatusListener::notifyInjectionError(
Cliff Wud3a05312021-04-26 23:07:31 +08004128 String8 injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08004129 if (mCameraInjectionCallback == nullptr) {
4130 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
4131 return;
4132 }
Cliff Wud3a05312021-04-26 23:07:31 +08004133
4134 switch (err) {
4135 case -ENODEV:
4136 mCameraInjectionCallback->onInjectionError(
4137 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4138 ALOGE("No camera device with ID \"%s\" currently available!",
4139 injectedCamId.string());
4140 break;
4141 case -EBUSY:
4142 mCameraInjectionCallback->onInjectionError(
4143 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4144 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
4145 injectedCamId.string());
4146 break;
4147 case DEAD_OBJECT:
4148 mCameraInjectionCallback->onInjectionError(
4149 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4150 ALOGE("Camera ID \"%s\" object is dead!",
4151 injectedCamId.string());
4152 break;
4153 case INVALID_OPERATION:
4154 mCameraInjectionCallback->onInjectionError(
4155 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4156 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
4157 injectedCamId.string());
4158 break;
4159 case UNKNOWN_TRANSACTION:
4160 mCameraInjectionCallback->onInjectionError(
4161 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
4162 ALOGE("Camera ID \"%s\" method doesn't support!",
4163 injectedCamId.string());
4164 break;
4165 default:
4166 mCameraInjectionCallback->onInjectionError(
4167 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
4168 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
4169 strerror(-err), err, injectedCamId.string());
4170 }
Cliff Wud8cae102021-03-11 01:37:42 +08004171}
4172
4173void CameraService::InjectionStatusListener::binderDied(
4174 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08004175 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
4176 auto parent = mParent.promote();
4177 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08004178 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
4179 if (clientDescriptor != nullptr) {
4180 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
4181 baseClientPtr->stopInjection();
4182 }
Cliff Wu3b268182021-07-06 15:44:43 +08004183 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08004184 }
4185}
4186
4187// ----------------------------------------------------------------------------
4188// CameraInjectionSession
4189// ----------------------------------------------------------------------------
4190
4191binder::Status CameraService::CameraInjectionSession::stopInjection() {
4192 Mutex::Autolock lock(mInjectionSessionLock);
4193 auto parent = mParent.promote();
4194 if (parent == nullptr) {
4195 ALOGE("CameraInjectionSession: Parent is gone");
4196 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
4197 "Camera service encountered error");
4198 }
Cliff Wud3a05312021-04-26 23:07:31 +08004199
4200 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08004201 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
4202 if (clientDescriptor != nullptr) {
4203 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
4204 res = baseClientPtr->stopInjection();
4205 if (res != OK) {
4206 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
4207 " ret != NO_ERROR: %d", res);
4208 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
4209 "Camera session encountered error");
4210 }
4211 }
Cliff Wu3b268182021-07-06 15:44:43 +08004212 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08004213 return binder::Status::ok();
4214}
4215
4216// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07004217
4218static const int kDumpLockRetries = 50;
4219static const int kDumpLockSleep = 60000;
4220
4221static bool tryLock(Mutex& mutex)
4222{
4223 bool locked = false;
4224 for (int i = 0; i < kDumpLockRetries; ++i) {
4225 if (mutex.tryLock() == NO_ERROR) {
4226 locked = true;
4227 break;
4228 }
4229 usleep(kDumpLockSleep);
4230 }
4231 return locked;
4232}
4233
Rucha Katakwardf223072021-06-15 10:21:00 -07004234void CameraService::cacheDump() {
4235 if (mMemFd != -1) {
4236 const Vector<String16> args;
4237 ATRACE_CALL();
4238 // Acquiring service lock here will avoid the deadlock since
4239 // cacheDump will not be called during the second disconnect.
4240 Mutex::Autolock lock(mServiceLock);
4241
4242 Mutex::Autolock l(mCameraStatesLock);
4243 // Start collecting the info for open sessions and store it in temp file.
4244 for (const auto& state : mCameraStates) {
4245 String8 cameraId = state.first;
4246 auto clientDescriptor = mActiveClientManager.get(cameraId);
4247 if (clientDescriptor != nullptr) {
4248 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.string());
4249 // Log the current open session info before device is disconnected.
4250 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
4251 }
4252 }
4253 }
4254}
4255
Mathias Agopian65ab4712010-07-14 17:59:35 -07004256status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004257 ATRACE_CALL();
4258
Jayant Chowdhary5216b212019-07-17 09:26:23 -07004259 if (checkCallingPermission(sDumpPermission) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004260 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07004261 CameraThreadState::getCallingPid(),
4262 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004263 return NO_ERROR;
4264 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004265 bool locked = tryLock(mServiceLock);
4266 // failed to lock - CameraService is probably deadlocked
4267 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004268 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004269 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004270
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004271 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004272 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07004273
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004274 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004275 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08004276
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004277 if (locked) mServiceLock.unlock();
4278 return NO_ERROR;
4279 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004280 dprintf(fd, "\n== Service global info: ==\n\n");
4281 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004282 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07004283 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
4284 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004285 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
4286 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
4287 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004288 String8 activeClientString = mActiveClientManager.toString();
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004289 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
4290 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004291
4292 dumpEventLog(fd);
4293
4294 bool stateLocked = tryLock(mCameraStatesLock);
4295 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004296 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004297 }
4298
Emilian Peevbd8c5032018-02-14 23:05:40 +00004299 int argSize = args.size();
4300 for (int i = 0; i < argSize; i++) {
4301 if (args[i] == TagMonitor::kMonitorOption) {
4302 if (i + 1 < argSize) {
4303 mMonitorTags = String8(args[i + 1]);
4304 }
4305 break;
4306 }
4307 }
4308
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004309 for (auto& state : mCameraStates) {
4310 String8 cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004311
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004312 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004313
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004314 CameraParameters p = state.second->getShimParams();
4315 if (!p.isEmpty()) {
4316 dprintf(fd, " Camera1 API shim is using parameters:\n ");
4317 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004318 }
4319
4320 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08004321 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07004322 // log the current open session info
4323 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08004324 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07004325 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004326 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004327
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004328 }
4329
4330 if (stateLocked) mCameraStatesLock.unlock();
4331
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004332 if (locked) mServiceLock.unlock();
4333
Emilian Peevf53f66e2017-04-11 14:29:43 +01004334 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004335
4336 dprintf(fd, "\n== Vendor tags: ==\n\n");
4337
4338 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
4339 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00004340 sp<VendorTagDescriptorCache> cache =
4341 VendorTagDescriptorCache::getGlobalVendorTagCache();
4342 if (cache == NULL) {
4343 dprintf(fd, "No vendor tags.\n");
4344 } else {
4345 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
4346 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004347 } else {
4348 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
4349 }
4350
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004351 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004352 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004353 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004354
4355 // Process dump arguments, if any
4356 int n = args.size();
4357 String16 verboseOption("-v");
4358 String16 unreachableOption("--unreachable");
4359 for (int i = 0; i < n; i++) {
4360 if (args[i] == verboseOption) {
4361 // change logging level
4362 if (i + 1 >= n) continue;
4363 String8 levelStr(args[i+1]);
4364 int level = atoi(levelStr.string());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004365 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004366 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004367 } else if (args[i] == unreachableOption) {
4368 // Dump memory analysis
4369 // TODO - should limit be an argument parameter?
4370 UnreachableMemoryInfo info;
4371 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
4372 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004373 dprintf(fd, "\n== Unable to dump unreachable memory. "
4374 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004375 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004376 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004377 std::string s = info.ToString(/*log_contents*/ true);
4378 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004379 }
4380 }
4381 }
Rucha Katakwardf223072021-06-15 10:21:00 -07004382
4383 bool serviceLocked = tryLock(mServiceLock);
4384
4385 // Dump info from previous open sessions.
4386 // Reposition the offset to beginning of the file before reading
4387
4388 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
4389 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
4390 ssize_t size_read;
4391 char buf[4096];
4392 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
4393 // Read data from file to a small buffer and write it to fd.
4394 write(fd, buf, size_read);
4395 if (size_read == -1) {
4396 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
4397 break;
4398 }
4399 }
4400 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
4401 } else {
4402 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
4403 }
4404
4405 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004406 return NO_ERROR;
4407}
4408
Rucha Katakwardf223072021-06-15 10:21:00 -07004409void CameraService::dumpOpenSessionClientLogs(int fd,
4410 const Vector<String16>& args, const String8& cameraId) {
4411 auto clientDescriptor = mActiveClientManager.get(cameraId);
4412 dprintf(fd, " Device %s is open. Client instance dump:\n",
4413 cameraId.string());
4414 dprintf(fd, " Client priority score: %d state: %d\n",
4415 clientDescriptor->getPriority().getScore(),
4416 clientDescriptor->getPriority().getState());
4417 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
4418
4419 auto client = clientDescriptor->getValue();
4420 dprintf(fd, " Client package: %s\n",
4421 String8(client->getPackageName()).string());
4422
4423 client->dumpClient(fd, args);
4424}
4425
4426void CameraService::dumpClosedSessionClientLogs(int fd, const String8& cameraId) {
4427 dprintf(fd, " Device %s is closed, no client instance\n",
4428 cameraId.string());
4429}
4430
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004431void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004432 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004433
4434 Mutex::Autolock l(mLogLock);
4435 for (const auto& msg : mEventLog) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004436 dprintf(fd, " %s\n", msg.string());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004437 }
4438
4439 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004440 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004441 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004442 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004443 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004444 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004445}
4446
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004447void CameraService::cacheClientTagDumpIfNeeded(const char *cameraId, BasicClient* client) {
4448 Mutex::Autolock lock(mLogLock);
4449 if (!isClientWatchedLocked(client)) { return; }
4450
4451 std::vector<std::string> dumpVector;
4452 client->dumpWatchedEventsToVector(dumpVector);
4453
4454 if (dumpVector.empty()) { return; }
4455
Avichal Rakesh882c08b2021-12-09 17:47:07 -08004456 std::string dumpString;
4457
4458 String8 currentTime = getFormattedCurrentTime();
4459 dumpString += "Cached @ ";
4460 dumpString += currentTime.string();
4461 dumpString += "\n"; // First line is the timestamp of when client is cached.
4462
4463
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08004464 const String16 &packageName = client->getPackageName();
4465
4466 String8 packageName8 = String8(packageName);
4467 const char *printablePackageName = packageName8.lockBuffer(packageName.size());
4468
Avichal Rakesh882c08b2021-12-09 17:47:07 -08004469
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004470 size_t i = dumpVector.size();
4471
4472 // Store the string in reverse order (latest last)
4473 while (i > 0) {
4474 i--;
4475 dumpString += cameraId;
4476 dumpString += ":";
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08004477 dumpString += printablePackageName;
4478 dumpString += " ";
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004479 dumpString += dumpVector[i]; // implicitly ends with '\n'
4480 }
4481
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08004482 packageName8.unlockBuffer();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004483 mWatchedClientsDumpCache[packageName] = dumpString;
4484}
4485
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004486void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004487 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004488 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
4489 if (mTorchClientMap[i] == who) {
4490 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004491 String8 cameraId = mTorchClientMap.keyAt(i);
4492 status_t res = mFlashlight->setTorchMode(cameraId, false);
4493 if (res) {
4494 ALOGE("%s: torch client died but couldn't turn off torch: "
4495 "%s (%d)", __FUNCTION__, strerror(-res), res);
4496 return;
4497 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004498 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004499 break;
4500 }
4501 }
4502}
4503
Ruben Brunkcc776712015-02-17 20:18:47 -08004504/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07004505
Igor Murashkin294d0ec2012-10-05 10:44:57 -07004506 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07004507 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
4508 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07004509 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08004510 // PID here is approximate and can be wrong.
Jayant Chowdhary12361932018-08-27 14:46:13 -07004511 logClientDied(CameraThreadState::getCallingPid(), String8("Binder died unexpectedly"));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004512
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004513 // check torch client
4514 handleTorchClientBinderDied(who);
4515
4516 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08004517 if(!evictClientIdByRemote(who)) {
4518 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07004519 return;
4520 }
4521
Ruben Brunkcc776712015-02-17 20:18:47 -08004522 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
4523 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07004524}
4525
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004526void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004527 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08004528}
4529
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004530void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
4531 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004532 // Do not lock mServiceLock here or can get into a deadlock from
4533 // connect() -> disconnect -> updateStatus
4534
4535 auto state = getCameraState(cameraId);
4536
4537 if (state == nullptr) {
4538 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
4539 cameraId.string());
4540 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07004541 }
4542
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004543 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
4544 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
4545 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
4546 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
4547 return;
4548 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004549
4550 // Collect the logical cameras without holding mStatusLock in updateStatus
4551 // as that can lead to a deadlock(b/162192331).
4552 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08004553 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08004554 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07004555 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004556 &logicalCameraIds]
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004557 (const String8& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004558
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004559 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004560 // Update torch status if it has a flash unit.
4561 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004562 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004563 if (getTorchStatusLocked(cameraId, &torchStatus) !=
4564 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004565 TorchModeStatus newTorchStatus =
4566 status == StatusInternal::PRESENT ?
4567 TorchModeStatus::AVAILABLE_OFF :
4568 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004569 if (torchStatus != newTorchStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07004570 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004571 }
4572 }
Ruben Brunkcc776712015-02-17 20:18:47 -08004573 }
4574
4575 Mutex::Autolock lock(mStatusListenerLock);
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004576 notifyPhysicalCameraStatusLocked(mapToInterface(status), String16(cameraId),
4577 logicalCameraIds, deviceKind);
Shuzhen Wang43858162020-01-10 13:42:15 -08004578
Ruben Brunkcc776712015-02-17 20:18:47 -08004579 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07004580 bool isVendorListener = listener->isVendorListener();
4581 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
4582 listener->getListenerPid(), listener->getListenerUid()) ||
Shuzhen Wangb8259792021-05-27 09:27:06 -07004583 isVendorListener) {
4584 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07004585 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08004586 continue;
4587 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07004588 listener->getListener()->onStatusChanged(mapToInterface(status),
Emilian Peev53722fa2019-02-22 17:47:20 -08004589 String16(cameraId));
Ruben Brunkcc776712015-02-17 20:18:47 -08004590 }
4591 });
Igor Murashkincba2c162013-03-20 15:56:31 -07004592}
4593
Shuzhen Wang695044d2020-03-06 09:02:23 -08004594void CameraService::updateOpenCloseStatus(const String8& cameraId, bool open,
4595 const String16& clientPackageName) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07004596 auto state = getCameraState(cameraId);
4597 if (state == nullptr) {
4598 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
4599 cameraId.string());
4600 return;
4601 }
4602 if (open) {
4603 state->setClientPackage(String8(clientPackageName));
4604 } else {
4605 state->setClientPackage(String8::empty());
4606 }
4607
Shuzhen Wang695044d2020-03-06 09:02:23 -08004608 Mutex::Autolock lock(mStatusListenerLock);
4609
4610 for (const auto& it : mListenerList) {
4611 if (!it->isOpenCloseCallbackAllowed()) {
4612 continue;
4613 }
4614
4615 binder::Status ret;
4616 String16 cameraId64(cameraId);
4617 if (open) {
4618 ret = it->getListener()->onCameraOpened(cameraId64, clientPackageName);
4619 } else {
4620 ret = it->getListener()->onCameraClosed(cameraId64);
4621 }
4622 if (!ret.isOk()) {
4623 ALOGE("%s: Failed to trigger onCameraOpened/onCameraClosed callback: %d", __FUNCTION__,
4624 ret.exceptionCode());
4625 }
4626 }
4627}
4628
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004629template<class Func>
4630void CameraService::CameraState::updateStatus(StatusInternal status,
4631 const String8& cameraId,
4632 std::initializer_list<StatusInternal> rejectSourceStates,
4633 Func onStatusUpdatedLocked) {
4634 Mutex::Autolock lock(mStatusLock);
4635 StatusInternal oldStatus = mStatus;
4636 mStatus = status;
4637
4638 if (oldStatus == status) {
4639 return;
4640 }
4641
4642 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
4643 cameraId.string(), oldStatus, status);
4644
4645 if (oldStatus == StatusInternal::NOT_PRESENT &&
4646 (status != StatusInternal::PRESENT &&
4647 status != StatusInternal::ENUMERATING)) {
4648
4649 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
4650 __FUNCTION__);
4651 mStatus = oldStatus;
4652 return;
4653 }
4654
4655 /**
4656 * Sometimes we want to conditionally do a transition.
4657 * For example if a client disconnects, we want to go to PRESENT
4658 * only if we weren't already in NOT_PRESENT or ENUMERATING.
4659 */
4660 for (auto& rejectStatus : rejectSourceStates) {
4661 if (oldStatus == rejectStatus) {
4662 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
4663 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
4664 mStatus = oldStatus;
4665 return;
4666 }
4667 }
4668
4669 onStatusUpdatedLocked(cameraId, status);
4670}
4671
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004672status_t CameraService::getTorchStatusLocked(
4673 const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004674 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004675 if (!status) {
4676 return BAD_VALUE;
4677 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004678 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
4679 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004680 // invalid camera ID or the camera doesn't have a flash unit
4681 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004682 }
4683
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004684 *status = mTorchStatusMap.valueAt(index);
4685 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004686}
4687
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004688status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004689 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004690 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
4691 if (index == NAME_NOT_FOUND) {
4692 return BAD_VALUE;
4693 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004694 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004695
4696 return OK;
4697}
4698
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004699std::list<String16> CameraService::getLogicalCameras(
4700 const String8& physicalCameraId) {
4701 std::list<String16> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08004702 Mutex::Autolock lock(mCameraStatesLock);
4703 for (const auto& state : mCameraStates) {
4704 std::vector<std::string> physicalCameraIds;
4705 if (!mCameraProviderManager->isLogicalCamera(state.first.c_str(), &physicalCameraIds)) {
4706 // This is not a logical multi-camera.
4707 continue;
4708 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004709 if (std::find(physicalCameraIds.begin(), physicalCameraIds.end(), physicalCameraId.c_str())
Shuzhen Wang43858162020-01-10 13:42:15 -08004710 == physicalCameraIds.end()) {
4711 // cameraId is not a physical camera of this logical multi-camera.
4712 continue;
4713 }
4714
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004715 retList.emplace_back(String16(state.first));
4716 }
4717 return retList;
4718}
4719
4720void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
4721 const String16& physicalCameraId, const std::list<String16>& logicalCameraIds,
4722 SystemCameraKind deviceKind) {
4723 // mStatusListenerLock is expected to be locked
4724 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08004725 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004726 // Note: we check only the deviceKind of the physical camera id
4727 // since, logical camera ids and their physical camera ids are
4728 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07004729 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
4730 listener->getListenerPid(), listener->getListenerUid())) {
4731 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004732 String8(physicalCameraId).c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07004733 continue;
4734 }
Shuzhen Wang43858162020-01-10 13:42:15 -08004735 listener->getListener()->onPhysicalCameraStatusChanged(status,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004736 logicalCameraId, physicalCameraId);
Shuzhen Wang43858162020-01-10 13:42:15 -08004737 }
4738 }
4739}
4740
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004741
Svet Ganova453d0d2018-01-11 15:37:58 -08004742void CameraService::blockClientsForUid(uid_t uid) {
4743 const auto clients = mActiveClientManager.getAll();
4744 for (auto& current : clients) {
4745 if (current != nullptr) {
4746 const auto basicClient = current->getValue();
4747 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
4748 basicClient->block();
4749 }
4750 }
4751 }
4752}
4753
Michael Grooverd1d435a2018-12-18 17:39:42 -08004754void CameraService::blockAllClients() {
4755 const auto clients = mActiveClientManager.getAll();
4756 for (auto& current : clients) {
4757 if (current != nullptr) {
4758 const auto basicClient = current->getValue();
4759 if (basicClient.get() != nullptr) {
4760 basicClient->block();
4761 }
4762 }
4763 }
4764}
4765
Svet Ganova453d0d2018-01-11 15:37:58 -08004766// NOTE: This is a remote API - make sure all args are validated
4767status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
4768 if (!checkCallingPermission(sManageCameraPermission, nullptr, nullptr)) {
4769 return PERMISSION_DENIED;
4770 }
4771 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
4772 return BAD_VALUE;
4773 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004774 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004775 return handleSetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07004776 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004777 return handleResetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07004778 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004779 return handleGetUidState(args, out, err);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004780 } else if (args.size() >= 2 && args[0] == String16("set-rotate-and-crop")) {
4781 return handleSetRotateAndCrop(args);
4782 } else if (args.size() >= 1 && args[0] == String16("get-rotate-and-crop")) {
4783 return handleGetRotateAndCrop(out);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004784 } else if (args.size() >= 2 && args[0] == String16("set-image-dump-mask")) {
4785 return handleSetImageDumpMask(args);
4786 } else if (args.size() >= 1 && args[0] == String16("get-image-dump-mask")) {
4787 return handleGetImageDumpMask(out);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004788 } else if (args.size() >= 2 && args[0] == String16("set-camera-mute")) {
4789 return handleSetCameraMute(args);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004790 } else if (args.size() >= 2 && args[0] == String16("watch")) {
Avichal Rakesh84147132021-11-11 17:47:11 -08004791 return handleWatchCommand(args, in, out);
Svet Ganova453d0d2018-01-11 15:37:58 -08004792 } else if (args.size() == 1 && args[0] == String16("help")) {
4793 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004794 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08004795 }
4796 printHelp(err);
4797 return BAD_VALUE;
4798}
4799
4800status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004801 String16 packageName = args[1];
4802
Svet Ganova453d0d2018-01-11 15:37:58 -08004803 bool active = false;
4804 if (args[2] == String16("active")) {
4805 active = true;
4806 } else if ((args[2] != String16("idle"))) {
4807 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
4808 return BAD_VALUE;
4809 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004810
4811 int userId = 0;
4812 if (args.size() >= 5 && args[3] == String16("--user")) {
4813 userId = atoi(String8(args[4]));
4814 }
4815
4816 uid_t uid;
4817 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
4818 return BAD_VALUE;
4819 }
4820
4821 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08004822 return NO_ERROR;
4823}
4824
4825status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004826 String16 packageName = args[1];
4827
4828 int userId = 0;
4829 if (args.size() >= 4 && args[2] == String16("--user")) {
4830 userId = atoi(String8(args[3]));
4831 }
4832
4833 uid_t uid;
4834 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004835 return BAD_VALUE;
4836 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004837
4838 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08004839 return NO_ERROR;
4840}
4841
4842status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004843 String16 packageName = args[1];
4844
4845 int userId = 0;
4846 if (args.size() >= 4 && args[2] == String16("--user")) {
4847 userId = atoi(String8(args[3]));
4848 }
4849
4850 uid_t uid;
4851 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004852 return BAD_VALUE;
4853 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004854
4855 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004856 return dprintf(out, "active\n");
4857 } else {
4858 return dprintf(out, "idle\n");
4859 }
4860}
4861
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004862status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
4863 int rotateValue = atoi(String8(args[1]));
4864 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
4865 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
4866 Mutex::Autolock lock(mServiceLock);
4867
4868 mOverrideRotateAndCropMode = rotateValue;
4869
4870 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
4871
4872 const auto clients = mActiveClientManager.getAll();
4873 for (auto& current : clients) {
4874 if (current != nullptr) {
4875 const auto basicClient = current->getValue();
4876 if (basicClient.get() != nullptr) {
4877 basicClient->setRotateAndCropOverride(rotateValue);
4878 }
4879 }
4880 }
4881
4882 return OK;
4883}
4884
4885status_t CameraService::handleGetRotateAndCrop(int out) {
4886 Mutex::Autolock lock(mServiceLock);
4887
4888 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
4889}
4890
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004891status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
4892 char *endPtr;
4893 errno = 0;
4894 String8 maskString8 = String8(args[1]);
4895 long maskValue = strtol(maskString8.c_str(), &endPtr, 10);
4896
4897 if (errno != 0) return BAD_VALUE;
4898 if (endPtr != maskString8.c_str() + maskString8.size()) return BAD_VALUE;
4899 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
4900
4901 Mutex::Autolock lock(mServiceLock);
4902
4903 mImageDumpMask = maskValue;
4904
4905 return OK;
4906}
4907
4908status_t CameraService::handleGetImageDumpMask(int out) {
4909 Mutex::Autolock lock(mServiceLock);
4910
4911 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
4912}
4913
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004914status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
4915 int muteValue = strtol(String8(args[1]), nullptr, 10);
4916 if (errno != 0) return BAD_VALUE;
4917
4918 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
4919 Mutex::Autolock lock(mServiceLock);
4920
4921 mOverrideCameraMuteMode = (muteValue == 1);
4922
4923 const auto clients = mActiveClientManager.getAll();
4924 for (auto& current : clients) {
4925 if (current != nullptr) {
4926 const auto basicClient = current->getValue();
4927 if (basicClient.get() != nullptr) {
4928 if (basicClient->supportsCameraMute()) {
4929 basicClient->setCameraMute(mOverrideCameraMuteMode);
4930 }
4931 }
4932 }
4933 }
4934
4935 return OK;
4936}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004937
Avichal Rakesh84147132021-11-11 17:47:11 -08004938status_t CameraService::handleWatchCommand(const Vector<String16>& args, int inFd, int outFd) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004939 if (args.size() >= 3 && args[1] == String16("start")) {
4940 return startWatchingTags(args, outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004941 } else if (args.size() == 2 && args[1] == String16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004942 return stopWatchingTags(outFd);
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08004943 } else if (args.size() == 2 && args[1] == String16("dump")) {
4944 return printWatchedTags(outFd);
4945 } else if (args.size() >= 2 && args[1] == String16("live")) {
4946 return printWatchedTagsUntilInterrupt(args, inFd, outFd);
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08004947 } else if (args.size() == 2 && args[1] == String16("clear")) {
4948 return clearCachedMonitoredTagDumps(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004949 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004950 dprintf(outFd, "Camera service watch commands:\n"
4951 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
4952 " starts watching the provided tags for clients with provided package\n"
4953 " recognizes tag shorthands like '3a'\n"
4954 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08004955 " dump dumps the monitoring information and exits\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004956 " stop stops watching all tags\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08004957 " live [-n <refresh_interval_ms>]\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004958 " prints the monitored information in real time\n"
Avichal Rakesh84147132021-11-11 17:47:11 -08004959 " Hit return to exit\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08004960 " clear clears all buffers storing information for watch command");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004961 return BAD_VALUE;
4962}
4963
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004964status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
4965 Mutex::Autolock lock(mLogLock);
4966 size_t tagsIdx; // index of '-m'
4967 String16 tags("");
4968 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != String16("-m"); tagsIdx++);
4969 if (tagsIdx < args.size() - 1) {
4970 tags = args[tagsIdx + 1];
4971 } else {
4972 dprintf(outFd, "No tags provided.\n");
4973 return BAD_VALUE;
4974 }
4975
4976 size_t clientsIdx; // index of '-c'
4977 String16 clients = kWatchAllClientsFlag; // watch all clients if no clients are provided
4978 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != String16("-c");
4979 clientsIdx++);
4980 if (clientsIdx < args.size() - 1) {
4981 clients = args[clientsIdx + 1];
4982 }
4983 parseClientsToWatchLocked(String8(clients));
4984
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004985 // track tags to initialize future clients with the monitoring information
4986 mMonitorTags = String8(tags);
4987
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004988 bool serviceLock = tryLock(mServiceLock);
4989 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004990 auto cameraClients = mActiveClientManager.getAll();
4991 for (const auto &clientDescriptor: cameraClients) {
4992 if (clientDescriptor == nullptr) { continue; }
4993 sp<BasicClient> client = clientDescriptor->getValue();
4994 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004995
4996 if (isClientWatchedLocked(client.get())) {
4997 client->startWatchingTags(mMonitorTags, outFd);
4998 numWatchedClients++;
4999 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005000 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005001 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
5002
5003 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005004 return OK;
5005}
5006
5007status_t CameraService::stopWatchingTags(int outFd) {
5008 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005009 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005010 mMonitorTags = String8::empty();
5011
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005012 mWatchedClientPackages.clear();
5013 mWatchedClientsDumpCache.clear();
5014
5015 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005016 auto cameraClients = mActiveClientManager.getAll();
5017 for (const auto &clientDescriptor : cameraClients) {
5018 if (clientDescriptor == nullptr) { continue; }
5019 sp<BasicClient> client = clientDescriptor->getValue();
5020 if (client.get() == nullptr) { continue; }
5021 client->stopWatchingTags(outFd);
5022 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005023 dprintf(outFd, "Stopped watching all clients.\n");
5024 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005025 return OK;
5026}
5027
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005028status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
5029 Mutex::Autolock lock(mLogLock);
5030 size_t clearedSize = mWatchedClientsDumpCache.size();
5031 mWatchedClientsDumpCache.clear();
5032 dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
5033 return OK;
5034}
5035
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005036status_t CameraService::printWatchedTags(int outFd) {
5037 Mutex::Autolock logLock(mLogLock);
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08005038 std::set<String16> connectedMonitoredClients;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005039
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005040 bool printedSomething = false; // tracks if any monitoring information was printed
5041 // (from either cached or active clients)
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005042
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005043 bool serviceLock = tryLock(mServiceLock);
5044 // get all watched clients that are currently connected
5045 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
5046 if (clientDescriptor == nullptr) { continue; }
5047
5048 sp<BasicClient> client = clientDescriptor->getValue();
5049 if (client.get() == nullptr) { continue; }
5050 if (!isClientWatchedLocked(client.get())) { continue; }
5051
5052 std::vector<std::string> dumpVector;
5053 client->dumpWatchedEventsToVector(dumpVector);
5054
5055 size_t printIdx = dumpVector.size();
5056 if (printIdx == 0) {
5057 continue;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005058 }
5059
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005060 // Print tag dumps for active client
5061 const String8 &cameraId = clientDescriptor->getKey();
5062 String8 packageName8 = String8(client->getPackageName());
5063 const char *printablePackageName = packageName8.lockBuffer(packageName8.size());
5064 dprintf(outFd, "Client: %s (active)\n", printablePackageName);
5065 while(printIdx > 0) {
5066 printIdx--;
5067 dprintf(outFd, "%s:%s %s", cameraId.string(), printablePackageName,
5068 dumpVector[printIdx].c_str());
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005069 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005070 dprintf(outFd, "\n");
5071 packageName8.unlockBuffer();
5072 printedSomething = true;
5073
5074 connectedMonitoredClients.emplace(client->getPackageName());
5075 }
5076 if (serviceLock) { mServiceLock.unlock(); }
5077
5078 // Print entries in mWatchedClientsDumpCache for clients that are not connected
5079 for (const auto &kv: mWatchedClientsDumpCache) {
5080 const String16 &package = kv.first;
5081 if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
5082 continue;
5083 }
5084
5085 dprintf(outFd, "Client: %s (cached)\n", String8(package).string());
5086 dprintf(outFd, "%s\n", kv.second.c_str());
5087 printedSomething = true;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005088 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005089
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005090 if (!printedSomething) {
5091 dprintf(outFd, "No monitoring information to print.\n");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005092 }
5093
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005094 return OK;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005095}
5096
Avichal Rakesh84147132021-11-11 17:47:11 -08005097// Print all events in vector `events' that came after lastPrintedEvent
5098void printNewWatchedEvents(int outFd,
5099 const char *cameraId,
5100 const String16 &packageName,
5101 const std::vector<std::string> &events,
5102 const std::string &lastPrintedEvent) {
5103 if (events.empty()) { return; }
5104
5105 // index of lastPrintedEvent in events.
5106 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
5107 size_t lastPrintedIdx;
5108 for (lastPrintedIdx = 0;
5109 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
5110 lastPrintedIdx++);
5111
5112 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
5113
5114 String8 packageName8(packageName);
5115 const char *printablePackageName = packageName8.lockBuffer(packageName8.size());
5116
5117 // print events in chronological order (latest event last)
5118 size_t idxToPrint = lastPrintedIdx;
5119 do {
5120 idxToPrint--;
5121 dprintf(outFd, "%s:%s %s", cameraId, printablePackageName, events[idxToPrint].c_str());
5122 } while (idxToPrint != 0);
5123
5124 packageName8.unlockBuffer();
5125}
5126
5127// Returns true if adb shell cmd watch should be interrupted based on data in inFd. The watch
5128// command should be interrupted if the user presses the return key, or if user loses any way to
5129// signal interrupt.
5130// If timeoutMs == 0, this function will always return false
5131bool shouldInterruptWatchCommand(int inFd, int outFd, long timeoutMs) {
5132 struct timeval startTime;
5133 int startTimeError = gettimeofday(&startTime, nullptr);
5134 if (startTimeError) {
5135 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
5136 return true;
5137 }
5138
5139 const nfds_t numFds = 1;
5140 struct pollfd pollFd = { .fd = inFd, .events = POLLIN, .revents = 0 };
5141
5142 struct timeval currTime;
5143 char buffer[2];
5144 while(true) {
5145 int currTimeError = gettimeofday(&currTime, nullptr);
5146 if (currTimeError) {
5147 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
5148 return true;
5149 }
5150
5151 long elapsedTimeMs = ((currTime.tv_sec - startTime.tv_sec) * 1000L)
5152 + ((currTime.tv_usec - startTime.tv_usec) / 1000L);
5153 int remainingTimeMs = (int) (timeoutMs - elapsedTimeMs);
5154
5155 if (remainingTimeMs <= 0) {
5156 // No user interrupt within timeoutMs, don't interrupt watch command
5157 return false;
5158 }
5159
5160 int numFdsUpdated = poll(&pollFd, numFds, remainingTimeMs);
5161 if (numFdsUpdated < 0) {
5162 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
5163 return true;
5164 }
5165
5166 if (numFdsUpdated == 0) {
5167 // No user input within timeoutMs, don't interrupt watch command
5168 return false;
5169 }
5170
5171 if (!(pollFd.revents & POLLIN)) {
5172 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
5173 return true;
5174 }
5175
5176 ssize_t sizeRead = read(inFd, buffer, sizeof(buffer) - 1);
5177 if (sizeRead < 0) {
5178 dprintf(outFd, "Error reading user input. Exiting.\n");
5179 return true;
5180 }
5181
5182 if (sizeRead == 0) {
5183 // Reached end of input fd (can happen if input is piped)
5184 // User has no way to signal an interrupt, so interrupt here
5185 return true;
5186 }
5187
5188 if (buffer[0] == '\n') {
5189 // User pressed return, interrupt watch command.
5190 return true;
5191 }
5192 }
5193}
5194
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005195status_t CameraService::printWatchedTagsUntilInterrupt(const Vector<String16> &args,
5196 int inFd, int outFd) {
5197 // Figure out refresh interval, if present in args
5198 long refreshTimeoutMs = 1000L; // refresh every 1s by default
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005199 if (args.size() > 2) {
5200 size_t intervalIdx; // index of '-n'
5201 for (intervalIdx = 2; intervalIdx < args.size() && String16("-n") != args[intervalIdx];
5202 intervalIdx++);
5203
5204 size_t intervalValIdx = intervalIdx + 1;
5205 if (intervalValIdx < args.size()) {
5206 refreshTimeoutMs = strtol(String8(args[intervalValIdx].string()), nullptr, 10);
5207 if (errno) { return BAD_VALUE; }
5208 }
5209 }
5210
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005211 // Set min timeout of 10ms. This prevents edge cases in polling when timeout of 0 is passed.
5212 refreshTimeoutMs = refreshTimeoutMs < 10 ? 10 : refreshTimeoutMs;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005213
Avichal Rakesh84147132021-11-11 17:47:11 -08005214 dprintf(outFd, "Press return to exit...\n\n");
Avichal Rakesha14d9832021-11-11 01:41:55 -08005215 std::map<String16, std::string> packageNameToLastEvent;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005216
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005217 while (true) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08005218 bool serviceLock = tryLock(mServiceLock);
5219 auto cameraClients = mActiveClientManager.getAll();
5220 if (serviceLock) { mServiceLock.unlock(); }
5221
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005222 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005223 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005224 if (clientDescriptor == nullptr) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005225
5226 sp<BasicClient> client = clientDescriptor->getValue();
5227 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005228 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005229
Avichal Rakesha14d9832021-11-11 01:41:55 -08005230 const String16 &packageName = client->getPackageName();
5231 // This also initializes the map entries with an empty string
5232 const std::string& lastPrintedEvent = packageNameToLastEvent[packageName];
5233
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005234 std::vector<std::string> latestEvents;
5235 client->dumpWatchedEventsToVector(latestEvents);
5236
5237 if (!latestEvents.empty()) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08005238 String8 cameraId = clientDescriptor->getKey();
5239 const char *printableCameraId = cameraId.lockBuffer(cameraId.size());
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005240 printNewWatchedEvents(outFd,
Avichal Rakesha14d9832021-11-11 01:41:55 -08005241 printableCameraId,
5242 packageName,
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005243 latestEvents,
5244 lastPrintedEvent);
Avichal Rakesha14d9832021-11-11 01:41:55 -08005245 packageNameToLastEvent[packageName] = latestEvents[0];
5246 cameraId.unlockBuffer();
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005247 }
5248 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005249 if (shouldInterruptWatchCommand(inFd, outFd, refreshTimeoutMs)) {
Avichal Rakesh84147132021-11-11 17:47:11 -08005250 break;
5251 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005252 }
5253 return OK;
5254}
5255
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005256void CameraService::parseClientsToWatchLocked(String8 clients) {
5257 mWatchedClientPackages.clear();
5258
5259 const char *allSentinel = String8(kWatchAllClientsFlag).string();
5260
5261 char *tokenized = clients.lockBuffer(clients.size());
5262 char *savePtr;
5263 char *nextClient = strtok_r(tokenized, ",", &savePtr);
5264
5265 while (nextClient != nullptr) {
5266 if (strcmp(nextClient, allSentinel) == 0) {
5267 // Don't need to track any other package if 'all' is present
5268 mWatchedClientPackages.clear();
5269 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
5270 break;
5271 }
5272
5273 // track package names
5274 mWatchedClientPackages.emplace(nextClient);
5275 nextClient = strtok_r(nullptr, ",", &savePtr);
5276 }
5277 clients.unlockBuffer();
5278}
5279
Svet Ganova453d0d2018-01-11 15:37:58 -08005280status_t CameraService::printHelp(int out) {
5281 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07005282 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
5283 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
5284 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005285 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
5286 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
5287 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005288 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
5289 " Valid values 0=OFF, 1=ON for JPEG\n"
5290 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005291 " set-camera-mute <0/1> enable or disable camera muting\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005292 " watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08005293 " help print this message\n");
5294}
5295
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005296bool CameraService::isClientWatched(const BasicClient *client) {
5297 Mutex::Autolock lock(mLogLock);
5298 return isClientWatchedLocked(client);
5299}
5300
5301bool CameraService::isClientWatchedLocked(const BasicClient *client) {
5302 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
5303 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
5304}
5305
Yin-Chia Yehdba03232019-08-19 15:54:28 -07005306int32_t CameraService::updateAudioRestriction() {
5307 Mutex::Autolock lock(mServiceLock);
5308 return updateAudioRestrictionLocked();
5309}
5310
5311int32_t CameraService::updateAudioRestrictionLocked() {
5312 int32_t mode = 0;
5313 // iterate through all active client
5314 for (const auto& i : mActiveClientManager.getAll()) {
5315 const auto clientSp = i->getValue();
5316 mode |= clientSp->getAudioRestriction();
5317 }
5318
5319 bool modeChanged = (mAudioRestriction != mode);
5320 mAudioRestriction = mode;
5321 if (modeChanged) {
5322 mAppOps.setCameraAudioRestriction(mode);
5323 }
5324 return mode;
5325}
5326
Cliff Wu646bd612021-11-23 23:21:29 +08005327status_t CameraService::checkIfInjectionCameraIsPresent(const String8& externalCamId,
5328 sp<BasicClient> clientSp) {
5329 std::unique_ptr<AutoConditionLock> lock =
5330 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
5331 status_t res = NO_ERROR;
5332 if ((res = checkIfDeviceIsUsable(externalCamId)) != NO_ERROR) {
5333 ALOGW("Device %s is not usable!", externalCamId.string());
5334 mInjectionStatusListener->notifyInjectionError(
5335 externalCamId, UNKNOWN_TRANSACTION);
5336 clientSp->notifyError(
5337 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
5338 CaptureResultExtras());
5339
5340 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
5341 // other clients from connecting in mServiceLockWrapper if held
5342 mServiceLock.unlock();
5343
5344 // Clear caller identity temporarily so client disconnect PID checks work correctly
5345 int64_t token = CameraThreadState::clearCallingIdentity();
5346 clientSp->disconnect();
5347 CameraThreadState::restoreCallingIdentity(token);
5348
5349 // Reacquire mServiceLock
5350 mServiceLock.lock();
5351 }
5352
5353 return res;
5354}
5355
Cliff Wud3a05312021-04-26 23:07:31 +08005356void CameraService::clearInjectionParameters() {
5357 {
5358 Mutex::Autolock lock(mInjectionParametersLock);
Cliff Wu646bd612021-11-23 23:21:29 +08005359 mInjectionInitPending = false;
Cliff Wud3a05312021-04-26 23:07:31 +08005360 mInjectionInternalCamId = "";
5361 }
5362 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08005363 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08005364}
5365
Mathias Agopian65ab4712010-07-14 17:59:35 -07005366}; // namespace android