blob: 8147701b6b5259113de27ebc11866c0ed9dc5c2e [file] [log] [blame]
Mathias Agopian65ab4712010-07-14 17:59:35 -07001/*
Ruben Brunkd1176ef2014-02-21 10:51:38 -08002 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Mathias Agopian65ab4712010-07-14 17:59:35 -070016
17#define LOG_TAG "CameraService"
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -070018#define ATRACE_TAG ATRACE_TAG_CAMERA
Iliyan Malchev8951a972011-04-14 16:55:59 -070019//#define LOG_NDEBUG 0
Mathias Agopian65ab4712010-07-14 17:59:35 -070020
Ruben Brunkcc776712015-02-17 20:18:47 -080021#include <algorithm>
22#include <climits>
Mathias Agopian65ab4712010-07-14 17:59:35 -070023#include <stdio.h>
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -080024#include <cstdlib>
Ruben Brunkcc776712015-02-17 20:18:47 -080025#include <cstring>
26#include <ctime>
27#include <string>
Mathias Agopian65ab4712010-07-14 17:59:35 -070028#include <sys/types.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080029#include <inttypes.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070030#include <pthread.h>
Avichal Rakesh84147132021-11-11 17:47:11 -080031#include <poll.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070032
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080033#include <android/hardware/ICamera.h>
34#include <android/hardware/ICameraClient.h>
35
Alex Deymo9c2a2c22016-08-25 11:59:14 -070036#include <android-base/macros.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080037#include <android-base/parseint.h>
Jayant Chowdharyb61526c2019-05-13 19:37:42 -070038#include <android-base/stringprintf.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080039#include <binder/ActivityManager.h>
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -080040#include <binder/AppOpsManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070041#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070042#include <binder/MemoryBase.h>
43#include <binder/MemoryHeapBase.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080044#include <binder/PermissionController.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080045#include <binder/IResultReceiver.h>
Steven Moreland89a2c5c2020-01-31 15:02:25 -080046#include <binderthreadstate/CallerUtils.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070047#include <cutils/atomic.h>
Nipun Kwatrab5ca4612010-09-11 19:31:10 -070048#include <cutils/properties.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080049#include <cutils/misc.h>
Mathias Agopiandf712ea2012-02-25 18:48:35 -080050#include <gui/Surface.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070051#include <hardware/hardware.h>
Jayant Chowdharybe543d42018-08-15 13:16:14 -070052#include "hidl/HidlCameraService.h"
53#include <hidl/HidlTransportSupport.h>
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -080054#include <hwbinder/IPCThreadState.h>
Eino-Ville Talvalad89821e2016-04-20 11:23:50 -070055#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070056#include <media/AudioSystem.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080057#include <media/IMediaHTTPService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070058#include <media/mediaplayer.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070059#include <mediautils/BatteryNotifier.h>
Steven Moreland886d7322021-04-02 04:19:45 +000060#include <processinfo/ProcessInfoService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070061#include <utils/Errors.h>
62#include <utils/Log.h>
63#include <utils/String16.h>
Svet Ganov94ec46f2018-06-08 15:03:46 -070064#include <utils/SystemClock.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080065#include <utils/Trace.h>
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080066#include <utils/CallStack.h>
Chien-Yu Chen98a668f2015-12-18 14:10:33 -080067#include <private/android_filesystem_config.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080068#include <system/camera_vendor_tags.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070069#include <system/camera_metadata.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080070
Ruben Brunkb2119af2014-05-09 19:57:56 -070071#include <system/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070072
73#include "CameraService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070074#include "api1/Camera2Client.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070075#include "api2/CameraDeviceClient.h"
Igor Murashkinff3e31d2013-10-23 16:40:06 -070076#include "utils/CameraTraces.h"
Emilian Peevbd8c5032018-02-14 23:05:40 +000077#include "utils/TagMonitor.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070078#include "utils/CameraThreadState.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070079#include "utils/CameraServiceProxyWrapper.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070080
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080081namespace {
82 const char* kPermissionServiceName = "permission";
83}; // namespace anonymous
84
Mathias Agopian65ab4712010-07-14 17:59:35 -070085namespace android {
86
Jayant Chowdharyb61526c2019-05-13 19:37:42 -070087using base::StringPrintf;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080088using binder::Status;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -070089using camera3::SessionConfigurationUtils;
Jayant Chowdharybe543d42018-08-15 13:16:14 -070090using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -080091using hardware::ICamera;
92using hardware::ICameraClient;
93using hardware::ICameraServiceListener;
94using hardware::camera::common::V1_0::CameraDeviceStatus;
95using hardware::camera::common::V1_0::TorchModeStatus;
Cliff Wud8cae102021-03-11 01:37:42 +080096using hardware::camera2::ICameraInjectionCallback;
97using hardware::camera2::ICameraInjectionSession;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080098using hardware::camera2::utils::CameraIdAndSessionConfiguration;
99using hardware::camera2::utils::ConcurrentCameraIdCombination;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800100
Mathias Agopian65ab4712010-07-14 17:59:35 -0700101// ----------------------------------------------------------------------------
102// Logging support -- this is for debugging only
103// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700104volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700105
Steve Blockb8a80522011-12-20 16:23:08 +0000106#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
107#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700108
109static void setLogLevel(int level) {
110 android_atomic_write(level, &gLogLevel);
111}
112
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800113// Convenience methods for constructing binder::Status objects for error returns
114
115#define STATUS_ERROR(errorCode, errorString) \
116 binder::Status::fromServiceSpecificError(errorCode, \
117 String8::format("%s:%d: %s", __FUNCTION__, __LINE__, errorString))
118
119#define STATUS_ERROR_FMT(errorCode, errorString, ...) \
120 binder::Status::fromServiceSpecificError(errorCode, \
121 String8::format("%s:%d: " errorString, __FUNCTION__, __LINE__, \
122 __VA_ARGS__))
123
Mathias Agopian65ab4712010-07-14 17:59:35 -0700124// ----------------------------------------------------------------------------
125
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700126static const String16 sDumpPermission("android.permission.DUMP");
Svet Ganova453d0d2018-01-11 15:37:58 -0800127static const String16 sManageCameraPermission("android.permission.MANAGE_CAMERA");
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700128static const String16 sCameraPermission("android.permission.CAMERA");
129static const String16 sSystemCameraPermission("android.permission.SYSTEM_CAMERA");
130static const String16
131 sCameraSendSystemEventsPermission("android.permission.CAMERA_SEND_SYSTEM_EVENTS");
Shuzhen Wang695044d2020-03-06 09:02:23 -0800132static const String16 sCameraOpenCloseListenerPermission(
133 "android.permission.CAMERA_OPEN_CLOSE_LISTENER");
Cliff Wud8cae102021-03-11 01:37:42 +0800134static const String16
135 sCameraInjectExternalCameraPermission("android.permission.CAMERA_INJECT_EXTERNAL_CAMERA");
Rucha Katakwardf223072021-06-15 10:21:00 -0700136const char *sFileName = "lastOpenSessionDumpFile";
Eino-Ville Talvala7c602c32021-03-20 17:00:18 -0700137static constexpr int32_t kVendorClientScore = resource_policy::PERCEPTIBLE_APP_ADJ;
138static constexpr int32_t kVendorClientState = ActivityManager::PROCESS_STATE_PERSISTENT_UI;
139
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800140const String8 CameraService::kOfflineDevice("offline-");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -0700141const String16 CameraService::kWatchAllClientsFlag("all");
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700142
Rucha Katakward9ea6452021-05-06 11:57:16 -0700143// Set to keep track of logged service error events.
144static std::set<String8> sServiceErrorEventSet;
145
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800146CameraService::CameraService() :
147 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800148 mNumberOfCameras(0),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700149 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700150 mSoundRef(0), mInitialized(false),
151 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000152 ALOGI("CameraService started (pid=%d)", getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800153 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Rucha Katakwardf223072021-06-15 10:21:00 -0700154 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
155 if (mMemFd == -1) {
156 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
157 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700158}
159
Iliyan Malchev8951a972011-04-14 16:55:59 -0700160void CameraService::onFirstRef()
161{
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -0700162
Ruben Brunkcc776712015-02-17 20:18:47 -0800163 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800164
Iliyan Malchev8951a972011-04-14 16:55:59 -0700165 BnCameraService::onFirstRef();
166
Ruben Brunk99e69712015-05-26 17:25:07 -0700167 // Update battery life tracking if service is restarting
168 BatteryNotifier& notifier(BatteryNotifier::getInstance());
169 notifier.noteResetCamera();
170 notifier.noteResetFlashlight();
171
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800172 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800173
Emilian Peevf53f66e2017-04-11 14:29:43 +0100174 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800175 if (res == OK) {
176 mInitialized = true;
177 }
178
Svet Ganova453d0d2018-01-11 15:37:58 -0800179 mUidPolicy = new UidPolicy(this);
180 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800181 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
182 mSensorPrivacyPolicy->registerSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800183 mInjectionStatusListener = new InjectionStatusListener(this);
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700184 mAppOps.setCameraAudioRestriction(mAudioRestriction);
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700185 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
186 if (hcs->registerAsService() != android::OK) {
187 ALOGE("%s: Failed to register default android.frameworks.cameraservice.service@1.0",
188 __FUNCTION__);
189 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700190
191 // This needs to be last call in this function, so that it's as close to
192 // ServiceManager::addService() as possible.
Shuzhen Wang316781a2020-08-18 18:11:01 -0700193 CameraServiceProxyWrapper::pingCameraServiceProxy();
Shuzhen Wang24b44152019-09-20 10:38:11 -0700194 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800195}
196
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800197status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800198 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100199
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800200 std::vector<std::string> deviceIds;
201 {
202 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800203
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800204 if (nullptr == mCameraProviderManager.get()) {
205 mCameraProviderManager = new CameraProviderManager();
206 res = mCameraProviderManager->initialize(this);
207 if (res != OK) {
208 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
209 __FUNCTION__, strerror(-res), res);
Rucha Katakward9ea6452021-05-06 11:57:16 -0700210 logServiceError(String8::format("Unable to initialize camera provider manager"),
211 ERROR_DISCONNECTED);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800212 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100213 }
214 }
215
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800216
217 // Setup vendor tags before we call get_camera_info the first time
218 // because HAL might need to setup static vendor keys in get_camera_info
219 // TODO: maybe put this into CameraProviderManager::initialize()?
220 mCameraProviderManager->setUpVendorTags();
221
222 if (nullptr == mFlashlight.get()) {
223 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700224 }
225
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800226 res = mFlashlight->findFlashUnits();
227 if (res != OK) {
228 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
229 }
230
231 deviceIds = mCameraProviderManager->getCameraDeviceIds();
232 }
233
234
235 for (auto& cameraId : deviceIds) {
236 String8 id8 = String8(cameraId.c_str());
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800237 if (getCameraState(id8) == nullptr) {
238 onDeviceStatusChanged(id8, CameraDeviceStatus::PRESENT);
239 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800240 }
241
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700242 // Derive primary rear/front cameras, and filter their charactierstics.
243 // This needs to be done after all cameras are enumerated and camera ids are sorted.
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700244 if (SessionConfigurationUtils::IS_PERF_CLASS) {
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700245 // Assume internal cameras are advertised from the same
246 // provider. If multiple providers are registered at different time,
247 // and each provider contains multiple internal color cameras, the current
248 // logic may filter the characteristics of more than one front/rear color
249 // cameras.
250 Mutex::Autolock l(mServiceLock);
251 filterSPerfClassCharacteristicsLocked();
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700252 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700253
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800254 return OK;
255}
256
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700257void CameraService::broadcastTorchModeStatus(const String8& cameraId, TorchModeStatus status,
258 SystemCameraKind systemCameraKind) {
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800259 Mutex::Autolock lock(mStatusListenerLock);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800260 for (auto& i : mListenerList) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700261 if (shouldSkipStatusUpdates(systemCameraKind, i->isVendorListener(), i->getListenerPid(),
262 i->getListenerUid())) {
263 ALOGV("Skipping torch callback for system-only camera device %s",
264 cameraId.c_str());
265 continue;
266 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700267 i->getListener()->onTorchStatusChanged(mapToInterface(status), String16{cameraId});
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800268 }
269}
270
Mathias Agopian65ab4712010-07-14 17:59:35 -0700271CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800272 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800273 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800274 mSensorPrivacyPolicy->unregisterSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800275 mInjectionStatusListener->removeListener();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700276}
277
Emilian Peevaee727d2017-05-04 16:35:48 +0100278void CameraService::onNewProviderRegistered() {
279 enumerateProviders();
280}
281
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700282void CameraService::filterAPI1SystemCameraLocked(
283 const std::vector<std::string> &normalDeviceIds) {
284 mNormalDeviceIdsWithoutSystemCamera.clear();
285 for (auto &deviceId : normalDeviceIds) {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700286 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
287 if (getSystemCameraKind(String8(deviceId.c_str()), &deviceKind) != OK) {
288 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, deviceId.c_str());
289 continue;
290 }
291 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700292 // All system camera ids will necessarily come after public camera
293 // device ids as per the HAL interface contract.
294 break;
295 }
296 mNormalDeviceIdsWithoutSystemCamera.push_back(deviceId);
297 }
298 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
299 mNormalDeviceIdsWithoutSystemCamera.size());
300}
301
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700302status_t CameraService::getSystemCameraKind(const String8& cameraId, SystemCameraKind *kind) const {
303 auto state = getCameraState(cameraId);
304 if (state != nullptr) {
305 *kind = state->getSystemCameraKind();
306 return OK;
307 }
308 // Hidden physical camera ids won't have CameraState
309 return mCameraProviderManager->getSystemCameraKind(cameraId.c_str(), kind);
310}
311
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800312void CameraService::updateCameraNumAndIds() {
313 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700314 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
315 // Excludes hidden secure cameras
316 mNumberOfCameras =
317 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
318 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800319 mNormalDeviceIds =
320 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700321 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800322}
323
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700324void CameraService::filterSPerfClassCharacteristicsLocked() {
Shuzhen Wang89db2992021-05-20 13:09:48 -0700325 // To claim to be S Performance primary cameras, the cameras must be
326 // backward compatible. So performance class primary camera Ids must be API1
327 // compatible.
328 bool firstRearCameraSeen = false, firstFrontCameraSeen = false;
329 for (const auto& cameraId : mNormalDeviceIdsWithoutSystemCamera) {
330 int facing = -1;
331 int orientation = 0;
332 String8 cameraId8(cameraId.c_str());
333 getDeviceVersion(cameraId8, /*out*/&facing, /*out*/&orientation);
334 if (facing == -1) {
335 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
336 return;
337 }
338
339 if ((facing == hardware::CAMERA_FACING_BACK && !firstRearCameraSeen) ||
340 (facing == hardware::CAMERA_FACING_FRONT && !firstFrontCameraSeen)) {
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700341 status_t res = mCameraProviderManager->filterSmallJpegSizes(cameraId);
342 if (res == OK) {
343 mPerfClassPrimaryCameraIds.insert(cameraId);
344 } else {
345 ALOGE("%s: Failed to filter small JPEG sizes for performance class primary "
346 "camera %s: %s(%d)", __FUNCTION__, cameraId.c_str(), strerror(-res), res);
347 break;
348 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700349
350 if (facing == hardware::CAMERA_FACING_BACK) {
351 firstRearCameraSeen = true;
352 }
353 if (facing == hardware::CAMERA_FACING_FRONT) {
354 firstFrontCameraSeen = true;
355 }
356 }
357
358 if (firstRearCameraSeen && firstFrontCameraSeen) {
359 break;
360 }
361 }
362}
363
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100364void CameraService::addStates(const String8 id) {
365 std::string cameraId(id.c_str());
366 hardware::camera::common::V1_0::CameraResourceCost cost;
367 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700368 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100369 if (res != OK) {
370 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
371 return;
372 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700373 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
374 if (res != OK) {
375 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
376 return;
377 }
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100378 std::set<String8> conflicting;
379 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
380 conflicting.emplace(String8(cost.conflictingDevices[i].c_str()));
381 }
382
383 {
384 Mutex::Autolock lock(mCameraStatesLock);
385 mCameraStates.emplace(id, std::make_shared<CameraState>(id, cost.resourceCost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700386 conflicting, deviceKind));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100387 }
388
389 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100390 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100391 mTorchStatusMap.add(id, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800392
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700393 broadcastTorchModeStatus(id, TorchModeStatus::AVAILABLE_OFF, deviceKind);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100394 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800395
396 updateCameraNumAndIds();
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100397 logDeviceAdded(id, "Device added");
398}
399
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100400void CameraService::removeStates(const String8 id) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800401 updateCameraNumAndIds();
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100402 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100403 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100404 mTorchStatusMap.removeItem(id);
405 }
406
407 {
408 Mutex::Autolock lock(mCameraStatesLock);
409 mCameraStates.erase(id);
410 }
411}
412
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800413void CameraService::onDeviceStatusChanged(const String8& id,
414 CameraDeviceStatus newHalStatus) {
415 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
416 id.string(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700417
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800418 StatusInternal newStatus = mapToInternal(newHalStatus);
419
Ruben Brunkcc776712015-02-17 20:18:47 -0800420 std::shared_ptr<CameraState> state = getCameraState(id);
421
422 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700423 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100424 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700425 __FUNCTION__, id.string());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100426
427 // First add as absent to make sure clients are notified below
428 addStates(id);
429
430 updateStatus(newStatus, id);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700431 } else {
432 ALOGE("%s: Bad camera ID %s", __FUNCTION__, id.string());
433 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700434 return;
435 }
436
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800437 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800438
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800439 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800440 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700441 return;
442 }
443
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800444 if (newStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700445 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
446 newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800447
448 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
449 // to this device until the status changes
450 updateStatus(StatusInternal::NOT_PRESENT, id);
451
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800452 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700453 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800454 // Don't do this in updateStatus to avoid deadlock over mServiceLock
455 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700456
Ruben Brunkcc776712015-02-17 20:18:47 -0800457 // Remove cached shim parameters
458 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700459
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800460 // Remove online as well as offline client from the list of active clients,
461 // if they are present
462 clientToDisconnectOnline = removeClientLocked(id);
463 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + id);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700464 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800465
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800466 disconnectClient(id, clientToDisconnectOnline);
467 disconnectClient(kOfflineDevice + id, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700468
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100469 removeStates(id);
Ruben Brunkcc776712015-02-17 20:18:47 -0800470 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800471 if (oldStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700472 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
473 newStatus));
474 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800475 updateStatus(newStatus, id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700476 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800477}
Igor Murashkincba2c162013-03-20 15:56:31 -0700478
Shuzhen Wang43858162020-01-10 13:42:15 -0800479void CameraService::onDeviceStatusChanged(const String8& id,
480 const String8& physicalId,
481 CameraDeviceStatus newHalStatus) {
482 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
483 __FUNCTION__, id.string(), physicalId.string(), newHalStatus);
484
485 StatusInternal newStatus = mapToInternal(newHalStatus);
486
487 std::shared_ptr<CameraState> state = getCameraState(id);
488
489 if (state == nullptr) {
490 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
491 __FUNCTION__, id.string(), physicalId.string());
492 return;
493 }
494
495 StatusInternal logicalCameraStatus = state->getStatus();
496 if (logicalCameraStatus != StatusInternal::PRESENT &&
497 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
498 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
499 __FUNCTION__, physicalId.string(), newHalStatus, logicalCameraStatus);
500 return;
501 }
502
503 bool updated = false;
504 if (newStatus == StatusInternal::PRESENT) {
505 updated = state->removeUnavailablePhysicalId(physicalId);
506 } else {
507 updated = state->addUnavailablePhysicalId(physicalId);
508 }
509
510 if (updated) {
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800511 String8 idCombo = id + " : " + physicalId;
512 if (newStatus == StatusInternal::PRESENT) {
513 logDeviceAdded(idCombo,
514 String8::format("Device status changed to %d", newStatus));
515 } else {
516 logDeviceRemoved(idCombo,
517 String8::format("Device status changed to %d", newStatus));
518 }
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700519 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
520 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
521 if (getSystemCameraKind(id, &deviceKind) != OK) {
522 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.string());
523 return;
524 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800525 String16 id16(id), physicalId16(physicalId);
526 Mutex::Autolock lock(mStatusListenerLock);
527 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700528 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
529 listener->getListenerPid(), listener->getListenerUid())) {
530 ALOGV("Skipping discovery callback for system-only camera device %s",
531 id.c_str());
532 continue;
533 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800534 listener->getListener()->onPhysicalCameraStatusChanged(mapToInterface(newStatus),
535 id16, physicalId16);
536 }
537 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700538}
539
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800540void CameraService::disconnectClient(const String8& id, sp<BasicClient> clientToDisconnect) {
541 if (clientToDisconnect.get() != nullptr) {
542 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
543 __FUNCTION__, id.string());
544 // Notify the client of disconnection
545 clientToDisconnect->notifyError(
546 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
547 CaptureResultExtras{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800548 clientToDisconnect->disconnect();
549 }
550}
551
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800552void CameraService::onTorchStatusChanged(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800553 TorchModeStatus newStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700554 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
555 status_t res = getSystemCameraKind(cameraId, &systemCameraKind);
556 if (res != OK) {
557 ALOGE("%s: Could not get system camera kind for camera id %s", __FUNCTION__,
558 cameraId.string());
559 return;
560 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800561 Mutex::Autolock al(mTorchStatusMutex);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700562 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800563}
564
Jayant Chowdhary46ef0f52021-10-05 14:36:13 -0700565
566void CameraService::onTorchStatusChanged(const String8& cameraId,
567 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
568 Mutex::Autolock al(mTorchStatusMutex);
569 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
570}
571
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800572void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700573 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800574 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
575 __FUNCTION__, cameraId.string(), newStatus);
576
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800577 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800578 status_t res = getTorchStatusLocked(cameraId, &status);
579 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700580 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
581 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800582 return;
583 }
584 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800585 return;
586 }
587
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800588 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800589 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800590 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
591 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800592 return;
593 }
594
Ruben Brunkcc776712015-02-17 20:18:47 -0800595 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700596 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700597 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700598 auto iter = mTorchUidMap.find(cameraId);
599 if (iter != mTorchUidMap.end()) {
600 int oldUid = iter->second.second;
601 int newUid = iter->second.first;
602 BatteryNotifier& notifier(BatteryNotifier::getInstance());
603 if (oldUid != newUid) {
604 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800605 if (status == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700606 notifier.noteFlashlightOff(cameraId, oldUid);
607 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800608 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700609 notifier.noteFlashlightOn(cameraId, newUid);
610 }
611 iter->second.second = newUid;
612 } else {
613 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800614 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700615 notifier.noteFlashlightOn(cameraId, oldUid);
616 } else {
617 notifier.noteFlashlightOff(cameraId, oldUid);
618 }
619 }
620 }
621 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700622 broadcastTorchModeStatus(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800623}
624
Jayant Chowdharyc3198c32021-07-28 20:59:14 +0000625static bool hasPermissionsForSystemCamera(int callingPid, int callingUid,
626 bool logPermissionFailure = false) {
627 return checkPermission(sSystemCameraPermission, callingPid, callingUid,
628 logPermissionFailure) &&
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700629 checkPermission(sCameraPermission, callingPid, callingUid);
630}
631
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800632Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700633 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100634 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700635 bool hasSystemCameraPermissions =
636 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
637 CameraThreadState::getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700638 switch (type) {
639 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700640 if (hasSystemCameraPermissions) {
641 *numCameras = static_cast<int>(mNormalDeviceIds.size());
642 } else {
643 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
644 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800645 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700646 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700647 if (hasSystemCameraPermissions) {
648 *numCameras = mNumberOfCameras;
649 } else {
650 *numCameras = mNumberOfCamerasWithoutSystemCamera;
651 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800652 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700653 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800654 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700655 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800656 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
657 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700658 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800659 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700660}
661
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800662Status CameraService::getCameraInfo(int cameraId,
663 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700664 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100665 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700666 std::string cameraIdStr = cameraIdIntToStrLocked(cameraId);
667 if (shouldRejectSystemCameraConnection(String8(cameraIdStr.c_str()))) {
668 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
669 "characteristics for system only device %s: ", cameraIdStr.c_str());
670 }
Emilian Peevaee727d2017-05-04 16:35:48 +0100671
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800672 if (!mInitialized) {
Rucha Katakward9ea6452021-05-06 11:57:16 -0700673 logServiceError(String8::format("Camera subsystem is not available"),ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800674 return STATUS_ERROR(ERROR_DISCONNECTED,
675 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -0700676 }
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700677 bool hasSystemCameraPermissions =
678 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
679 CameraThreadState::getCallingUid());
680 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
681 if (hasSystemCameraPermissions) {
682 cameraIdBound = mNumberOfCameras;
683 }
684 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800685 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
686 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700687 }
688
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800689 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800690 status_t err = mCameraProviderManager->getCameraInfo(
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700691 cameraIdStr.c_str(), cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100692 if (err != OK) {
693 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
694 "Error retrieving camera info from device %d: %s (%d)", cameraId,
695 strerror(-err), err);
Rucha Katakward9ea6452021-05-06 11:57:16 -0700696 logServiceError(String8::format("Error retrieving camera info from device %d",cameraId),
697 ERROR_INVALID_OPERATION);
Ruben Brunkcc776712015-02-17 20:18:47 -0800698 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100699
Ruben Brunkcc776712015-02-17 20:18:47 -0800700 return ret;
701}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700702
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800703std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700704 const std::vector<std::string> *deviceIds = &mNormalDeviceIdsWithoutSystemCamera;
705 auto callingPid = CameraThreadState::getCallingPid();
706 auto callingUid = CameraThreadState::getCallingUid();
Jayant Chowdharyc3198c32021-07-28 20:59:14 +0000707 if (checkPermission(sSystemCameraPermission, callingPid, callingUid,
708 /*logPermissionFailure*/false) || getpid() == callingPid) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700709 deviceIds = &mNormalDeviceIds;
710 }
711 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(deviceIds->size())) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800712 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700713 __FUNCTION__, cameraIdInt, deviceIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800714 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800715 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800716
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700717 return (*deviceIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800718}
719
720String8 CameraService::cameraIdIntToStr(int cameraIdInt) {
721 Mutex::Autolock lock(mServiceLock);
722 return String8(cameraIdIntToStrLocked(cameraIdInt).c_str());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800723}
724
725Status CameraService::getCameraCharacteristics(const String16& cameraId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700726 int targetSdkVersion, CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700727 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700728 if (!cameraInfo) {
729 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800730 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -0700731 }
732
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800733 if (!mInitialized) {
734 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Rucha Katakward9ea6452021-05-06 11:57:16 -0700735 logServiceError(String8::format("Camera subsystem is not available"),ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800736 return STATUS_ERROR(ERROR_DISCONNECTED,
737 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -0700738 }
739
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700740 if (shouldRejectSystemCameraConnection(String8(cameraId))) {
741 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
742 "characteristics for system only device %s: ", String8(cameraId).string());
743 }
744
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800745 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800746
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700747
748 std::string cameraIdStr = String8(cameraId).string();
749 bool overrideForPerfClass =
750 SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
751 cameraIdStr, targetSdkVersion);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100752 status_t res = mCameraProviderManager->getCameraCharacteristics(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700753 cameraIdStr, overrideForPerfClass, cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100754 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700755 if (res == NAME_NOT_FOUND) {
756 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
757 "characteristics for unknown device %s: %s (%d)", String8(cameraId).string(),
758 strerror(-res), res);
759 } else {
Rucha Katakward9ea6452021-05-06 11:57:16 -0700760 logServiceError(String8::format("Unable to retrieve camera characteristics for "
761 "device %s.", String8(cameraId).string()),ERROR_INVALID_OPERATION);
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700762 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
763 "characteristics for device %s: %s (%d)", String8(cameraId).string(),
764 strerror(-res), res);
765 }
Ruben Brunkb2119af2014-05-09 19:57:56 -0700766 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700767 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
768 if (getSystemCameraKind(String8(cameraId), &deviceKind) != OK) {
769 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, String8(cameraId).string());
770 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera kind "
771 "for device %s", String8(cameraId).string());
772 }
Jayant Chowdhary12361932018-08-27 14:46:13 -0700773 int callingPid = CameraThreadState::getCallingPid();
774 int callingUid = CameraThreadState::getCallingUid();
Emilian Peeve20c6372018-08-14 18:45:53 +0100775 std::vector<int32_t> tagsRemoved;
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700776 // If it's not calling from cameraserver, check the permission only if
777 // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
778 // it would've already been checked in shouldRejectSystemCameraConnection.
Emilian Peeve20c6372018-08-14 18:45:53 +0100779 if ((callingPid != getpid()) &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700780 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700781 !checkPermission(sCameraPermission, callingPid, callingUid)) {
Emilian Peeve20c6372018-08-14 18:45:53 +0100782 res = cameraInfo->removePermissionEntries(
783 mCameraProviderManager->getProviderTagIdLocked(String8(cameraId).string()),
784 &tagsRemoved);
785 if (res != OK) {
786 cameraInfo->clear();
787 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
788 " characteristics needing camera permission for device %s: %s (%d)",
789 String8(cameraId).string(), strerror(-res), res);
790 }
791 }
792
793 if (!tagsRemoved.empty()) {
794 res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
795 tagsRemoved.data(), tagsRemoved.size());
796 if (res != OK) {
797 cameraInfo->clear();
798 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
799 "keys needing permission for device %s: %s (%d)", String8(cameraId).string(),
800 strerror(-res), res);
801 }
802 }
803
Zhijun He2b59be82013-09-25 10:14:30 -0700804 return ret;
805}
806
Ruben Brunkcc776712015-02-17 20:18:47 -0800807String8 CameraService::getFormattedCurrentTime() {
808 time_t now = time(nullptr);
809 char formattedTime[64];
810 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
811 return String8(formattedTime);
812}
813
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800814Status CameraService::getCameraVendorTagDescriptor(
815 /*out*/
816 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700817 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800818 if (!mInitialized) {
819 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800820 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800821 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -0800822 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
823 if (globalDescriptor != nullptr) {
824 *desc = *(globalDescriptor.get());
825 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800826 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800827}
828
Emilian Peev71c73a22017-03-21 16:35:51 +0000829Status CameraService::getCameraVendorTagCache(
830 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
831 ATRACE_CALL();
832 if (!mInitialized) {
833 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
834 return STATUS_ERROR(ERROR_DISCONNECTED,
835 "Camera subsystem not available");
836 }
837 sp<VendorTagDescriptorCache> globalCache =
838 VendorTagDescriptorCache::getGlobalVendorTagCache();
839 if (globalCache != nullptr) {
840 *cache = *(globalCache.get());
841 }
842 return Status::ok();
843}
844
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -0700845void CameraService::clearCachedVariables() {
846 BasicClient::BasicClient::sCameraService = nullptr;
847}
848
Emilian Peevb91f1802021-03-23 14:50:28 -0700849int CameraService::getDeviceVersion(const String8& cameraId, int* facing, int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700850 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800851
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800852 int deviceVersion = 0;
853
Emilian Peevf53f66e2017-04-11 14:29:43 +0100854 status_t res;
855 hardware::hidl_version maxVersion{0,0};
856 res = mCameraProviderManager->getHighestSupportedVersion(cameraId.string(),
857 &maxVersion);
858 if (res != OK) return -1;
859 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800860
Emilian Peevf53f66e2017-04-11 14:29:43 +0100861 hardware::CameraInfo info;
862 if (facing) {
863 res = mCameraProviderManager->getCameraInfo(cameraId.string(), &info);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -0800864 if (res != OK) return -1;
Emilian Peevf53f66e2017-04-11 14:29:43 +0100865 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -0700866 if (orientation) {
867 *orientation = info.orientation;
868 }
Igor Murashkin634a5152013-02-20 17:15:11 -0800869 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100870
Igor Murashkin634a5152013-02-20 17:15:11 -0800871 return deviceVersion;
872}
873
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800874Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700875 switch(err) {
876 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800877 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800878 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800879 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
880 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800881 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800882 return STATUS_ERROR(ERROR_DISCONNECTED,
883 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700884 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800885 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
886 "Camera HAL encountered error %d: %s",
887 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700888 }
Igor Murashkinbfc99152013-02-27 12:55:20 -0800889}
890
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800891Status CameraService::makeClient(const sp<CameraService>& cameraService,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800892 const sp<IInterface>& cameraCb, const String16& packageName,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700893 const std::optional<String16>& featureId, const String8& cameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -0700894 int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700895 int servicePid, int deviceVersion, apiLevel effectiveApiLevel, bool overrideForPerfClass,
Ruben Brunkcc776712015-02-17 20:18:47 -0800896 /*out*/sp<BasicClient>* client) {
897
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700898 // Create CameraClient based on device version reported by the HAL.
899 switch(deviceVersion) {
900 case CAMERA_DEVICE_API_VERSION_1_0:
901 ALOGE("Camera using old HAL version: %d", deviceVersion);
902 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
903 "Camera device \"%s\" HAL version %d no longer supported",
904 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800905 break;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700906 case CAMERA_DEVICE_API_VERSION_3_0:
907 case CAMERA_DEVICE_API_VERSION_3_1:
908 case CAMERA_DEVICE_API_VERSION_3_2:
909 case CAMERA_DEVICE_API_VERSION_3_3:
910 case CAMERA_DEVICE_API_VERSION_3_4:
911 case CAMERA_DEVICE_API_VERSION_3_5:
912 case CAMERA_DEVICE_API_VERSION_3_6:
Shuzhen Wang83bff122020-11-20 15:51:39 -0800913 case CAMERA_DEVICE_API_VERSION_3_7:
Shuzhen Wang90708ea2021-11-04 11:40:49 -0700914 case CAMERA_DEVICE_API_VERSION_3_8:
Ruben Brunkcc776712015-02-17 20:18:47 -0800915 if (effectiveApiLevel == API_1) { // Camera1 API route
916 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800917 *client = new Camera2Client(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800918 cameraId, api1CameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -0700919 facing, sensorOrientation, clientPid, clientUid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700920 servicePid, overrideForPerfClass);
Ruben Brunkcc776712015-02-17 20:18:47 -0800921 } else { // Camera2 API route
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800922 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
923 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800924 *client = new CameraDeviceClient(cameraService, tmp, packageName, featureId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700925 cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid,
926 overrideForPerfClass);
Ruben Brunkcc776712015-02-17 20:18:47 -0800927 }
928 break;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700929 default:
Ruben Brunkcc776712015-02-17 20:18:47 -0800930 // Should not be reachable
931 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800932 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800933 "Camera device \"%s\" has unknown HAL version %d",
934 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800935 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800936 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800937}
938
Ruben Brunk6267b532015-04-30 17:44:07 -0700939String8 CameraService::toString(std::set<userid_t> intSet) {
940 String8 s("");
941 bool first = true;
942 for (userid_t i : intSet) {
943 if (first) {
944 s.appendFormat("%d", i);
945 first = false;
946 } else {
947 s.appendFormat(", %d", i);
948 }
949 }
950 return s;
951}
952
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800953int32_t CameraService::mapToInterface(TorchModeStatus status) {
954 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
955 switch (status) {
956 case TorchModeStatus::NOT_AVAILABLE:
957 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
958 break;
959 case TorchModeStatus::AVAILABLE_OFF:
960 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
961 break;
962 case TorchModeStatus::AVAILABLE_ON:
963 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
964 break;
965 default:
966 ALOGW("Unknown new flash status: %d", status);
967 }
968 return serviceStatus;
969}
970
971CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
972 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
973 switch (status) {
974 case CameraDeviceStatus::NOT_PRESENT:
975 serviceStatus = StatusInternal::NOT_PRESENT;
976 break;
977 case CameraDeviceStatus::PRESENT:
978 serviceStatus = StatusInternal::PRESENT;
979 break;
980 case CameraDeviceStatus::ENUMERATING:
981 serviceStatus = StatusInternal::ENUMERATING;
982 break;
983 default:
984 ALOGW("Unknown new HAL device status: %d", status);
985 }
986 return serviceStatus;
987}
988
989int32_t CameraService::mapToInterface(StatusInternal status) {
990 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
991 switch (status) {
992 case StatusInternal::NOT_PRESENT:
993 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
994 break;
995 case StatusInternal::PRESENT:
996 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
997 break;
998 case StatusInternal::ENUMERATING:
999 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
1000 break;
1001 case StatusInternal::NOT_AVAILABLE:
1002 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
1003 break;
1004 case StatusInternal::UNKNOWN:
1005 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
1006 break;
1007 default:
1008 ALOGW("Unknown new internal device status: %d", status);
1009 }
1010 return serviceStatus;
1011}
1012
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001013Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001014 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -07001015
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001016 String16 internalPackageName("cameraserver");
Ruben Brunkcc776712015-02-17 20:18:47 -08001017 String8 id = String8::format("%d", cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001018 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001019 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001020 if (!(ret = connectHelper<ICameraClient,Client>(
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001021 sp<ICameraClient>{nullptr}, id, cameraId,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001022 internalPackageName, {}, uid, USE_CALLING_PID,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001023 API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0,
1024 /*targetSdkVersion*/ __ANDROID_API_FUTURE__, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001025 ).isOk()) {
1026 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
Ruben Brunkb2119af2014-05-09 19:57:56 -07001027 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001028 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001029}
1030
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001031Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -07001032 /*out*/
1033 CameraParameters* parameters) {
1034
1035 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1036
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001037 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001038
1039 if (parameters == NULL) {
1040 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001041 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001042 }
1043
Ruben Brunkcc776712015-02-17 20:18:47 -08001044 String8 id = String8::format("%d", cameraId);
1045
1046 // Check if we already have parameters
1047 {
1048 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001049 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001050 auto cameraState = getCameraState(id);
1051 if (cameraState == nullptr) {
1052 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001053 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1054 "Invalid camera ID: %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001055 }
1056 CameraParameters p = cameraState->getShimParams();
1057 if (!p.isEmpty()) {
1058 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001059 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001060 }
1061 }
1062
Jayant Chowdhary12361932018-08-27 14:46:13 -07001063 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001064 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001065 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001066 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001067 // Error already logged by callee
1068 return ret;
1069 }
1070
1071 // Check for parameters again
1072 {
1073 // Scope for service lock
1074 Mutex::Autolock lock(mServiceLock);
1075 auto cameraState = getCameraState(id);
1076 if (cameraState == nullptr) {
1077 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001078 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1079 "Invalid camera ID: %s", id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001080 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001081 CameraParameters p = cameraState->getShimParams();
1082 if (!p.isEmpty()) {
1083 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001084 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001085 }
1086 }
1087
Ruben Brunkcc776712015-02-17 20:18:47 -08001088 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1089 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001090 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001091}
1092
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001093// Can camera service trust the caller based on the calling UID?
1094static bool isTrustedCallingUid(uid_t uid) {
1095 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001096 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001097 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001098 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001099 return true;
1100 default:
1101 return false;
1102 }
1103}
1104
Nicholas Sauera3620332019-04-03 14:05:17 -07001105static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1106 PermissionController pc;
1107 uid = pc.getPackageUid(packageName, 0);
1108 if (uid <= 0) {
1109 ALOGE("Unknown package: '%s'", String8(packageName).string());
1110 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
1111 return BAD_VALUE;
1112 }
1113
1114 if (userId < 0) {
1115 ALOGE("Invalid user: %d", userId);
1116 dprintf(err, "Invalid user: %d\n", userId);
1117 return BAD_VALUE;
1118 }
1119
1120 uid = multiuser_get_uid(userId, uid);
1121 return NO_ERROR;
1122}
1123
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001124Status CameraService::validateConnectLocked(const String8& cameraId,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001125 const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
1126 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001127
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001128#ifdef __BRILLO__
1129 UNUSED(clientName8);
1130 UNUSED(clientUid);
1131 UNUSED(clientPid);
1132 UNUSED(originalClientPid);
1133#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001134 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1135 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001136 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001137 return allowed;
1138 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001139#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001140
Jayant Chowdhary12361932018-08-27 14:46:13 -07001141 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001142
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001143 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001144 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1145 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001146 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1147 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001148 }
1149
Ruben Brunkcc776712015-02-17 20:18:47 -08001150 if (getCameraState(cameraId) == nullptr) {
1151 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1152 cameraId.string());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001153 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1154 "No camera device with ID \"%s\" available", cameraId.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001155 }
1156
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001157 status_t err = checkIfDeviceIsUsable(cameraId);
1158 if (err != NO_ERROR) {
1159 switch(err) {
1160 case -ENODEV:
1161 case -EBUSY:
1162 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1163 "No camera device with ID \"%s\" currently available", cameraId.string());
1164 default:
1165 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1166 "Unknown error connecting to ID \"%s\"", cameraId.string());
1167 }
1168 }
1169 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001170}
1171
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001172Status CameraService::validateClientPermissionsLocked(const String8& cameraId,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001173 const String8& clientName8, int& clientUid, int& clientPid,
1174 /*out*/int& originalClientPid) const {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001175 int callingPid = CameraThreadState::getCallingPid();
1176 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001177
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001178 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001179 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001180 clientUid = callingUid;
1181 } else if (!isTrustedCallingUid(callingUid)) {
1182 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1183 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001184 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1185 "Untrusted caller (calling PID %d, UID %d) trying to "
1186 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1187 callingPid, callingUid, cameraId.string(),
1188 clientName8.string(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001189 }
1190
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001191 // Check if we can trust clientPid
1192 if (clientPid == USE_CALLING_PID) {
1193 clientPid = callingPid;
1194 } else if (!isTrustedCallingUid(callingUid)) {
1195 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1196 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001197 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1198 "Untrusted caller (calling PID %d, UID %d) trying to "
1199 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1200 callingPid, callingUid, cameraId.string(),
1201 clientName8.string(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001202 }
1203
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001204 if (shouldRejectSystemCameraConnection(cameraId)) {
1205 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1206 cameraId.c_str());
1207 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
1208 "available", cameraId.string());
1209 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001210 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1211 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1212 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
1213 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
1214 "found while trying to query device kind", cameraId.string());
1215
1216 }
1217
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001218 // If it's not calling from cameraserver, check the permission if the
1219 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1220 // android.permission.SYSTEM_CAMERA for system only camera devices).
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001221 if (callingPid != getpid() &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001222 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001223 !checkPermission(sCameraPermission, clientPid, clientUid)) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001224 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001225 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1226 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
1227 clientName8.string(), clientUid, clientPid, cameraId.string());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001228 }
1229
Svet Ganova453d0d2018-01-11 15:37:58 -08001230 // Make sure the UID is in an active state to use the camera
Svet Ganov7b4ab782018-03-25 12:48:10 -07001231 if (!mUidPolicy->isUidActive(callingUid, String16(clientName8))) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001232 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001233 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1234 clientPid, clientUid);
1235 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001236 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1237 "calling UID %d proc state %" PRId32 ")",
1238 clientName8.string(), clientUid, clientPid, cameraId.string(),
1239 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001240 }
1241
Michael Grooverd1d435a2018-12-18 17:39:42 -08001242 // If sensor privacy is enabled then prevent access to the camera
1243 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1244 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1245 return STATUS_ERROR_FMT(ERROR_DISABLED,
1246 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
1247 "is enabled", clientName8.string(), clientUid, clientPid, cameraId.string());
1248 }
1249
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001250 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1251 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001252 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001253 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001254
Ruben Brunk6267b532015-04-30 17:44:07 -07001255 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001256
Ruben Brunka8ca9152015-04-07 14:23:40 -07001257 // Only allow clients who are being used by the current foreground device user, unless calling
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001258 // from our own process OR the caller is using the cameraserver's HIDL interface.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001259 if (getCurrentServingCall() != BinderCallType::HWBINDER && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001260 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001261 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1262 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
1263 toString(mAllowedUsers).string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001264 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1265 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
1266 clientUserId, cameraId.string());
Ruben Brunk36597b22015-03-20 22:15:57 -07001267 }
1268
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001269 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001270}
1271
1272status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
1273 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001274 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001275 if (cameraState == nullptr) {
1276 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1277 cameraId.string());
1278 return -ENODEV;
1279 }
1280
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001281 StatusInternal currentStatus = cameraState->getStatus();
1282 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001283 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
1284 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001285 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001286 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001287 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
1288 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001289 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001290 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001291
Ruben Brunkcc776712015-02-17 20:18:47 -08001292 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001293}
1294
Ruben Brunkcc776712015-02-17 20:18:47 -08001295void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001296 const CameraService::DescriptorPtr& desc, int oomScoreOffset) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001297
Ruben Brunkcc776712015-02-17 20:18:47 -08001298 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001299 auto clientDescriptor =
1300 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
1301 oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08001302 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1303
1304 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
1305 String8(client->getPackageName()));
1306
1307 if (evicted.size() > 0) {
1308 // This should never happen - clients should already have been removed in disconnect
1309 for (auto& i : evicted) {
1310 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
1311 __FUNCTION__, i->getKey().string());
1312 }
1313
1314 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1315 __FUNCTION__);
1316 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001317
1318 // And register a death notification for the client callback. Do
1319 // this last to avoid Binder policy where a nested Binder
1320 // transaction might be pre-empted to service the client death
1321 // notification if the client process dies before linkToDeath is
1322 // invoked.
1323 sp<IBinder> remoteCallback = client->getRemote();
1324 if (remoteCallback != nullptr) {
1325 remoteCallback->linkToDeath(this);
1326 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001327}
1328
1329status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
1330 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001331 int oomScoreOffset,
Ruben Brunkcc776712015-02-17 20:18:47 -08001332 /*out*/
1333 sp<BasicClient>* client,
1334 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001335 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001336 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001337 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001338 DescriptorPtr clientDescriptor;
1339 {
1340 if (effectiveApiLevel == API_1) {
1341 // If we are using API1, any existing client for this camera ID with the same remote
1342 // should be returned rather than evicted to allow MediaRecorder to work properly.
1343
1344 auto current = mActiveClientManager.get(cameraId);
1345 if (current != nullptr) {
1346 auto clientSp = current->getValue();
1347 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001348 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
Shuzhen Wangb2d43f62021-08-25 14:01:11 -07001349 ALOGW("CameraService connect called with a different"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001350 " API level, evicting prior client...");
1351 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001352 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001353 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001354 *client = clientSp;
1355 return NO_ERROR;
1356 }
1357 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001358 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001359 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001360
Ruben Brunkcc776712015-02-17 20:18:47 -08001361 // Get current active client PIDs
1362 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1363 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001364
Emilian Peev8131a262017-02-01 12:33:43 +00001365 std::vector<int> priorityScores(ownerPids.size());
1366 std::vector<int> states(ownerPids.size());
Igor Murashkine6800ce2013-03-04 17:25:57 -08001367
Emilian Peev8131a262017-02-01 12:33:43 +00001368 // Get priority scores of all active PIDs
1369 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1370 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1371 /*out*/&priorityScores[0]);
1372 if (err != OK) {
1373 ALOGE("%s: Priority score query failed: %d",
1374 __FUNCTION__, err);
1375 return err;
1376 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001377
Ruben Brunkcc776712015-02-17 20:18:47 -08001378 // Update all active clients' priorities
Emilian Peev8131a262017-02-01 12:33:43 +00001379 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
Ruben Brunkcc776712015-02-17 20:18:47 -08001380 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
Emilian Peev8131a262017-02-01 12:33:43 +00001381 pidToPriorityMap.emplace(ownerPids[i],
Jayant Chowdharyc578a502019-05-08 10:57:54 -07001382 resource_policy::ClientPriority(priorityScores[i], states[i],
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001383 /* isVendorClient won't get copied over*/ false,
1384 /* oomScoreOffset won't get copied over*/ 0));
Ruben Brunkcc776712015-02-17 20:18:47 -08001385 }
1386 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001387
Ruben Brunkcc776712015-02-17 20:18:47 -08001388 // Get state for the given cameraId
1389 auto state = getCameraState(cameraId);
1390 if (state == nullptr) {
1391 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1392 clientPid, cameraId.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001393 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001394 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001395 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001396
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001397 int32_t actualScore = priorityScores[priorityScores.size() - 1];
1398 int32_t actualState = states[states.size() - 1];
1399
1400 // Make descriptor for incoming client. We store the oomScoreOffset
1401 // since we might need it later on new handleEvictionsLocked and
1402 // ProcessInfoService would not take that into account.
Shuzhen Wang2db86ff2018-04-25 01:11:17 +00001403 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001404 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001405 state->getConflicting(), actualScore, clientPid, actualState,
1406 oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08001407
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001408 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1409
Ruben Brunkcc776712015-02-17 20:18:47 -08001410 // Find clients that would be evicted
1411 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1412
1413 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1414 // background, so we cannot do evictions
1415 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1416 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1417 " priority).", clientPid);
1418
1419 sp<BasicClient> clientSp = clientDescriptor->getValue();
1420 String8 curTime = getFormattedCurrentTime();
1421 auto incompatibleClients =
1422 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1423
1424 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Emilian Peev8131a262017-02-01 12:33:43 +00001425 "(PID %d, score %d state %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001426 cameraId.string(), packageName.string(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001427 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001428
1429 for (auto& i : incompatibleClients) {
1430 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001431 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
1432 i->getKey().string(),
1433 String8{i->getValue()->getPackageName()}.string(),
1434 i->getOwnerId(), i->getPriority().getScore(),
1435 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001436 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00001437 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(),
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001438 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001439 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001440 }
1441
1442 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001443 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001444 mEventLog.add(msg);
1445
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001446 auto current = mActiveClientManager.get(cameraId);
1447 if (current != nullptr) {
1448 return -EBUSY; // CAMERA_IN_USE
1449 } else {
1450 return -EUSERS; // MAX_CAMERAS_IN_USE
1451 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001452 }
1453
1454 for (auto& i : evicted) {
1455 sp<BasicClient> clientSp = i->getValue();
1456 if (clientSp.get() == nullptr) {
1457 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1458
1459 // TODO: Remove this
1460 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1461 __FUNCTION__);
1462 mActiveClientManager.remove(i);
1463 continue;
1464 }
1465
1466 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1467 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001468 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001469
Ruben Brunkcc776712015-02-17 20:18:47 -08001470 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001471 logEvent(String8::format("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00001472 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1473 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001474 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
Emilian Peev8131a262017-02-01 12:33:43 +00001475 i->getOwnerId(), i->getPriority().getScore(),
1476 i->getPriority().getState(), cameraId.string(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001477 packageName.string(), clientPid, clientPriority.getScore(),
1478 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08001479
1480 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001481 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001482 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001483 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001484 }
1485
Ruben Brunkcc776712015-02-17 20:18:47 -08001486 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1487 // other clients from connecting in mServiceLockWrapper if held
1488 mServiceLock.unlock();
1489
1490 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07001491 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001492
1493 // Destroy evicted clients
1494 for (auto& i : evictedClients) {
1495 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001496 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001497 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001498
Jayant Chowdhary12361932018-08-27 14:46:13 -07001499 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08001500
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001501 for (const auto& i : evictedClients) {
1502 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1503 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1504 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1505 if (ret == TIMED_OUT) {
1506 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1507 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1508 mActiveClientManager.toString().string());
1509 return -EBUSY;
1510 }
1511 if (ret != NO_ERROR) {
1512 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1513 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1514 ret, mActiveClientManager.toString().string());
1515 return ret;
1516 }
1517 }
1518
1519 evictedClients.clear();
1520
Ruben Brunkcc776712015-02-17 20:18:47 -08001521 // Once clients have been disconnected, relock
1522 mServiceLock.lock();
1523
1524 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1525 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1526 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001527 }
1528
Ruben Brunkcc776712015-02-17 20:18:47 -08001529 *partial = clientDescriptor;
1530 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001531}
1532
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001533Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001534 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001535 int api1CameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001536 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001537 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001538 int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001539 int targetSdkVersion,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001540 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001541 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001542
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001543 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001544 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001545
1546 String8 id = cameraIdIntToStr(api1CameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001547 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001548 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001549 clientPackageName, {}, clientUid, clientPid, API_1,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001550 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001551
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001552 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001553 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001554 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001555 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001556 }
1557
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001558 *device = client;
1559 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001560}
1561
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001562bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
1563 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001564 // If the client is not a vendor client, don't add listener if
1565 // a) the camera is a publicly hidden secure camera OR
1566 // b) the camera is a system only camera and the client doesn't
1567 // have android.permission.SYSTEM_CAMERA permissions.
1568 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
1569 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1570 !hasPermissionsForSystemCamera(clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001571 return true;
1572 }
1573 return false;
1574}
1575
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001576bool CameraService::shouldRejectSystemCameraConnection(const String8& cameraId) const {
1577 // Rules for rejection:
1578 // 1) If cameraserver tries to access this camera device, accept the
1579 // connection.
1580 // 2) The camera device is a publicly hidden secure camera device AND some
1581 // component is trying to access it on a non-hwbinder thread (generally a non HAL client),
1582 // reject it.
1583 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
1584 // and the serving thread is a non hwbinder thread, the client must have
1585 // android.permission.SYSTEM_CAMERA permissions to connect.
1586
1587 int cPid = CameraThreadState::getCallingPid();
1588 int cUid = CameraThreadState::getCallingUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001589 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
1590 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001591 // This isn't a known camera ID, so it's not a system camera
1592 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
1593 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001594 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001595
1596 // (1) Cameraserver trying to connect, accept.
1597 if (CameraThreadState::getCallingPid() == getpid()) {
1598 return false;
1599 }
1600 // (2)
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001601 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001602 systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
1603 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
1604 return true;
1605 }
1606 // (3) Here we only check for permissions if it is a system only camera device. This is since
1607 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
1608 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
1609 // same behavior for system camera devices.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001610 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001611 systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Jayant Chowdharyc3198c32021-07-28 20:59:14 +00001612 !hasPermissionsForSystemCamera(cPid, cUid, /*logPermissionFailure*/true)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001613 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
1614 cameraId.c_str());
1615 return true;
1616 }
1617
1618 return false;
1619}
1620
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001621Status CameraService::connectDevice(
1622 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001623 const String16& cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001624 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001625 const std::optional<String16>& clientFeatureId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001626 int clientUid, int oomScoreOffset, int targetSdkVersion,
Ruben Brunkcc776712015-02-17 20:18:47 -08001627 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001628 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001629
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001630 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001631 Status ret = Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001632 String8 id = String8(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001633 sp<CameraDeviceClient> client = nullptr;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001634 String16 clientPackageNameAdj = clientPackageName;
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001635 int callingPid = CameraThreadState::getCallingPid();
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001636
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001637 if (getCurrentServingCall() == BinderCallType::HWBINDER) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001638 std::string vendorClient =
1639 StringPrintf("vendor.client.pid<%d>", CameraThreadState::getCallingPid());
1640 clientPackageNameAdj = String16(vendorClient.c_str());
1641 }
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001642
1643 if (oomScoreOffset < 0) {
1644 String8 msg =
1645 String8::format("Cannot increase the priority of a client %s pid %d for "
1646 "camera id %s", String8(clientPackageNameAdj).string(), callingPid,
1647 id.string());
1648 ALOGE("%s: %s", __FUNCTION__, msg.string());
1649 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
1650 }
1651
1652 // enforce system camera permissions
1653 if (oomScoreOffset > 0 &&
1654 !hasPermissionsForSystemCamera(callingPid, CameraThreadState::getCallingUid())) {
1655 String8 msg =
1656 String8::format("Cannot change the priority of a client %s pid %d for "
1657 "camera id %s without SYSTEM_CAMERA permissions",
1658 String8(clientPackageNameAdj).string(), callingPid, id.string());
1659 ALOGE("%s: %s", __FUNCTION__, msg.string());
1660 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.string());
1661 }
1662
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001663 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001664 /*api1CameraId*/-1, clientPackageNameAdj, clientFeatureId,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001665 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, oomScoreOffset,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001666 targetSdkVersion, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08001667
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001668 if(!ret.isOk()) {
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001669 logRejected(id, callingPid, String8(clientPackageNameAdj), ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001670 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001671 }
1672
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001673 *device = client;
Rucha Katakwardf223072021-06-15 10:21:00 -07001674 Mutex::Autolock lock(mServiceLock);
1675
1676 // Clear the previous cached logs and reposition the
1677 // file offset to beginning of the file to log new data.
1678 // If either truncate or lseek fails, close the previous file and create a new one.
1679 if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
1680 ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
1681 // Close the previous memfd.
1682 close(mMemFd);
1683 // If failure to wipe the data, then create a new file and
1684 // assign the new value to mMemFd.
1685 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
1686 if (mMemFd == -1) {
1687 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
1688 }
1689 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001690 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001691}
1692
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001693template<class CALLBACK, class CLIENT>
1694Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001695 int api1CameraId, const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001696 const std::optional<String16>& clientFeatureId, int clientUid, int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001697 apiLevel effectiveApiLevel, bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001698 /*out*/sp<CLIENT>& device) {
1699 binder::Status ret = binder::Status::ok();
1700
1701 String8 clientName8(clientPackageName);
1702
1703 int originalClientPid = 0;
1704
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001705 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001706 "Camera API version %d", clientPid, clientName8.string(), cameraId.string(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001707 static_cast<int>(effectiveApiLevel));
1708
Shuzhen Wang316781a2020-08-18 18:11:01 -07001709 nsecs_t openTimeNs = systemTime();
1710
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001711 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001712 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07001713 int orientation = 0;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001714 bool isNdk = (clientPackageName.size() == 0);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001715 {
1716 // Acquire mServiceLock and prevent other clients from connecting
1717 std::unique_ptr<AutoConditionLock> lock =
1718 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1719
1720 if (lock == nullptr) {
1721 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
1722 , clientPid);
1723 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1724 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
1725 cameraId.string(), clientName8.string(), clientPid);
1726 }
1727
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07001728 // Enforce client permissions and do basic validity checks
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001729 if(!(ret = validateConnectLocked(cameraId, clientName8,
1730 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
1731 return ret;
1732 }
1733
1734 // Check the shim parameters after acquiring lock, if they have already been updated and
1735 // we were doing a shim update, return immediately
1736 if (shimUpdateOnly) {
1737 auto cameraState = getCameraState(cameraId);
1738 if (cameraState != nullptr) {
1739 if (!cameraState->getShimParams().isEmpty()) return ret;
1740 }
1741 }
1742
1743 status_t err;
1744
1745 sp<BasicClient> clientTmp = nullptr;
1746 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
1747 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001748 IInterface::asBinder(cameraCb), clientName8, oomScoreOffset, /*out*/&clientTmp,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001749 /*out*/&partial)) != NO_ERROR) {
1750 switch (err) {
1751 case -ENODEV:
1752 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1753 "No camera device with ID \"%s\" currently available",
1754 cameraId.string());
1755 case -EBUSY:
1756 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1757 "Higher-priority client using camera, ID \"%s\" currently unavailable",
1758 cameraId.string());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001759 case -EUSERS:
1760 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1761 "Too many cameras already open, cannot open camera \"%s\"",
1762 cameraId.string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001763 default:
1764 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1765 "Unexpected error %s (%d) opening camera \"%s\"",
1766 strerror(-err), err, cameraId.string());
1767 }
1768 }
1769
1770 if (clientTmp.get() != nullptr) {
1771 // Handle special case for API1 MediaRecorder where the existing client is returned
1772 device = static_cast<CLIENT*>(clientTmp.get());
1773 return ret;
1774 }
1775
1776 // give flashlight a chance to close devices if necessary.
1777 mFlashlight->prepareDeviceOpen(cameraId);
1778
Emilian Peevb91f1802021-03-23 14:50:28 -07001779 int deviceVersion = getDeviceVersion(cameraId, /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08001780 if (facing == -1) {
1781 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.string());
1782 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1783 "Unable to get camera device \"%s\" facing", cameraId.string());
1784 }
1785
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001786 sp<BasicClient> tmp = nullptr;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001787 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
1788 mPerfClassPrimaryCameraIds, cameraId.string(), targetSdkVersion);
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001789 if(!(ret = makeClient(this, cameraCb, clientPackageName, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07001790 cameraId, api1CameraId, facing, orientation,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001791 clientPid, clientUid, getpid(),
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001792 deviceVersion, effectiveApiLevel, overrideForPerfClass,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001793 /*out*/&tmp)).isOk()) {
1794 return ret;
1795 }
1796 client = static_cast<CLIENT*>(tmp.get());
1797
1798 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
1799 __FUNCTION__);
1800
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07001801 String8 monitorTags = isClientWatched(client.get()) ? mMonitorTags : String8("");
1802 err = client->initialize(mCameraProviderManager, monitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001803 if (err != OK) {
1804 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001805 // Errors could be from the HAL module open call or from AppOpsManager
1806 switch(err) {
1807 case BAD_VALUE:
1808 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1809 "Illegal argument to HAL module for camera \"%s\"", cameraId.string());
1810 case -EBUSY:
1811 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1812 "Camera \"%s\" is already open", cameraId.string());
1813 case -EUSERS:
1814 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1815 "Too many cameras already open, cannot open camera \"%s\"",
1816 cameraId.string());
1817 case PERMISSION_DENIED:
1818 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1819 "No permission to open camera \"%s\"", cameraId.string());
1820 case -EACCES:
1821 return STATUS_ERROR_FMT(ERROR_DISABLED,
1822 "Camera \"%s\" disabled by policy", cameraId.string());
1823 case -ENODEV:
1824 default:
1825 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1826 "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
1827 strerror(-err), err);
1828 }
1829 }
1830
1831 // Update shim paremeters for legacy clients
1832 if (effectiveApiLevel == API_1) {
1833 // Assume we have always received a Client subclass for API1
1834 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
1835 String8 rawParams = shimClient->getParameters();
1836 CameraParameters params(rawParams);
1837
1838 auto cameraState = getCameraState(cameraId);
1839 if (cameraState != nullptr) {
1840 cameraState->setShimParams(params);
1841 } else {
1842 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
1843 __FUNCTION__, cameraId.string());
1844 }
1845 }
1846
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001847 // Set rotate-and-crop override behavior
1848 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
1849 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
Emilian Peev5368ebf2021-10-08 17:52:18 -07001850 } else if (effectiveApiLevel == API_2) {
1851 client->setRotateAndCropOverride(CameraServiceProxyWrapper::getRotateAndCropOverride(
1852 clientPackageName, facing));
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001853 }
1854
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08001855 // Set camera muting behavior
Valentin Iftimec0b8d472021-07-23 20:21:06 +02001856 bool isCameraPrivacyEnabled =
1857 mSensorPrivacyPolicy->isCameraPrivacyEnabled(multiuser_get_user_id(clientUid));
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08001858 if (client->supportsCameraMute()) {
Valentin Iftimec0b8d472021-07-23 20:21:06 +02001859 client->setCameraMute(
1860 mOverrideCameraMuteMode || isCameraPrivacyEnabled);
1861 } else if (isCameraPrivacyEnabled) {
1862 // no camera mute supported, but privacy is on! => disconnect
1863 ALOGI("Camera mute not supported for package: %s, camera id: %s",
1864 String8(client->getPackageName()).string(), cameraId.string());
1865 // Do not hold mServiceLock while disconnecting clients, but
1866 // retain the condition blocking other clients from connecting
1867 // in mServiceLockWrapper if held.
1868 mServiceLock.unlock();
1869 // Clear caller identity temporarily so client disconnect PID
1870 // checks work correctly
1871 int64_t token = CameraThreadState::clearCallingIdentity();
1872 // Note AppOp to trigger the "Unblock" dialog
1873 client->noteAppOp();
1874 client->disconnect();
1875 CameraThreadState::restoreCallingIdentity(token);
1876 // Reacquire mServiceLock
1877 mServiceLock.lock();
1878
1879 return STATUS_ERROR_FMT(ERROR_DISABLED,
1880 "Camera \"%s\" disabled due to camera mute", cameraId.string());
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08001881 }
1882
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001883 if (shimUpdateOnly) {
1884 // If only updating legacy shim parameters, immediately disconnect client
1885 mServiceLock.unlock();
1886 client->disconnect();
1887 mServiceLock.lock();
1888 } else {
1889 // Otherwise, add client to active clients list
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001890 finishConnectLocked(client, partial, oomScoreOffset);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001891 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001892
1893 client->setImageDumpMask(mImageDumpMask);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001894 } // lock is destroyed, allow further connect calls
1895
1896 // Important: release the mutex here so the client can call back into the service from its
1897 // destructor (can be at the end of the call)
1898 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001899
1900 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
1901 CameraServiceProxyWrapper::logOpen(cameraId, facing, clientPackageName,
1902 effectiveApiLevel, isNdk, openLatencyMs);
1903
Cliff Wud3a05312021-04-26 23:07:31 +08001904 {
1905 Mutex::Autolock lock(mInjectionParametersLock);
1906 if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
1907 mInjectionInitPending = false;
1908 status_t res = NO_ERROR;
1909 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
1910 if (clientDescriptor != nullptr) {
Cliff Wu646bd612021-11-23 23:21:29 +08001911 sp<BasicClient> clientSp = clientDescriptor->getValue();
1912 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
1913 if(res != OK) {
1914 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1915 "No camera device with ID \"%s\" currently available",
1916 mInjectionExternalCamId.string());
1917 }
1918 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08001919 if (res != OK) {
1920 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
1921 }
1922 } else {
1923 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
1924 __FUNCTION__, mInjectionInternalCamId.string());
1925 res = NO_INIT;
1926 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
1927 }
1928 }
1929 }
1930
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001931 return ret;
1932}
1933
Emilian Peevb2bc5a42019-11-20 16:02:14 -08001934status_t CameraService::addOfflineClient(String8 cameraId, sp<BasicClient> offlineClient) {
1935 if (offlineClient.get() == nullptr) {
1936 return BAD_VALUE;
1937 }
1938
1939 {
1940 // Acquire mServiceLock and prevent other clients from connecting
1941 std::unique_ptr<AutoConditionLock> lock =
1942 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1943
1944 if (lock == nullptr) {
1945 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
1946 , __FUNCTION__, offlineClient->getClientPid());
1947 return TIMED_OUT;
1948 }
1949
1950 auto onlineClientDesc = mActiveClientManager.get(cameraId);
1951 if (onlineClientDesc.get() == nullptr) {
1952 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
1953 cameraId.c_str());
1954 return BAD_VALUE;
1955 }
1956
1957 // Offline clients do not evict or conflict with other online devices. Resource sharing
1958 // conflicts are handled by the camera provider which will either succeed or fail before
1959 // reaching this method.
1960 const auto& onlinePriority = onlineClientDesc->getPriority();
1961 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
1962 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
1963 /*conflictingKeys*/ std::set<String8>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001964 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
1965 /*ommScoreOffset*/ 0);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08001966
1967 // Allow only one offline device per camera
1968 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
1969 if (!incompatibleClients.empty()) {
1970 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
1971 return BAD_VALUE;
1972 }
1973
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07001974 String8 monitorTags = isClientWatched(offlineClient.get()) ? mMonitorTags : String8("");
1975 auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08001976 if (err != OK) {
1977 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
1978 return err;
1979 }
1980
1981 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
1982 if (evicted.size() > 0) {
1983 for (auto& i : evicted) {
1984 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
1985 __FUNCTION__, i->getKey().string());
1986 }
1987
1988 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
1989 "properly", __FUNCTION__);
1990
1991 return BAD_VALUE;
1992 }
1993
1994 logConnectedOffline(offlineClientDesc->getKey(),
1995 static_cast<int>(offlineClientDesc->getOwnerId()),
1996 String8(offlineClient->getPackageName()));
1997
1998 sp<IBinder> remoteCallback = offlineClient->getRemote();
1999 if (remoteCallback != nullptr) {
2000 remoteCallback->linkToDeath(this);
2001 }
2002 } // lock is destroyed, allow further connect calls
2003
2004 return OK;
2005}
2006
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002007Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002008 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002009 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002010
2011 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07002012 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002013 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002014 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2015 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002016 }
2017
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002018 String8 id = String8(cameraId.string());
Jayant Chowdhary12361932018-08-27 14:46:13 -07002019 int uid = CameraThreadState::getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002020
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002021 if (shouldRejectSystemCameraConnection(id)) {
2022 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
2023 " for system only device %s: ", id.string());
2024 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002025 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08002026 auto state = getCameraState(id);
2027 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07002028 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002029 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2030 "Camera ID \"%s\" is a not valid camera ID", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08002031 }
2032
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002033 StatusInternal cameraStatus = state->getStatus();
2034 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002035 cameraStatus != StatusInternal::NOT_AVAILABLE) {
2036 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002037 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2038 "Camera ID \"%s\" is a not valid camera ID", id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002039 }
2040
2041 {
2042 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002043 TorchModeStatus status;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002044 status_t err = getTorchStatusLocked(id, &status);
2045 if (err != OK) {
2046 if (err == NAME_NOT_FOUND) {
2047 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2048 "Camera \"%s\" does not have a flash unit", id.string());
2049 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002050 ALOGE("%s: getting current torch status failed for camera %s",
2051 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002052 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2053 "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
2054 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002055 }
2056
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002057 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002058 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002059 ALOGE("%s: torch mode of camera %s is not available because "
2060 "camera is in use", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002061 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2062 "Torch for camera \"%s\" is not available due to an existing camera user",
2063 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002064 } else {
2065 ALOGE("%s: torch mode of camera %s is not available due to "
2066 "insufficient resources", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002067 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2068 "Torch for camera \"%s\" is not available due to insufficient resources",
2069 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002070 }
2071 }
2072 }
2073
Ruben Brunk99e69712015-05-26 17:25:07 -07002074 {
2075 // Update UID map - this is used in the torch status changed callbacks, so must be done
2076 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07002077 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -07002078 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
2079 mTorchUidMap[id].first = uid;
2080 mTorchUidMap[id].second = uid;
2081 } else {
2082 // Set the pending UID
2083 mTorchUidMap[id].first = uid;
2084 }
2085 }
2086
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002087 status_t err = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07002088
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002089 if (err != OK) {
2090 int32_t errorCode;
2091 String8 msg;
2092 switch (err) {
2093 case -ENOSYS:
2094 msg = String8::format("Camera \"%s\" has no flashlight",
2095 id.string());
2096 errorCode = ERROR_ILLEGAL_ARGUMENT;
2097 break;
Dijack Dongc8a6f252021-09-17 16:21:16 +08002098 case -EBUSY:
2099 msg = String8::format("Camera \"%s\" is in use",
2100 id.string());
2101 errorCode = ERROR_CAMERA_IN_USE;
2102 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002103 default:
2104 msg = String8::format(
2105 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
2106 id.string(), enabled, strerror(-err), err);
2107 errorCode = ERROR_INVALID_OPERATION;
2108 }
2109 ALOGE("%s: %s", __FUNCTION__, msg.string());
Rucha Katakward9ea6452021-05-06 11:57:16 -07002110 logServiceError(msg,errorCode);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002111 return STATUS_ERROR(errorCode, msg.string());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002112 }
2113
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002114 {
2115 // update the link to client's death
2116 Mutex::Autolock al(mTorchClientMapMutex);
2117 ssize_t index = mTorchClientMap.indexOfKey(id);
2118 if (enabled) {
2119 if (index == NAME_NOT_FOUND) {
2120 mTorchClientMap.add(id, clientBinder);
2121 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07002122 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002123 mTorchClientMap.replaceValueAt(index, clientBinder);
2124 }
2125 clientBinder->linkToDeath(this);
2126 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07002127 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002128 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002129 }
2130
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002131 int clientPid = CameraThreadState::getCallingPid();
2132 const char *id_cstr = id.c_str();
2133 const char *torchState = enabled ? "on" : "off";
2134 ALOGI("Torch for camera id %s turned %s for client PID %d", id_cstr, torchState, clientPid);
2135 logTorchEvent(id_cstr, torchState , clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002136 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002137}
2138
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002139Status CameraService::notifySystemEvent(int32_t eventId,
2140 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002141 const int pid = CameraThreadState::getCallingPid();
2142 const int selfPid = getpid();
2143
2144 // Permission checks
2145 if (pid != selfPid) {
2146 // Ensure we're being called by system_server, or similar process with
2147 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002148 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002149 const int uid = CameraThreadState::getCallingUid();
2150 ALOGE("Permission Denial: cannot send updates to camera service about system"
2151 " events from pid=%d, uid=%d", pid, uid);
2152 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09002153 "No permission to send updates to camera service about system events"
2154 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002155 }
2156 }
2157
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002158 ATRACE_CALL();
2159
Ruben Brunk36597b22015-03-20 22:15:57 -07002160 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002161 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08002162 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002163 // from a system server crash
2164 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08002165 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002166 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07002167 break;
2168 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002169 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07002170 default: {
2171 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
2172 eventId);
2173 break;
2174 }
2175 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002176 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002177}
2178
Emilian Peev53722fa2019-02-22 17:47:20 -08002179void CameraService::notifyMonitoredUids() {
2180 Mutex::Autolock lock(mStatusListenerLock);
2181
2182 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002183 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Emilian Peev53722fa2019-02-22 17:47:20 -08002184 if (!ret.isOk()) {
2185 ALOGE("%s: Failed to trigger permission callback: %d", __FUNCTION__,
2186 ret.exceptionCode());
2187 }
2188 }
2189}
2190
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002191Status CameraService::notifyDeviceStateChange(int64_t newState) {
2192 const int pid = CameraThreadState::getCallingPid();
2193 const int selfPid = getpid();
2194
2195 // Permission checks
2196 if (pid != selfPid) {
2197 // Ensure we're being called by system_server, or similar process with
2198 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002199 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002200 const int uid = CameraThreadState::getCallingUid();
2201 ALOGE("Permission Denial: cannot send updates to camera service about device"
2202 " state changes from pid=%d, uid=%d", pid, uid);
2203 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2204 "No permission to send updates to camera service about device state"
2205 " changes from pid=%d, uid=%d", pid, uid);
2206 }
2207 }
2208
2209 ATRACE_CALL();
2210
2211 using hardware::camera::provider::V2_5::DeviceState;
2212 hardware::hidl_bitfield<DeviceState> newDeviceState{};
2213 if (newState & ICameraService::DEVICE_STATE_BACK_COVERED) {
2214 newDeviceState |= DeviceState::BACK_COVERED;
2215 }
2216 if (newState & ICameraService::DEVICE_STATE_FRONT_COVERED) {
2217 newDeviceState |= DeviceState::FRONT_COVERED;
2218 }
2219 if (newState & ICameraService::DEVICE_STATE_FOLDED) {
2220 newDeviceState |= DeviceState::FOLDED;
2221 }
2222 // Only map vendor bits directly
2223 uint64_t vendorBits = static_cast<uint64_t>(newState) & 0xFFFFFFFF00000000l;
2224 newDeviceState |= vendorBits;
2225
2226 ALOGV("%s: New device state 0x%" PRIx64, __FUNCTION__, newDeviceState);
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002227 mCameraProviderManager->notifyDeviceStateChange(newDeviceState);
2228
2229 return Status::ok();
2230}
2231
Emilian Peev8b64f282021-03-25 16:49:57 -07002232Status CameraService::notifyDisplayConfigurationChange() {
2233 ATRACE_CALL();
2234 const int callingPid = CameraThreadState::getCallingPid();
2235 const int selfPid = getpid();
2236
2237 // Permission checks
2238 if (callingPid != selfPid) {
2239 // Ensure we're being called by system_server, or similar process with
2240 // permissions to notify the camera service about system events
2241 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
2242 const int uid = CameraThreadState::getCallingUid();
2243 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
2244 " changes from pid=%d, uid=%d", callingPid, uid);
2245 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2246 "No permission to send updates to camera service about orientation"
2247 " changes from pid=%d, uid=%d", callingPid, uid);
2248 }
2249 }
2250
2251 Mutex::Autolock lock(mServiceLock);
2252
2253 // Don't do anything if rotate-and-crop override via cmd is active
2254 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
2255
2256 const auto clients = mActiveClientManager.getAll();
2257 for (auto& current : clients) {
2258 if (current != nullptr) {
2259 const auto basicClient = current->getValue();
Emilian Peeve23f1d92021-09-20 14:56:01 -07002260 if (basicClient.get() != nullptr && basicClient->canCastToApiClient(API_2)) {
Emilian Peev5368ebf2021-10-08 17:52:18 -07002261 basicClient->setRotateAndCropOverride(
2262 CameraServiceProxyWrapper::getRotateAndCropOverride(
2263 basicClient->getPackageName(), basicClient->getCameraFacing()));
Emilian Peev8b64f282021-03-25 16:49:57 -07002264 }
2265 }
2266 }
2267
2268 return Status::ok();
2269}
2270
2271Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002272 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
2273 ATRACE_CALL();
2274 if (!concurrentCameraIds) {
2275 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
2276 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
2277 }
2278
2279 if (!mInitialized) {
2280 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Rucha Katakward9ea6452021-05-06 11:57:16 -07002281 logServiceError(String8::format("Camera subsystem is not available"),ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002282 return STATUS_ERROR(ERROR_DISCONNECTED,
2283 "Camera subsystem is not available");
2284 }
2285 // First call into the provider and get the set of concurrent camera
2286 // combinations
2287 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07002288 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002289 for (auto &combination : concurrentCameraCombinations) {
2290 std::vector<std::string> validCombination;
2291 for (auto &cameraId : combination) {
2292 // if the camera state is not present, skip
2293 String8 cameraIdStr(cameraId.c_str());
2294 auto state = getCameraState(cameraIdStr);
2295 if (state == nullptr) {
2296 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
2297 continue;
2298 }
2299 StatusInternal status = state->getStatus();
2300 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
2301 continue;
2302 }
2303 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
2304 continue;
2305 }
2306 validCombination.push_back(cameraId);
2307 }
2308 if (validCombination.size() != 0) {
2309 concurrentCameraIds->push_back(std::move(validCombination));
2310 }
2311 }
2312 return Status::ok();
2313}
2314
2315Status CameraService::isConcurrentSessionConfigurationSupported(
2316 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002317 int targetSdkVersion, /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002318 if (!isSupported) {
2319 ALOGE("%s: isSupported is NULL", __FUNCTION__);
2320 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
2321 }
2322
2323 if (!mInitialized) {
2324 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2325 return STATUS_ERROR(ERROR_DISCONNECTED,
2326 "Camera subsystem is not available");
2327 }
2328
2329 // Check for camera permissions
2330 int callingPid = CameraThreadState::getCallingPid();
2331 int callingUid = CameraThreadState::getCallingUid();
2332 if ((callingPid != getpid()) && !checkPermission(sCameraPermission, callingPid, callingUid)) {
2333 ALOGE("%s: pid %d doesn't have camera permissions", __FUNCTION__, callingPid);
2334 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2335 "android.permission.CAMERA needed to call"
2336 "isConcurrentSessionConfigurationSupported");
2337 }
2338
2339 status_t res =
2340 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002341 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
2342 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002343 if (res != OK) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07002344 logServiceError(String8::format("Unable to query session configuration support"),
2345 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002346 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
2347 "support %s (%d)", strerror(-res), res);
2348 }
2349 return Status::ok();
2350}
2351
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002352Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
2353 /*out*/
2354 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002355 return addListenerHelper(listener, cameraStatuses);
2356}
2357
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002358binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
2359 std::vector<hardware::CameraStatus>* cameraStatuses) {
2360 return addListenerHelper(listener, cameraStatuses, false, true);
2361}
2362
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002363Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
2364 /*out*/
2365 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002366 bool isVendorListener, bool isProcessLocalTest) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002367
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002368 ATRACE_CALL();
2369
Igor Murashkinbfc99152013-02-27 12:55:20 -08002370 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08002371
Ruben Brunk3450ba72015-06-16 11:00:37 -07002372 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002373 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002374 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002375 }
2376
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002377 auto clientUid = CameraThreadState::getCallingUid();
2378 auto clientPid = CameraThreadState::getCallingPid();
Shuzhen Wang695044d2020-03-06 09:02:23 -08002379 bool openCloseCallbackAllowed = checkPermission(sCameraOpenCloseListenerPermission,
Jayant Chowdharyc3198c32021-07-28 20:59:14 +00002380 clientPid, clientUid, /*logPermissionFailure*/false);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002381
Igor Murashkinbfc99152013-02-27 12:55:20 -08002382 Mutex::Autolock lock(mServiceLock);
2383
Ruben Brunkcc776712015-02-17 20:18:47 -08002384 {
2385 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08002386 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002387 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002388 ALOGW("%s: Tried to add listener %p which was already subscribed",
2389 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002390 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08002391 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002392 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002393
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002394 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08002395 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
2396 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002397 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08002398 if (ret != NO_ERROR) {
2399 String8 msg = String8::format("Failed to initialize service listener: %s (%d)",
2400 strerror(-ret), ret);
Rucha Katakward9ea6452021-05-06 11:57:16 -07002401 logServiceError(msg,ERROR_ILLEGAL_ARGUMENT);
Emilian Peev53722fa2019-02-22 17:47:20 -08002402 ALOGE("%s: %s", __FUNCTION__, msg.string());
2403 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
2404 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002405 // The listener still needs to be added to the list of listeners, regardless of what
2406 // permissions the listener process has / whether it is a vendor listener. Since it might be
2407 // eligible to listen to other camera ids.
2408 mListenerList.emplace_back(serviceListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08002409 mUidPolicy->registerMonitorUid(clientUid);
Igor Murashkinbfc99152013-02-27 12:55:20 -08002410 }
2411
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002412 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07002413 {
Ruben Brunkcc776712015-02-17 20:18:47 -08002414 Mutex::Autolock lock(mCameraStatesLock);
2415 for (auto& i : mCameraStates) {
Shuzhen Wang43858162020-01-10 13:42:15 -08002416 cameraStatuses->emplace_back(i.first,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07002417 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
2418 openCloseCallbackAllowed ? i.second->getClientPackage() : String8::empty());
Igor Murashkincba2c162013-03-20 15:56:31 -07002419 }
2420 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002421 // Remove the camera statuses that should be hidden from the client, we do
2422 // this after collecting the states in order to avoid holding
2423 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
2424 // the same time.
2425 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
2426 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
2427 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
2428 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
2429 ALOGE("%s: Invalid camera id %s, skipping status update",
2430 __FUNCTION__, s.cameraId.c_str());
2431 return true;
2432 }
2433 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
2434 clientUid);}), cameraStatuses->end());
2435
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002436 //cameraStatuses will have non-eligible camera ids removed.
2437 std::set<String16> idsChosenForCallback;
2438 for (const auto &s : *cameraStatuses) {
2439 idsChosenForCallback.insert(String16(s.cameraId));
2440 }
Igor Murashkincba2c162013-03-20 15:56:31 -07002441
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002442 /*
2443 * Immediately signal current torch status to this listener only
2444 * This may be a subset of all the devices, so don't include it in the response directly
2445 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002446 {
2447 Mutex::Autolock al(mTorchStatusMutex);
2448 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002449 String16 id = String16(mTorchStatusMap.keyAt(i).string());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002450 // The camera id is visible to the client. Fine to send torch
2451 // callback.
2452 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
2453 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
2454 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002455 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002456 }
2457
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002458 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08002459}
Ruben Brunkcc776712015-02-17 20:18:47 -08002460
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002461Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002462 ATRACE_CALL();
2463
Igor Murashkinbfc99152013-02-27 12:55:20 -08002464 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
2465
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002466 if (listener == 0) {
2467 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002468 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002469 }
2470
Igor Murashkinbfc99152013-02-27 12:55:20 -08002471 Mutex::Autolock lock(mServiceLock);
2472
Ruben Brunkcc776712015-02-17 20:18:47 -08002473 {
2474 Mutex::Autolock lock(mStatusListenerLock);
2475 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002476 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
2477 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid());
2478 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08002479 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002480 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002481 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002482 }
2483 }
2484
2485 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
2486 __FUNCTION__, listener.get());
2487
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002488 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08002489}
2490
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002491Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002492
2493 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002494 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
2495
2496 if (parameters == NULL) {
2497 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002498 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07002499 }
2500
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002501 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002502
2503 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002504 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07002505 // Error logged by caller
2506 return ret;
2507 }
2508
2509 String8 shimParamsString8 = shimParams.flatten();
2510 String16 shimParamsString16 = String16(shimParamsString8);
2511
2512 *parameters = shimParamsString16;
2513
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002514 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07002515}
2516
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002517Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
2518 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002519 ATRACE_CALL();
2520
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002521 const String8 id = String8(cameraId);
2522
2523 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002524
2525 switch (apiVersion) {
2526 case API_VERSION_1:
2527 case API_VERSION_2:
2528 break;
2529 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002530 String8 msg = String8::format("Unknown API version %d", apiVersion);
2531 ALOGE("%s: %s", __FUNCTION__, msg.string());
2532 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002533 }
2534
Emilian Peev28ad2ea2017-02-07 16:14:32 +00002535 int deviceVersion = getDeviceVersion(id);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002536 switch (deviceVersion) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002537 case CAMERA_DEVICE_API_VERSION_1_0:
2538 case CAMERA_DEVICE_API_VERSION_3_0:
2539 case CAMERA_DEVICE_API_VERSION_3_1:
2540 if (apiVersion == API_VERSION_2) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002541 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without shim",
2542 __FUNCTION__, id.string(), deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002543 *isSupported = false;
2544 } else { // if (apiVersion == API_VERSION_1) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002545 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always supported",
2546 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002547 *isSupported = true;
2548 }
2549 break;
2550 case CAMERA_DEVICE_API_VERSION_3_2:
2551 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -07002552 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002553 case CAMERA_DEVICE_API_VERSION_3_5:
Yin-Chia Yeh56d98ba2020-01-16 16:57:14 -08002554 case CAMERA_DEVICE_API_VERSION_3_6:
Shuzhen Wang83bff122020-11-20 15:51:39 -08002555 case CAMERA_DEVICE_API_VERSION_3_7:
Shuzhen Wang90708ea2021-11-04 11:40:49 -07002556 case CAMERA_DEVICE_API_VERSION_3_8:
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002557 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
2558 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002559 *isSupported = true;
2560 break;
2561 case -1: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002562 String8 msg = String8::format("Unknown camera ID %s", id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002563 ALOGE("%s: %s", __FUNCTION__, msg.string());
2564 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002565 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002566 default: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002567 String8 msg = String8::format("Unknown device version %x for device %s",
2568 deviceVersion, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002569 ALOGE("%s: %s", __FUNCTION__, msg.string());
2570 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
2571 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07002572 }
2573
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002574 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002575}
2576
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002577Status CameraService::isHiddenPhysicalCamera(const String16& cameraId,
2578 /*out*/ bool *isSupported) {
2579 ATRACE_CALL();
2580
2581 const String8 id = String8(cameraId);
2582
2583 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
2584 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(id.string());
2585
2586 return Status::ok();
2587}
2588
Cliff Wud8cae102021-03-11 01:37:42 +08002589Status CameraService::injectCamera(
2590 const String16& packageName, const String16& internalCamId,
2591 const String16& externalCamId,
2592 const sp<ICameraInjectionCallback>& callback,
2593 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08002594 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08002595 ATRACE_CALL();
2596
2597 if (!checkCallingPermission(sCameraInjectExternalCameraPermission)) {
2598 const int pid = CameraThreadState::getCallingPid();
2599 const int uid = CameraThreadState::getCallingUid();
2600 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
2601 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2602 "Permission Denial: no permission to inject camera");
2603 }
2604
2605 ALOGV(
2606 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
2607 "%s",
2608 __FUNCTION__, String8(packageName).string(),
2609 String8(internalCamId).string(), String8(externalCamId).string());
2610
Cliff Wud3a05312021-04-26 23:07:31 +08002611 {
2612 Mutex::Autolock lock(mInjectionParametersLock);
2613 mInjectionInternalCamId = String8(internalCamId);
2614 mInjectionExternalCamId = String8(externalCamId);
Cliff Wu646bd612021-11-23 23:21:29 +08002615 mInjectionStatusListener->addListener(callback);
2616 *cameraInjectionSession = new CameraInjectionSession(this);
Cliff Wud3a05312021-04-26 23:07:31 +08002617 status_t res = NO_ERROR;
2618 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2619 // If the client already exists, we can directly connect to the camera device through the
2620 // client's injectCamera(), otherwise we need to wait until the client is established
2621 // (execute connectHelper()) before injecting the camera to the camera device.
2622 if (clientDescriptor != nullptr) {
2623 mInjectionInitPending = false;
Cliff Wu646bd612021-11-23 23:21:29 +08002624 sp<BasicClient> clientSp = clientDescriptor->getValue();
2625 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2626 if(res != OK) {
2627 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2628 "No camera device with ID \"%s\" currently available",
2629 mInjectionExternalCamId.string());
2630 }
2631 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08002632 if(res != OK) {
2633 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2634 }
2635 } else {
2636 mInjectionInitPending = true;
2637 }
2638 }
Cliff Wud8cae102021-03-11 01:37:42 +08002639
Cliff Wud3a05312021-04-26 23:07:31 +08002640 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08002641}
2642
Ruben Brunkcc776712015-02-17 20:18:47 -08002643void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002644 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002645 for (auto& i : mActiveClientManager.getAll()) {
2646 auto clientSp = i->getValue();
2647 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002648 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08002649 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08002650 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07002651 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002652 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08002653}
2654
Ruben Brunkcc776712015-02-17 20:18:47 -08002655bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002656 bool ret = false;
2657 {
2658 // Acquire mServiceLock and prevent other clients from connecting
2659 std::unique_ptr<AutoConditionLock> lock =
2660 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08002661
Igor Murashkin634a5152013-02-20 17:15:11 -08002662
Ruben Brunkcc776712015-02-17 20:18:47 -08002663 std::vector<sp<BasicClient>> evicted;
2664 for (auto& i : mActiveClientManager.getAll()) {
2665 auto clientSp = i->getValue();
2666 if (clientSp.get() == nullptr) {
2667 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2668 mActiveClientManager.remove(i);
2669 continue;
2670 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08002671 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002672 mActiveClientManager.remove(i);
2673 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08002674
Ruben Brunkcc776712015-02-17 20:18:47 -08002675 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002676 clientSp->notifyError(
2677 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002678 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08002679 }
2680 }
2681
Ruben Brunkcc776712015-02-17 20:18:47 -08002682 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2683 // other clients from connecting in mServiceLockWrapper if held
2684 mServiceLock.unlock();
2685
Ruben Brunk36597b22015-03-20 22:15:57 -07002686 // Do not clear caller identity, remote caller should be client proccess
2687
Ruben Brunkcc776712015-02-17 20:18:47 -08002688 for (auto& i : evicted) {
2689 if (i.get() != nullptr) {
2690 i->disconnect();
2691 ret = true;
2692 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002693 }
2694
Ruben Brunkcc776712015-02-17 20:18:47 -08002695 // Reacquire mServiceLock
2696 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08002697
Ruben Brunkcc776712015-02-17 20:18:47 -08002698 } // lock is destroyed, allow further connect calls
2699
2700 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07002701}
2702
Ruben Brunkcc776712015-02-17 20:18:47 -08002703std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
2704 const String8& cameraId) const {
2705 std::shared_ptr<CameraState> state;
2706 {
2707 Mutex::Autolock lock(mCameraStatesLock);
2708 auto iter = mCameraStates.find(cameraId);
2709 if (iter != mCameraStates.end()) {
2710 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002711 }
2712 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002713 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002714}
2715
Ruben Brunkcc776712015-02-17 20:18:47 -08002716sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
2717 // Remove from active clients list
2718 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
2719 if (clientDescriptorPtr == nullptr) {
2720 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
2721 cameraId.string());
2722 return sp<BasicClient>{nullptr};
2723 }
2724
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002725 sp<BasicClient> client = clientDescriptorPtr->getValue();
2726 if (client.get() != nullptr) {
2727 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
2728 }
2729 return client;
Keun young Parkd8973a72012-03-28 14:13:09 -07002730}
2731
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002732void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07002733 // Acquire mServiceLock and prevent other clients from connecting
2734 std::unique_ptr<AutoConditionLock> lock =
2735 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
2736
Ruben Brunk6267b532015-04-30 17:44:07 -07002737 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002738 for (size_t i = 0; i < newUserIds.size(); i++) {
2739 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07002740 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002741 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07002742 return;
2743 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002744 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07002745 }
2746
Ruben Brunka8ca9152015-04-07 14:23:40 -07002747
Ruben Brunk6267b532015-04-30 17:44:07 -07002748 if (newAllowedUsers == mAllowedUsers) {
2749 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
2750 return;
2751 }
2752
2753 logUserSwitch(mAllowedUsers, newAllowedUsers);
2754
2755 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07002756
2757 // Current user has switched, evict all current clients.
2758 std::vector<sp<BasicClient>> evicted;
2759 for (auto& i : mActiveClientManager.getAll()) {
2760 auto clientSp = i->getValue();
2761
2762 if (clientSp.get() == nullptr) {
2763 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2764 continue;
2765 }
2766
Ruben Brunk6267b532015-04-30 17:44:07 -07002767 // Don't evict clients that are still allowed.
2768 uid_t clientUid = clientSp->getClientUid();
2769 userid_t clientUserId = multiuser_get_user_id(clientUid);
2770 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
2771 continue;
2772 }
2773
Ruben Brunk36597b22015-03-20 22:15:57 -07002774 evicted.push_back(clientSp);
2775
2776 String8 curTime = getFormattedCurrentTime();
2777
2778 ALOGE("Evicting conflicting client for camera ID %s due to user change",
2779 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07002780
Ruben Brunk36597b22015-03-20 22:15:57 -07002781 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002782 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00002783 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
2784 " to user switch.", i->getKey().string(),
2785 String8{clientSp->getPackageName()}.string(),
2786 i->getOwnerId(), i->getPriority().getScore(),
2787 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07002788
2789 }
2790
2791 // Do not hold mServiceLock while disconnecting clients, but retain the condition
2792 // blocking other clients from connecting in mServiceLockWrapper if held.
2793 mServiceLock.unlock();
2794
2795 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07002796 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07002797
2798 for (auto& i : evicted) {
2799 i->disconnect();
2800 }
2801
Jayant Chowdhary12361932018-08-27 14:46:13 -07002802 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07002803
2804 // Reacquire mServiceLock
2805 mServiceLock.lock();
2806}
Ruben Brunkcc776712015-02-17 20:18:47 -08002807
Ruben Brunka8ca9152015-04-07 14:23:40 -07002808void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002809 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07002810 Mutex::Autolock l(mLogLock);
Rucha Katakward9ea6452021-05-06 11:57:16 -07002811 String8 msg = String8::format("%s : %s", curTime.string(), event);
2812 // For service error events, print the msg only once.
2813 if(!msg.contains("SERVICE ERROR")) {
2814 mEventLog.add(msg);
2815 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
2816 // Error event not added to the dumpsys log before
2817 mEventLog.add(msg);
2818 sServiceErrorEventSet.insert(msg);
2819 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002820}
2821
Ruben Brunka8ca9152015-04-07 14:23:40 -07002822void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002823 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002824 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002825 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002826 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002827}
2828
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002829void CameraService::logDisconnectedOffline(const char* cameraId, int clientPid,
2830 const char* clientPackage) {
2831 // Log the clients evicted
2832 logEvent(String8::format("DISCONNECT offline device %s client for package %s (PID %d)",
2833 cameraId, clientPackage, clientPid));
2834}
2835
Ruben Brunka8ca9152015-04-07 14:23:40 -07002836void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002837 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002838 // Log the clients evicted
2839 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002840 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002841}
2842
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002843void CameraService::logConnectedOffline(const char* cameraId, int clientPid,
2844 const char* clientPackage) {
2845 // Log the clients evicted
2846 logEvent(String8::format("CONNECT offline device %s client for package %s (PID %d)", cameraId,
2847 clientPackage, clientPid));
2848}
2849
Ruben Brunka8ca9152015-04-07 14:23:40 -07002850void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002851 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002852 // Log the client rejected
2853 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002854 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002855}
2856
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002857void CameraService::logTorchEvent(const char* cameraId, const char *torchState, int clientPid) {
2858 // Log torch event
2859 logEvent(String8::format("Torch for camera id %s turned %s for client PID %d", cameraId,
2860 torchState, clientPid));
2861}
2862
Ruben Brunk6267b532015-04-30 17:44:07 -07002863void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
2864 const std::set<userid_t>& newUserIds) {
2865 String8 newUsers = toString(newUserIds);
2866 String8 oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002867 if (oldUsers.size() == 0) {
2868 oldUsers = "<None>";
2869 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07002870 // Log the new and old users
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002871 logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
Ruben Brunk6267b532015-04-30 17:44:07 -07002872 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002873}
2874
2875void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
2876 // Log the device removal
2877 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
2878}
2879
2880void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
2881 // Log the device removal
2882 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
2883}
2884
2885void CameraService::logClientDied(int clientPid, const char* reason) {
2886 // Log the device removal
2887 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07002888}
2889
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002890void CameraService::logServiceError(const char* msg, int errorCode) {
2891 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002892 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002893}
2894
Ruben Brunk36597b22015-03-20 22:15:57 -07002895status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
2896 uint32_t flags) {
2897
Mathias Agopian65ab4712010-07-14 17:59:35 -07002898 // Permission checks
2899 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002900 case SHELL_COMMAND_TRANSACTION: {
2901 int in = data.readFileDescriptor();
2902 int out = data.readFileDescriptor();
2903 int err = data.readFileDescriptor();
2904 int argc = data.readInt32();
2905 Vector<String16> args;
2906 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
2907 args.add(data.readString16());
2908 }
2909 sp<IBinder> unusedCallback;
2910 sp<IResultReceiver> resultReceiver;
2911 status_t status;
2912 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
2913 return status;
2914 }
2915 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
2916 return status;
2917 }
2918 status = shellCommand(in, out, err, args);
2919 if (resultReceiver != nullptr) {
2920 resultReceiver->send(status);
2921 }
2922 return NO_ERROR;
2923 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002924 }
2925
2926 return BnCameraService::onTransact(code, data, reply, flags);
2927}
2928
Mathias Agopian65ab4712010-07-14 17:59:35 -07002929// We share the media players for shutter and recording sound for all clients.
2930// A reference count is kept to determine when we will actually release the
2931// media players.
2932
Jaekyun Seokef498052018-03-23 13:09:44 +09002933sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
2934 sp<MediaPlayer> mp = new MediaPlayer();
2935 status_t error;
2936 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08002937 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09002938 error = mp->prepare();
2939 }
2940 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00002941 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09002942 mp->disconnect();
2943 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002944 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002945 }
2946 return mp;
2947}
2948
username5755fea2018-12-27 09:48:08 +08002949void CameraService::increaseSoundRef() {
2950 Mutex::Autolock lock(mSoundLock);
2951 mSoundRef++;
2952}
2953
2954void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002955 ATRACE_CALL();
2956
username5755fea2018-12-27 09:48:08 +08002957 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
2958 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
2959 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
2960 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
2961 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
2962 }
2963 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
2964 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
2965 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
2966 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002967 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08002968 }
2969 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
2970 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
2971 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
2972 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
2973 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002974 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002975}
2976
username5755fea2018-12-27 09:48:08 +08002977void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002978 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002979 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002980 if (--mSoundRef) return;
2981
2982 for (int i = 0; i < NUM_SOUNDS; i++) {
2983 if (mSoundPlayer[i] != 0) {
2984 mSoundPlayer[i]->disconnect();
2985 mSoundPlayer[i].clear();
2986 }
2987 }
2988}
2989
2990void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002991 ATRACE_CALL();
2992
Mathias Agopian65ab4712010-07-14 17:59:35 -07002993 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07002994 if (kind < 0 || kind >= NUM_SOUNDS) {
2995 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
2996 return;
2997 }
2998
Mathias Agopian65ab4712010-07-14 17:59:35 -07002999 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08003000 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003001 sp<MediaPlayer> player = mSoundPlayer[kind];
3002 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08003003 player->seekTo(0);
3004 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003005 }
3006}
3007
3008// ----------------------------------------------------------------------------
3009
3010CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07003011 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003012 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09003013 const std::optional<String16>& clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003014 const String8& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07003015 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003016 int clientPid, uid_t clientUid,
3017 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08003018 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08003019 IInterface::asBinder(cameraClient),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08003020 clientPackageName, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07003021 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003022 clientPid, clientUid,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003023 servicePid),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003024 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08003025{
Jayant Chowdhary12361932018-08-27 14:46:13 -07003026 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003027 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003028
Igor Murashkin44cfcf02013-03-01 16:22:28 -08003029 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003030
username5755fea2018-12-27 09:48:08 +08003031 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003032
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003033 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003034}
3035
Mathias Agopian65ab4712010-07-14 17:59:35 -07003036// tear down the client
3037CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003038 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08003039 mDestructionStarted = true;
3040
username5755fea2018-12-27 09:48:08 +08003041 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003042 // unconditionally disconnect. function is idempotent
3043 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003044}
3045
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003046sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
3047
Igor Murashkin634a5152013-02-20 17:15:11 -08003048CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003049 const sp<IBinder>& remoteCallback,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09003050 const String16& clientPackageName, const std::optional<String16>& clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07003051 const String8& cameraIdStr, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003052 int clientPid, uid_t clientUid,
3053 int servicePid):
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003054 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07003055 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09003056 mClientPackageName(clientPackageName), mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08003057 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003058 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07003059 mDisconnected(false), mUidIsTrusted(false),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003060 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003061 mRemoteBinder(remoteCallback),
3062 mOpsActive(false),
3063 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08003064{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003065 if (sCameraService == nullptr) {
3066 sCameraService = cameraService;
3067 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08003068
3069 // In some cases the calling code has no access to the package it runs under.
3070 // For example, NDK camera API.
3071 // In this case we will get the packages for the calling UID and pick the first one
3072 // for attributing the app op. This will work correctly for runtime permissions
3073 // as for legacy apps we will toggle the app op for all packages in the UID.
3074 // The caveat is that the operation may be attributed to the wrong package and
3075 // stats based on app ops may be slightly off.
3076 if (mClientPackageName.size() <= 0) {
3077 sp<IServiceManager> sm = defaultServiceManager();
3078 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
3079 if (binder == 0) {
3080 ALOGE("Cannot get permission service");
3081 // Leave mClientPackageName unchanged (empty) and the further interaction
3082 // with camera will fail in BasicClient::startCameraOps
3083 return;
3084 }
3085
3086 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
3087 Vector<String16> packages;
3088
3089 permCtrl->getPackagesForUid(mClientUid, packages);
3090
3091 if (packages.isEmpty()) {
3092 ALOGE("No packages for calling UID");
3093 // Leave mClientPackageName unchanged (empty) and the further interaction
3094 // with camera will fail in BasicClient::startCameraOps
3095 return;
3096 }
3097 mClientPackageName = packages[0];
3098 }
Steven Moreland89a2c5c2020-01-31 15:02:25 -08003099 if (getCurrentServingCall() != BinderCallType::HWBINDER) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003100 mAppOpsManager = std::make_unique<AppOpsManager>();
3101 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07003102
3103 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08003104}
3105
3106CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003107 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08003108 mDestructionStarted = true;
3109}
3110
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003111binder::Status CameraService::BasicClient::disconnect() {
3112 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003113 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003114 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07003115 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07003116 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08003117
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003118 sCameraService->removeByClient(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003119 sCameraService->logDisconnected(mCameraIdStr, mClientPid, String8(mClientPackageName));
Peter Kalauskasa29c1352018-10-10 12:05:42 -07003120 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
3121 mCameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003122
3123 sp<IBinder> remote = getRemote();
3124 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003125 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08003126 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003127
3128 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07003129 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003130 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
3131 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
3132 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003133
Igor Murashkincba2c162013-03-20 15:56:31 -07003134 // client shouldn't be able to call into us anymore
3135 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003136
3137 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08003138}
3139
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08003140status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
3141 // No dumping of clients directly over Binder,
3142 // must go through CameraService::dump
3143 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07003144 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08003145 return OK;
3146}
3147
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07003148status_t CameraService::BasicClient::startWatchingTags(const String8&, int) {
3149 // Can't watch tags directly, must go through CameraService::startWatchingTags
3150 return OK;
3151}
3152
3153status_t CameraService::BasicClient::stopWatchingTags(int) {
3154 // Can't watch tags directly, must go through CameraService::stopWatchingTags
3155 return OK;
3156}
3157
3158status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
3159 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
3160 return OK;
3161}
3162
Ruben Brunkcc776712015-02-17 20:18:47 -08003163String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003164 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08003165}
3166
Emilian Peev8b64f282021-03-25 16:49:57 -07003167int CameraService::BasicClient::getCameraFacing() const {
3168 return mCameraFacing;
3169}
3170
3171int CameraService::BasicClient::getCameraOrientation() const {
3172 return mOrientation;
3173}
Ruben Brunkcc776712015-02-17 20:18:47 -08003174
3175int CameraService::BasicClient::getClientPid() const {
3176 return mClientPid;
3177}
3178
Ruben Brunk6267b532015-04-30 17:44:07 -07003179uid_t CameraService::BasicClient::getClientUid() const {
3180 return mClientUid;
3181}
3182
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003183bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
3184 // Defaults to API2.
3185 return level == API_2;
3186}
3187
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07003188status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003189 {
3190 Mutex::Autolock l(mAudioRestrictionLock);
3191 mAudioRestriction = mode;
3192 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07003193 sCameraService->updateAudioRestriction();
3194 return OK;
3195}
3196
3197int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003198 return sCameraService->updateAudioRestriction();
3199}
3200
3201int32_t CameraService::BasicClient::getAudioRestriction() const {
3202 Mutex::Autolock l(mAudioRestrictionLock);
3203 return mAudioRestriction;
3204}
3205
3206bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
3207 switch (mode) {
3208 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
3209 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
3210 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
3211 return true;
3212 default:
3213 return false;
3214 }
3215}
3216
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003217status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
3218 if (mode == AppOpsManager::MODE_ERRORED) {
3219 ALOGI("Camera %s: Access for \"%s\" has been revoked",
3220 mCameraIdStr.string(), String8(mClientPackageName).string());
3221 return PERMISSION_DENIED;
3222 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
3223 // If the calling Uid is trusted (a native service), the AppOpsManager could
3224 // return MODE_IGNORED. Do not treat such case as error.
3225 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
3226 mClientPackageName);
3227 bool isCameraPrivacyEnabled =
3228 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled(
3229 multiuser_get_user_id(mClientUid));
3230 if (!isUidActive || !isCameraPrivacyEnabled) {
3231 ALOGI("Camera %s: Access for \"%s\" has been restricted",
3232 mCameraIdStr.string(), String8(mClientPackageName).string());
3233 // Return the same error as for device policy manager rejection
3234 return -EACCES;
3235 }
3236 }
3237 return OK;
3238}
3239
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003240status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003241 ATRACE_CALL();
3242
Igor Murashkine6800ce2013-03-04 17:25:57 -08003243 {
3244 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003245 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08003246 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003247 if (mAppOpsManager != nullptr) {
3248 // Notify app ops that the camera is not available
3249 mOpsCallback = new OpsCallback(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003250 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
3251 mClientPackageName, mOpsCallback);
Igor Murashkine6800ce2013-03-04 17:25:57 -08003252
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003253 // Just check for camera acccess here on open - delay startOp until
3254 // camera frames start streaming in startCameraStreamingOps
3255 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
3256 mClientPackageName);
3257 status_t res = handleAppOpMode(mode);
3258 if (res != OK) {
3259 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003260 }
Svetoslav28e8ef72015-05-11 19:21:31 -07003261 }
3262
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003263 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003264
3265 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003266 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003267
Emilian Peev53722fa2019-02-22 17:47:20 -08003268 sCameraService->mUidPolicy->registerMonitorUid(mClientUid);
3269
Shuzhen Wang695044d2020-03-06 09:02:23 -08003270 // Notify listeners of camera open/close status
3271 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
3272
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003273 return OK;
3274}
3275
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003276status_t CameraService::BasicClient::startCameraStreamingOps() {
3277 ATRACE_CALL();
3278
3279 if (!mOpsActive) {
3280 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
3281 return INVALID_OPERATION;
3282 }
3283 if (mOpsStreaming) {
3284 ALOGV("%s: Streaming already active!", __FUNCTION__);
3285 return OK;
3286 }
3287
3288 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
3289 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
3290
3291 if (mAppOpsManager != nullptr) {
3292 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
3293 mClientPackageName, /*startIfModeDefault*/ false, mClientFeatureId,
3294 String16("start camera ") + String16(mCameraIdStr));
3295 status_t res = handleAppOpMode(mode);
3296 if (res != OK) {
3297 return res;
3298 }
3299 }
3300
3301 mOpsStreaming = true;
3302
3303 return OK;
3304}
3305
Valentin Iftimec0b8d472021-07-23 20:21:06 +02003306status_t CameraService::BasicClient::noteAppOp() {
3307 ATRACE_CALL();
3308
3309 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d",
3310 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
3311
3312 // noteAppOp is only used for when camera mute is not supported, in order
3313 // to trigger the sensor privacy "Unblock" dialog
3314 if (mAppOpsManager != nullptr) {
3315 int32_t mode = mAppOpsManager->noteOp(AppOpsManager::OP_CAMERA, mClientUid,
3316 mClientPackageName, mClientFeatureId,
3317 String16("start camera ") + String16(mCameraIdStr));
3318 status_t res = handleAppOpMode(mode);
3319 if (res != OK) {
3320 return res;
3321 }
3322 }
3323
3324 return OK;
3325}
3326
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003327status_t CameraService::BasicClient::finishCameraStreamingOps() {
3328 ATRACE_CALL();
3329
3330 if (!mOpsActive) {
3331 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
3332 return INVALID_OPERATION;
3333 }
3334 if (!mOpsStreaming) {
3335 ALOGV("%s: Streaming not active!", __FUNCTION__);
3336 return OK;
3337 }
3338
3339 if (mAppOpsManager != nullptr) {
3340 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
3341 mClientPackageName, mClientFeatureId);
3342 mOpsStreaming = false;
3343 }
3344
3345 return OK;
3346}
3347
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003348status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003349 ATRACE_CALL();
3350
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003351 if (mOpsStreaming) {
3352 // Make sure we've notified everyone about camera stopping
3353 finishCameraStreamingOps();
3354 }
3355
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003356 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003357 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003358 mOpsActive = false;
3359
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01003360 // This function is called when a client disconnects. This should
3361 // release the camera, but actually only if it was in a proper
3362 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003363 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01003364 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003365
Ruben Brunkcc776712015-02-17 20:18:47 -08003366 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003367 sCameraService->updateStatus(StatusInternal::PRESENT,
3368 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003369 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003370 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003371 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
3372 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08003373 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003374 mOpsCallback.clear();
3375
Emilian Peev53722fa2019-02-22 17:47:20 -08003376 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid);
3377
Shuzhen Wang695044d2020-03-06 09:02:23 -08003378 // Notify listeners of camera open/close status
3379 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
3380
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003381 return OK;
3382}
3383
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003384void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003385 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003386 if (mAppOpsManager == nullptr) {
3387 return;
3388 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003389 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003390 if (op != AppOpsManager::OP_CAMERA) {
3391 ALOGW("Unexpected app ops notification received: %d", op);
3392 return;
3393 }
3394
3395 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003396 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003397 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003398 ALOGV("checkOp returns: %d, %s ", res,
3399 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
3400 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
3401 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
3402 "UNKNOWN");
3403
Shuzhen Wang64900852021-02-05 09:03:29 -08003404 if (res == AppOpsManager::MODE_ERRORED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003405 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003406 String8(mClientPackageName).string());
Svet Ganova453d0d2018-01-11 15:37:58 -08003407 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08003408 } else if (res == AppOpsManager::MODE_IGNORED) {
3409 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Evan Severson09ab4002021-02-10 14:15:19 -08003410 bool isCameraPrivacyEnabled =
3411 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled(
3412 multiuser_get_user_id(mClientUid));
Shuzhen Wang64900852021-02-05 09:03:29 -08003413 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d",
3414 mCameraIdStr.string(), String8(mClientPackageName).string(),
3415 mUidIsTrusted, isUidActive);
3416 // If the calling Uid is trusted (a native service), or the client Uid is active (WAR for
3417 // b/175320666), the AppOpsManager could return MODE_IGNORED. Do not treat such cases as
3418 // error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02003419 if (!mUidIsTrusted) {
3420 if (isUidActive && isCameraPrivacyEnabled && supportsCameraMute()) {
3421 setCameraMute(true);
3422 } else if (!isUidActive
3423 || (isCameraPrivacyEnabled && !supportsCameraMute())) {
3424 block();
3425 }
Shuzhen Wang64900852021-02-05 09:03:29 -08003426 }
Evan Severson09ab4002021-02-10 14:15:19 -08003427 } else if (res == AppOpsManager::MODE_ALLOWED) {
3428 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003429 }
3430}
3431
Svet Ganova453d0d2018-01-11 15:37:58 -08003432void CameraService::BasicClient::block() {
3433 ATRACE_CALL();
3434
3435 // Reset the client PID to allow server-initiated disconnect,
3436 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003437 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08003438 CaptureResultExtras resultExtras; // a dummy result (invalid)
3439 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
3440 disconnect();
3441}
3442
Mathias Agopian65ab4712010-07-14 17:59:35 -07003443// ----------------------------------------------------------------------------
3444
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003445void CameraService::Client::notifyError(int32_t errorCode,
Jianing Weicb0652e2014-03-12 18:29:36 -07003446 const CaptureResultExtras& resultExtras) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08003447 (void) resultExtras;
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003448 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07003449 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
3450 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
3451 api1ErrorCode = CAMERA_ERROR_DISABLED;
3452 }
3453 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003454 } else {
3455 ALOGE("mRemoteCallback is NULL!!");
3456 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003457}
3458
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003459// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003460binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003461 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003462 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08003463}
3464
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003465bool CameraService::Client::canCastToApiClient(apiLevel level) const {
3466 return level == API_1;
3467}
3468
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003469CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
3470 mClient(client) {
3471}
3472
3473void CameraService::Client::OpsCallback::opChanged(int32_t op,
3474 const String16& packageName) {
3475 sp<BasicClient> client = mClient.promote();
3476 if (client != NULL) {
3477 client->opChanged(op, packageName);
3478 }
3479}
3480
Mathias Agopian65ab4712010-07-14 17:59:35 -07003481// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08003482// UidPolicy
3483// ----------------------------------------------------------------------------
3484
3485void CameraService::UidPolicy::registerSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003486 Mutex::Autolock _l(mUidLock);
3487
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003488 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07003489 status_t res = mAm.linkToDeath(this);
3490 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08003491 | ActivityManager::UID_OBSERVER_IDLE
Emilian Peev53722fa2019-02-22 17:47:20 -08003492 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganova453d0d2018-01-11 15:37:58 -08003493 ActivityManager::PROCESS_STATE_UNKNOWN,
3494 String16("cameraserver"));
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003495 if (res == OK) {
3496 mRegistered = true;
3497 ALOGV("UidPolicy: Registered with ActivityManager");
3498 }
Svet Ganova453d0d2018-01-11 15:37:58 -08003499}
3500
3501void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003502 Mutex::Autolock _l(mUidLock);
3503
Steven Moreland2f348142019-07-02 15:59:07 -07003504 mAm.unregisterUidObserver(this);
3505 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003506 mRegistered = false;
3507 mActiveUids.clear();
3508 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08003509}
3510
3511void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
3512 onUidIdle(uid, disabled);
3513}
3514
3515void CameraService::UidPolicy::onUidActive(uid_t uid) {
3516 Mutex::Autolock _l(mUidLock);
3517 mActiveUids.insert(uid);
3518}
3519
3520void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
3521 bool deleted = false;
3522 {
3523 Mutex::Autolock _l(mUidLock);
3524 if (mActiveUids.erase(uid) > 0) {
3525 deleted = true;
3526 }
3527 }
3528 if (deleted) {
3529 sp<CameraService> service = mService.promote();
3530 if (service != nullptr) {
3531 service->blockClientsForUid(uid);
3532 }
3533 }
3534}
3535
Emilian Peev53722fa2019-02-22 17:47:20 -08003536void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07003537 int64_t procStateSeq __unused, int32_t capability __unused) {
Emilian Peev53722fa2019-02-22 17:47:20 -08003538 bool procStateChange = false;
3539 {
3540 Mutex::Autolock _l(mUidLock);
3541 if ((mMonitoredUids.find(uid) != mMonitoredUids.end()) &&
3542 (mMonitoredUids[uid].first != procState)) {
3543 mMonitoredUids[uid].first = procState;
3544 procStateChange = true;
3545 }
3546 }
3547
3548 if (procStateChange) {
3549 sp<CameraService> service = mService.promote();
3550 if (service != nullptr) {
3551 service->notifyMonitoredUids();
3552 }
3553 }
3554}
3555
3556void CameraService::UidPolicy::registerMonitorUid(uid_t uid) {
3557 Mutex::Autolock _l(mUidLock);
3558 auto it = mMonitoredUids.find(uid);
3559 if (it != mMonitoredUids.end()) {
3560 it->second.second++;
3561 } else {
3562 mMonitoredUids.emplace(
3563 std::pair<uid_t, std::pair<int32_t, size_t>> (uid,
3564 std::pair<int32_t, size_t> (ActivityManager::PROCESS_STATE_NONEXISTENT, 1)));
3565 }
3566}
3567
3568void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid) {
3569 Mutex::Autolock _l(mUidLock);
3570 auto it = mMonitoredUids.find(uid);
3571 if (it != mMonitoredUids.end()) {
3572 it->second.second--;
3573 if (it->second.second == 0) {
3574 mMonitoredUids.erase(it);
3575 }
3576 } else {
3577 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
3578 }
3579}
3580
Svet Ganov7b4ab782018-03-25 12:48:10 -07003581bool CameraService::UidPolicy::isUidActive(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003582 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003583 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003584}
3585
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003586static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
3587static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003588
Svet Ganov7b4ab782018-03-25 12:48:10 -07003589bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003590 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003591 // If activity manager is unreachable, assume everything is active
3592 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003593 return true;
3594 }
3595 auto it = mOverrideUids.find(uid);
3596 if (it != mOverrideUids.end()) {
3597 return it->second;
3598 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003599 bool active = mActiveUids.find(uid) != mActiveUids.end();
3600 if (!active) {
3601 // We want active UIDs to always access camera with their first attempt since
3602 // there is no guarantee the app is robustly written and would retry getting
3603 // the camera on failure. The inverse case is not a problem as we would take
3604 // camera away soon once we get the callback that the uid is no longer active.
3605 ActivityManager am;
3606 // Okay to access with a lock held as UID changes are dispatched without
3607 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07003608 int64_t startTimeMillis = 0;
3609 do {
3610 // TODO: Fix this b/109950150!
3611 // Okay this is a hack. There is a race between the UID turning active and
3612 // activity being resumed. The proper fix is very risky, so we temporary add
3613 // some polling which should happen pretty rarely anyway as the race is hard
3614 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003615 active = mActiveUids.find(uid) != mActiveUids.end();
Hui Yu12c7ec72020-05-04 17:40:52 +00003616 if (!active) active = am.isUidActive(uid, callingPackage);
Svet Ganov94ec46f2018-06-08 15:03:46 -07003617 if (active) {
3618 break;
3619 }
3620 if (startTimeMillis <= 0) {
3621 startTimeMillis = uptimeMillis();
3622 }
3623 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003624 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003625 if (remainingTimeMillis <= 0) {
3626 break;
3627 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003628 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
3629
3630 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003631 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003632 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003633 } while (true);
3634
Svet Ganov7b4ab782018-03-25 12:48:10 -07003635 if (active) {
3636 // Now that we found out the UID is actually active, cache that
3637 mActiveUids.insert(uid);
3638 }
3639 }
3640 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08003641}
3642
Varun Shahb42f1eb2019-04-16 14:45:13 -07003643int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
3644 Mutex::Autolock _l(mUidLock);
3645 return getProcStateLocked(uid);
3646}
3647
3648int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
3649 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
3650 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
3651 procState = mMonitoredUids[uid].first;
3652 }
3653 return procState;
3654}
3655
Svet Ganov7b4ab782018-03-25 12:48:10 -07003656void CameraService::UidPolicy::UidPolicy::addOverrideUid(uid_t uid,
3657 String16 callingPackage, bool active) {
3658 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08003659}
3660
Svet Ganov7b4ab782018-03-25 12:48:10 -07003661void CameraService::UidPolicy::removeOverrideUid(uid_t uid, String16 callingPackage) {
3662 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08003663}
3664
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003665void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
3666 Mutex::Autolock _l(mUidLock);
3667 ALOGV("UidPolicy: ActivityManager has died");
3668 mRegistered = false;
3669 mActiveUids.clear();
3670}
3671
Svet Ganov7b4ab782018-03-25 12:48:10 -07003672void CameraService::UidPolicy::updateOverrideUid(uid_t uid, String16 callingPackage,
3673 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003674 bool wasActive = false;
3675 bool isActive = false;
3676 {
3677 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003678 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003679 mOverrideUids.erase(uid);
3680 if (insert) {
3681 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
3682 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003683 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003684 }
3685 if (wasActive != isActive && !isActive) {
3686 sp<CameraService> service = mService.promote();
3687 if (service != nullptr) {
3688 service->blockClientsForUid(uid);
3689 }
3690 }
3691}
3692
3693// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08003694// SensorPrivacyPolicy
3695// ----------------------------------------------------------------------------
3696void CameraService::SensorPrivacyPolicy::registerSelf() {
3697 Mutex::Autolock _l(mSensorPrivacyLock);
3698 if (mRegistered) {
3699 return;
3700 }
Evan Severson09ab4002021-02-10 14:15:19 -08003701 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08003702 mSpm.addSensorPrivacyListener(this);
3703 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
3704 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003705 if (res == OK) {
3706 mRegistered = true;
3707 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
3708 }
3709}
3710
3711void CameraService::SensorPrivacyPolicy::unregisterSelf() {
3712 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08003713 mSpm.removeSensorPrivacyListener(this);
3714 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003715 mRegistered = false;
3716 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
3717}
3718
3719bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
3720 Mutex::Autolock _l(mSensorPrivacyLock);
3721 return mSensorPrivacyEnabled;
3722}
3723
Evan Severson09ab4002021-02-10 14:15:19 -08003724bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled(userid_t userId) {
3725 if (!hasCameraPrivacyFeature()) {
3726 return false;
3727 }
3728 return mSpm.isIndividualSensorPrivacyEnabled(userId,
3729 SensorPrivacyManager::INDIVIDUAL_SENSOR_CAMERA);
3730}
3731
Michael Grooverd1d435a2018-12-18 17:39:42 -08003732binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
3733 {
3734 Mutex::Autolock _l(mSensorPrivacyLock);
3735 mSensorPrivacyEnabled = enabled;
3736 }
3737 // if sensor privacy is enabled then block all clients from accessing the camera
Evan Severson09ab4002021-02-10 14:15:19 -08003738 if (enabled) {
3739 sp<CameraService> service = mService.promote();
3740 if (service != nullptr) {
3741 service->blockAllClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08003742 }
3743 }
3744 return binder::Status::ok();
3745}
3746
3747void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
3748 Mutex::Autolock _l(mSensorPrivacyLock);
3749 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
3750 mRegistered = false;
3751}
3752
Evan Severson09ab4002021-02-10 14:15:19 -08003753bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Severson671806e2021-04-20 16:44:53 -07003754 return mSpm.supportsSensorToggle(SensorPrivacyManager::INDIVIDUAL_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08003755}
3756
Michael Grooverd1d435a2018-12-18 17:39:42 -08003757// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003758// CameraState
3759// ----------------------------------------------------------------------------
3760
3761CameraService::CameraState::CameraState(const String8& id, int cost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003762 const std::set<String8>& conflicting, SystemCameraKind systemCameraKind) : mId(id),
3763 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
3764 mSystemCameraKind(systemCameraKind) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08003765
3766CameraService::CameraState::~CameraState() {}
3767
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003768CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003769 Mutex::Autolock lock(mStatusLock);
3770 return mStatus;
3771}
3772
Shuzhen Wang43858162020-01-10 13:42:15 -08003773std::vector<String8> CameraService::CameraState::getUnavailablePhysicalIds() const {
3774 Mutex::Autolock lock(mStatusLock);
3775 std::vector<String8> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
3776 return res;
3777}
3778
Ruben Brunkcc776712015-02-17 20:18:47 -08003779CameraParameters CameraService::CameraState::getShimParams() const {
3780 return mShimParams;
3781}
3782
3783void CameraService::CameraState::setShimParams(const CameraParameters& params) {
3784 mShimParams = params;
3785}
3786
3787int CameraService::CameraState::getCost() const {
3788 return mCost;
3789}
3790
3791std::set<String8> CameraService::CameraState::getConflicting() const {
3792 return mConflicting;
3793}
3794
3795String8 CameraService::CameraState::getId() const {
3796 return mId;
3797}
3798
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003799SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
3800 return mSystemCameraKind;
3801}
3802
Shuzhen Wang43858162020-01-10 13:42:15 -08003803bool CameraService::CameraState::addUnavailablePhysicalId(const String8& physicalId) {
3804 Mutex::Autolock lock(mStatusLock);
3805 auto result = mUnavailablePhysicalIds.insert(physicalId);
3806 return result.second;
3807}
3808
3809bool CameraService::CameraState::removeUnavailablePhysicalId(const String8& physicalId) {
3810 Mutex::Autolock lock(mStatusLock);
3811 auto count = mUnavailablePhysicalIds.erase(physicalId);
3812 return count > 0;
3813}
3814
Shuzhen Wange7aa0342021-08-03 11:29:47 -07003815void CameraService::CameraState::setClientPackage(const String8& clientPackage) {
3816 Mutex::Autolock lock(mStatusLock);
3817 mClientPackage = clientPackage;
3818}
3819
3820String8 CameraService::CameraState::getClientPackage() const {
3821 Mutex::Autolock lock(mStatusLock);
3822 return mClientPackage;
3823}
3824
Ruben Brunkcc776712015-02-17 20:18:47 -08003825// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07003826// ClientEventListener
3827// ----------------------------------------------------------------------------
3828
3829void CameraService::ClientEventListener::onClientAdded(
3830 const resource_policy::ClientDescriptor<String8,
3831 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003832 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003833 if (basicClient.get() != nullptr) {
3834 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3835 notifier.noteStartCamera(descriptor.getKey(),
3836 static_cast<int>(basicClient->getClientUid()));
3837 }
3838}
3839
3840void CameraService::ClientEventListener::onClientRemoved(
3841 const resource_policy::ClientDescriptor<String8,
3842 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003843 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003844 if (basicClient.get() != nullptr) {
3845 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3846 notifier.noteStopCamera(descriptor.getKey(),
3847 static_cast<int>(basicClient->getClientUid()));
3848 }
3849}
3850
3851
3852// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003853// CameraClientManager
3854// ----------------------------------------------------------------------------
3855
Ruben Brunk99e69712015-05-26 17:25:07 -07003856CameraService::CameraClientManager::CameraClientManager() {
3857 setListener(std::make_shared<ClientEventListener>());
3858}
3859
Ruben Brunkcc776712015-02-17 20:18:47 -08003860CameraService::CameraClientManager::~CameraClientManager() {}
3861
3862sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
3863 const String8& id) const {
3864 auto descriptor = get(id);
3865 if (descriptor == nullptr) {
3866 return sp<BasicClient>{nullptr};
3867 }
3868 return descriptor->getValue();
3869}
3870
3871String8 CameraService::CameraClientManager::toString() const {
3872 auto all = getAll();
3873 String8 ret("[");
3874 bool hasAny = false;
3875 for (auto& i : all) {
3876 hasAny = true;
3877 String8 key = i->getKey();
3878 int32_t cost = i->getCost();
3879 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00003880 int32_t score = i->getPriority().getScore();
3881 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08003882 auto conflicting = i->getConflicting();
3883 auto clientSp = i->getValue();
3884 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07003885 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08003886 if (clientSp.get() != nullptr) {
3887 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07003888 uid_t clientUid = clientSp->getClientUid();
3889 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003890 }
Emilian Peev8131a262017-02-01 12:33:43 +00003891 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
3892 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08003893
Ruben Brunk6267b532015-04-30 17:44:07 -07003894 if (clientSp.get() != nullptr) {
3895 ret.appendFormat("User Id: %d, ", clientUserId);
3896 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003897 if (packageName.size() != 0) {
3898 ret.appendFormat("Client Package Name: %s", packageName.string());
3899 }
3900
3901 ret.append(", Conflicting Client Devices: {");
3902 for (auto& j : conflicting) {
3903 ret.appendFormat("%s, ", j.string());
3904 }
3905 ret.append("})");
3906 }
3907 if (hasAny) ret.append("\n");
3908 ret.append("]\n");
3909 return ret;
3910}
3911
3912CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3913 const String8& key, const sp<BasicClient>& value, int32_t cost,
Emilian Peev8131a262017-02-01 12:33:43 +00003914 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00003915 int32_t state, int32_t oomScoreOffset) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003916
Steven Moreland89a2c5c2020-01-31 15:02:25 -08003917 bool isVendorClient = getCurrentServingCall() == BinderCallType::HWBINDER;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003918 int32_t score_adj = isVendorClient ? kVendorClientScore : score;
3919 int32_t state_adj = isVendorClient ? kVendorClientState: state;
3920
Ruben Brunkcc776712015-02-17 20:18:47 -08003921 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00003922 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj, isVendorClient,
3923 oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08003924}
3925
3926CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00003927 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
3928 int32_t oomScoreOffset) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003929 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00003930 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00003931 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08003932}
3933
3934// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08003935// InjectionStatusListener
3936// ----------------------------------------------------------------------------
3937
3938void CameraService::InjectionStatusListener::addListener(
3939 const sp<ICameraInjectionCallback>& callback) {
3940 Mutex::Autolock lock(mListenerLock);
3941 if (mCameraInjectionCallback) return;
3942 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
3943 if (res == OK) {
3944 mCameraInjectionCallback = callback;
3945 }
3946}
3947
3948void CameraService::InjectionStatusListener::removeListener() {
3949 Mutex::Autolock lock(mListenerLock);
3950 if (mCameraInjectionCallback == nullptr) {
3951 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
3952 return;
3953 }
3954 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
3955 mCameraInjectionCallback = nullptr;
3956}
3957
3958void CameraService::InjectionStatusListener::notifyInjectionError(
Cliff Wud3a05312021-04-26 23:07:31 +08003959 String8 injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08003960 if (mCameraInjectionCallback == nullptr) {
3961 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
3962 return;
3963 }
Cliff Wud3a05312021-04-26 23:07:31 +08003964
3965 switch (err) {
3966 case -ENODEV:
3967 mCameraInjectionCallback->onInjectionError(
3968 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
3969 ALOGE("No camera device with ID \"%s\" currently available!",
3970 injectedCamId.string());
3971 break;
3972 case -EBUSY:
3973 mCameraInjectionCallback->onInjectionError(
3974 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
3975 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
3976 injectedCamId.string());
3977 break;
3978 case DEAD_OBJECT:
3979 mCameraInjectionCallback->onInjectionError(
3980 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
3981 ALOGE("Camera ID \"%s\" object is dead!",
3982 injectedCamId.string());
3983 break;
3984 case INVALID_OPERATION:
3985 mCameraInjectionCallback->onInjectionError(
3986 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
3987 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
3988 injectedCamId.string());
3989 break;
3990 case UNKNOWN_TRANSACTION:
3991 mCameraInjectionCallback->onInjectionError(
3992 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
3993 ALOGE("Camera ID \"%s\" method doesn't support!",
3994 injectedCamId.string());
3995 break;
3996 default:
3997 mCameraInjectionCallback->onInjectionError(
3998 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
3999 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
4000 strerror(-err), err, injectedCamId.string());
4001 }
Cliff Wud8cae102021-03-11 01:37:42 +08004002}
4003
4004void CameraService::InjectionStatusListener::binderDied(
4005 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08004006 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
4007 auto parent = mParent.promote();
4008 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08004009 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
4010 if (clientDescriptor != nullptr) {
4011 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
4012 baseClientPtr->stopInjection();
4013 }
Cliff Wu3b268182021-07-06 15:44:43 +08004014 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08004015 }
4016}
4017
4018// ----------------------------------------------------------------------------
4019// CameraInjectionSession
4020// ----------------------------------------------------------------------------
4021
4022binder::Status CameraService::CameraInjectionSession::stopInjection() {
4023 Mutex::Autolock lock(mInjectionSessionLock);
4024 auto parent = mParent.promote();
4025 if (parent == nullptr) {
4026 ALOGE("CameraInjectionSession: Parent is gone");
4027 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
4028 "Camera service encountered error");
4029 }
Cliff Wud3a05312021-04-26 23:07:31 +08004030
4031 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08004032 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
4033 if (clientDescriptor != nullptr) {
4034 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
4035 res = baseClientPtr->stopInjection();
4036 if (res != OK) {
4037 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
4038 " ret != NO_ERROR: %d", res);
4039 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
4040 "Camera session encountered error");
4041 }
4042 }
Cliff Wu3b268182021-07-06 15:44:43 +08004043 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08004044 return binder::Status::ok();
4045}
4046
4047// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07004048
4049static const int kDumpLockRetries = 50;
4050static const int kDumpLockSleep = 60000;
4051
4052static bool tryLock(Mutex& mutex)
4053{
4054 bool locked = false;
4055 for (int i = 0; i < kDumpLockRetries; ++i) {
4056 if (mutex.tryLock() == NO_ERROR) {
4057 locked = true;
4058 break;
4059 }
4060 usleep(kDumpLockSleep);
4061 }
4062 return locked;
4063}
4064
Rucha Katakwardf223072021-06-15 10:21:00 -07004065void CameraService::cacheDump() {
4066 if (mMemFd != -1) {
4067 const Vector<String16> args;
4068 ATRACE_CALL();
4069 // Acquiring service lock here will avoid the deadlock since
4070 // cacheDump will not be called during the second disconnect.
4071 Mutex::Autolock lock(mServiceLock);
4072
4073 Mutex::Autolock l(mCameraStatesLock);
4074 // Start collecting the info for open sessions and store it in temp file.
4075 for (const auto& state : mCameraStates) {
4076 String8 cameraId = state.first;
4077 auto clientDescriptor = mActiveClientManager.get(cameraId);
4078 if (clientDescriptor != nullptr) {
4079 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.string());
4080 // Log the current open session info before device is disconnected.
4081 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
4082 }
4083 }
4084 }
4085}
4086
Mathias Agopian65ab4712010-07-14 17:59:35 -07004087status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004088 ATRACE_CALL();
4089
Jayant Chowdhary5216b212019-07-17 09:26:23 -07004090 if (checkCallingPermission(sDumpPermission) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004091 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07004092 CameraThreadState::getCallingPid(),
4093 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004094 return NO_ERROR;
4095 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004096 bool locked = tryLock(mServiceLock);
4097 // failed to lock - CameraService is probably deadlocked
4098 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004099 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004100 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004101
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004102 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004103 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07004104
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004105 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004106 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08004107
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004108 if (locked) mServiceLock.unlock();
4109 return NO_ERROR;
4110 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004111 dprintf(fd, "\n== Service global info: ==\n\n");
4112 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004113 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07004114 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
4115 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004116 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
4117 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
4118 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004119 String8 activeClientString = mActiveClientManager.toString();
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004120 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
4121 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004122
4123 dumpEventLog(fd);
4124
4125 bool stateLocked = tryLock(mCameraStatesLock);
4126 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004127 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004128 }
4129
Emilian Peevbd8c5032018-02-14 23:05:40 +00004130 int argSize = args.size();
4131 for (int i = 0; i < argSize; i++) {
4132 if (args[i] == TagMonitor::kMonitorOption) {
4133 if (i + 1 < argSize) {
4134 mMonitorTags = String8(args[i + 1]);
4135 }
4136 break;
4137 }
4138 }
4139
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004140 for (auto& state : mCameraStates) {
4141 String8 cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004142
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004143 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004144
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004145 CameraParameters p = state.second->getShimParams();
4146 if (!p.isEmpty()) {
4147 dprintf(fd, " Camera1 API shim is using parameters:\n ");
4148 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004149 }
4150
4151 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08004152 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07004153 // log the current open session info
4154 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08004155 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07004156 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004157 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004158
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004159 }
4160
4161 if (stateLocked) mCameraStatesLock.unlock();
4162
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004163 if (locked) mServiceLock.unlock();
4164
Emilian Peevf53f66e2017-04-11 14:29:43 +01004165 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004166
4167 dprintf(fd, "\n== Vendor tags: ==\n\n");
4168
4169 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
4170 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00004171 sp<VendorTagDescriptorCache> cache =
4172 VendorTagDescriptorCache::getGlobalVendorTagCache();
4173 if (cache == NULL) {
4174 dprintf(fd, "No vendor tags.\n");
4175 } else {
4176 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
4177 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004178 } else {
4179 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
4180 }
4181
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004182 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004183 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004184 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004185
4186 // Process dump arguments, if any
4187 int n = args.size();
4188 String16 verboseOption("-v");
4189 String16 unreachableOption("--unreachable");
4190 for (int i = 0; i < n; i++) {
4191 if (args[i] == verboseOption) {
4192 // change logging level
4193 if (i + 1 >= n) continue;
4194 String8 levelStr(args[i+1]);
4195 int level = atoi(levelStr.string());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004196 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004197 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004198 } else if (args[i] == unreachableOption) {
4199 // Dump memory analysis
4200 // TODO - should limit be an argument parameter?
4201 UnreachableMemoryInfo info;
4202 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
4203 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004204 dprintf(fd, "\n== Unable to dump unreachable memory. "
4205 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004206 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004207 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004208 std::string s = info.ToString(/*log_contents*/ true);
4209 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004210 }
4211 }
4212 }
Rucha Katakwardf223072021-06-15 10:21:00 -07004213
4214 bool serviceLocked = tryLock(mServiceLock);
4215
4216 // Dump info from previous open sessions.
4217 // Reposition the offset to beginning of the file before reading
4218
4219 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
4220 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
4221 ssize_t size_read;
4222 char buf[4096];
4223 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
4224 // Read data from file to a small buffer and write it to fd.
4225 write(fd, buf, size_read);
4226 if (size_read == -1) {
4227 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
4228 break;
4229 }
4230 }
4231 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
4232 } else {
4233 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
4234 }
4235
4236 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004237 return NO_ERROR;
4238}
4239
Rucha Katakwardf223072021-06-15 10:21:00 -07004240void CameraService::dumpOpenSessionClientLogs(int fd,
4241 const Vector<String16>& args, const String8& cameraId) {
4242 auto clientDescriptor = mActiveClientManager.get(cameraId);
4243 dprintf(fd, " Device %s is open. Client instance dump:\n",
4244 cameraId.string());
4245 dprintf(fd, " Client priority score: %d state: %d\n",
4246 clientDescriptor->getPriority().getScore(),
4247 clientDescriptor->getPriority().getState());
4248 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
4249
4250 auto client = clientDescriptor->getValue();
4251 dprintf(fd, " Client package: %s\n",
4252 String8(client->getPackageName()).string());
4253
4254 client->dumpClient(fd, args);
4255}
4256
4257void CameraService::dumpClosedSessionClientLogs(int fd, const String8& cameraId) {
4258 dprintf(fd, " Device %s is closed, no client instance\n",
4259 cameraId.string());
4260}
4261
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004262void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004263 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004264
4265 Mutex::Autolock l(mLogLock);
4266 for (const auto& msg : mEventLog) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004267 dprintf(fd, " %s\n", msg.string());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004268 }
4269
4270 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004271 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004272 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004273 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004274 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004275 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004276}
4277
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004278void CameraService::cacheClientTagDumpIfNeeded(const char *cameraId, BasicClient* client) {
4279 Mutex::Autolock lock(mLogLock);
4280 if (!isClientWatchedLocked(client)) { return; }
4281
4282 std::vector<std::string> dumpVector;
4283 client->dumpWatchedEventsToVector(dumpVector);
4284
4285 if (dumpVector.empty()) { return; }
4286
Avichal Rakesh882c08b2021-12-09 17:47:07 -08004287 std::string dumpString;
4288
4289 String8 currentTime = getFormattedCurrentTime();
4290 dumpString += "Cached @ ";
4291 dumpString += currentTime.string();
4292 dumpString += "\n"; // First line is the timestamp of when client is cached.
4293
4294
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08004295 const String16 &packageName = client->getPackageName();
4296
4297 String8 packageName8 = String8(packageName);
4298 const char *printablePackageName = packageName8.lockBuffer(packageName.size());
4299
Avichal Rakesh882c08b2021-12-09 17:47:07 -08004300
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004301 size_t i = dumpVector.size();
4302
4303 // Store the string in reverse order (latest last)
4304 while (i > 0) {
4305 i--;
4306 dumpString += cameraId;
4307 dumpString += ":";
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08004308 dumpString += printablePackageName;
4309 dumpString += " ";
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004310 dumpString += dumpVector[i]; // implicitly ends with '\n'
4311 }
4312
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08004313 packageName8.unlockBuffer();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004314 mWatchedClientsDumpCache[packageName] = dumpString;
4315}
4316
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004317void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004318 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004319 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
4320 if (mTorchClientMap[i] == who) {
4321 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004322 String8 cameraId = mTorchClientMap.keyAt(i);
4323 status_t res = mFlashlight->setTorchMode(cameraId, false);
4324 if (res) {
4325 ALOGE("%s: torch client died but couldn't turn off torch: "
4326 "%s (%d)", __FUNCTION__, strerror(-res), res);
4327 return;
4328 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004329 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004330 break;
4331 }
4332 }
4333}
4334
Ruben Brunkcc776712015-02-17 20:18:47 -08004335/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07004336
Igor Murashkin294d0ec2012-10-05 10:44:57 -07004337 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07004338 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
4339 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07004340 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08004341 // PID here is approximate and can be wrong.
Jayant Chowdhary12361932018-08-27 14:46:13 -07004342 logClientDied(CameraThreadState::getCallingPid(), String8("Binder died unexpectedly"));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004343
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004344 // check torch client
4345 handleTorchClientBinderDied(who);
4346
4347 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08004348 if(!evictClientIdByRemote(who)) {
4349 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07004350 return;
4351 }
4352
Ruben Brunkcc776712015-02-17 20:18:47 -08004353 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
4354 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07004355}
4356
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004357void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004358 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08004359}
4360
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004361void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
4362 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004363 // Do not lock mServiceLock here or can get into a deadlock from
4364 // connect() -> disconnect -> updateStatus
4365
4366 auto state = getCameraState(cameraId);
4367
4368 if (state == nullptr) {
4369 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
4370 cameraId.string());
4371 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07004372 }
4373
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004374 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
4375 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
4376 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
4377 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
4378 return;
4379 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004380
4381 // Collect the logical cameras without holding mStatusLock in updateStatus
4382 // as that can lead to a deadlock(b/162192331).
4383 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08004384 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08004385 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07004386 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004387 &logicalCameraIds]
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004388 (const String8& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004389
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004390 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004391 // Update torch status if it has a flash unit.
4392 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004393 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004394 if (getTorchStatusLocked(cameraId, &torchStatus) !=
4395 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004396 TorchModeStatus newTorchStatus =
4397 status == StatusInternal::PRESENT ?
4398 TorchModeStatus::AVAILABLE_OFF :
4399 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004400 if (torchStatus != newTorchStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07004401 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004402 }
4403 }
Ruben Brunkcc776712015-02-17 20:18:47 -08004404 }
4405
4406 Mutex::Autolock lock(mStatusListenerLock);
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004407 notifyPhysicalCameraStatusLocked(mapToInterface(status), String16(cameraId),
4408 logicalCameraIds, deviceKind);
Shuzhen Wang43858162020-01-10 13:42:15 -08004409
Ruben Brunkcc776712015-02-17 20:18:47 -08004410 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07004411 bool isVendorListener = listener->isVendorListener();
4412 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
4413 listener->getListenerPid(), listener->getListenerUid()) ||
Shuzhen Wangb8259792021-05-27 09:27:06 -07004414 isVendorListener) {
4415 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07004416 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08004417 continue;
4418 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07004419 listener->getListener()->onStatusChanged(mapToInterface(status),
Emilian Peev53722fa2019-02-22 17:47:20 -08004420 String16(cameraId));
Ruben Brunkcc776712015-02-17 20:18:47 -08004421 }
4422 });
Igor Murashkincba2c162013-03-20 15:56:31 -07004423}
4424
Shuzhen Wang695044d2020-03-06 09:02:23 -08004425void CameraService::updateOpenCloseStatus(const String8& cameraId, bool open,
4426 const String16& clientPackageName) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07004427 auto state = getCameraState(cameraId);
4428 if (state == nullptr) {
4429 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
4430 cameraId.string());
4431 return;
4432 }
4433 if (open) {
4434 state->setClientPackage(String8(clientPackageName));
4435 } else {
4436 state->setClientPackage(String8::empty());
4437 }
4438
Shuzhen Wang695044d2020-03-06 09:02:23 -08004439 Mutex::Autolock lock(mStatusListenerLock);
4440
4441 for (const auto& it : mListenerList) {
4442 if (!it->isOpenCloseCallbackAllowed()) {
4443 continue;
4444 }
4445
4446 binder::Status ret;
4447 String16 cameraId64(cameraId);
4448 if (open) {
4449 ret = it->getListener()->onCameraOpened(cameraId64, clientPackageName);
4450 } else {
4451 ret = it->getListener()->onCameraClosed(cameraId64);
4452 }
4453 if (!ret.isOk()) {
4454 ALOGE("%s: Failed to trigger onCameraOpened/onCameraClosed callback: %d", __FUNCTION__,
4455 ret.exceptionCode());
4456 }
4457 }
4458}
4459
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004460template<class Func>
4461void CameraService::CameraState::updateStatus(StatusInternal status,
4462 const String8& cameraId,
4463 std::initializer_list<StatusInternal> rejectSourceStates,
4464 Func onStatusUpdatedLocked) {
4465 Mutex::Autolock lock(mStatusLock);
4466 StatusInternal oldStatus = mStatus;
4467 mStatus = status;
4468
4469 if (oldStatus == status) {
4470 return;
4471 }
4472
4473 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
4474 cameraId.string(), oldStatus, status);
4475
4476 if (oldStatus == StatusInternal::NOT_PRESENT &&
4477 (status != StatusInternal::PRESENT &&
4478 status != StatusInternal::ENUMERATING)) {
4479
4480 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
4481 __FUNCTION__);
4482 mStatus = oldStatus;
4483 return;
4484 }
4485
4486 /**
4487 * Sometimes we want to conditionally do a transition.
4488 * For example if a client disconnects, we want to go to PRESENT
4489 * only if we weren't already in NOT_PRESENT or ENUMERATING.
4490 */
4491 for (auto& rejectStatus : rejectSourceStates) {
4492 if (oldStatus == rejectStatus) {
4493 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
4494 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
4495 mStatus = oldStatus;
4496 return;
4497 }
4498 }
4499
4500 onStatusUpdatedLocked(cameraId, status);
4501}
4502
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004503status_t CameraService::getTorchStatusLocked(
4504 const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004505 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004506 if (!status) {
4507 return BAD_VALUE;
4508 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004509 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
4510 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004511 // invalid camera ID or the camera doesn't have a flash unit
4512 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004513 }
4514
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004515 *status = mTorchStatusMap.valueAt(index);
4516 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004517}
4518
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004519status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004520 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004521 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
4522 if (index == NAME_NOT_FOUND) {
4523 return BAD_VALUE;
4524 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004525 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004526
4527 return OK;
4528}
4529
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004530std::list<String16> CameraService::getLogicalCameras(
4531 const String8& physicalCameraId) {
4532 std::list<String16> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08004533 Mutex::Autolock lock(mCameraStatesLock);
4534 for (const auto& state : mCameraStates) {
4535 std::vector<std::string> physicalCameraIds;
4536 if (!mCameraProviderManager->isLogicalCamera(state.first.c_str(), &physicalCameraIds)) {
4537 // This is not a logical multi-camera.
4538 continue;
4539 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004540 if (std::find(physicalCameraIds.begin(), physicalCameraIds.end(), physicalCameraId.c_str())
Shuzhen Wang43858162020-01-10 13:42:15 -08004541 == physicalCameraIds.end()) {
4542 // cameraId is not a physical camera of this logical multi-camera.
4543 continue;
4544 }
4545
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004546 retList.emplace_back(String16(state.first));
4547 }
4548 return retList;
4549}
4550
4551void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
4552 const String16& physicalCameraId, const std::list<String16>& logicalCameraIds,
4553 SystemCameraKind deviceKind) {
4554 // mStatusListenerLock is expected to be locked
4555 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08004556 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004557 // Note: we check only the deviceKind of the physical camera id
4558 // since, logical camera ids and their physical camera ids are
4559 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07004560 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
4561 listener->getListenerPid(), listener->getListenerUid())) {
4562 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004563 String8(physicalCameraId).c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07004564 continue;
4565 }
Shuzhen Wang43858162020-01-10 13:42:15 -08004566 listener->getListener()->onPhysicalCameraStatusChanged(status,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004567 logicalCameraId, physicalCameraId);
Shuzhen Wang43858162020-01-10 13:42:15 -08004568 }
4569 }
4570}
4571
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004572
Svet Ganova453d0d2018-01-11 15:37:58 -08004573void CameraService::blockClientsForUid(uid_t uid) {
4574 const auto clients = mActiveClientManager.getAll();
4575 for (auto& current : clients) {
4576 if (current != nullptr) {
4577 const auto basicClient = current->getValue();
4578 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
4579 basicClient->block();
4580 }
4581 }
4582 }
4583}
4584
Michael Grooverd1d435a2018-12-18 17:39:42 -08004585void CameraService::blockAllClients() {
4586 const auto clients = mActiveClientManager.getAll();
4587 for (auto& current : clients) {
4588 if (current != nullptr) {
4589 const auto basicClient = current->getValue();
4590 if (basicClient.get() != nullptr) {
4591 basicClient->block();
4592 }
4593 }
4594 }
4595}
4596
Svet Ganova453d0d2018-01-11 15:37:58 -08004597// NOTE: This is a remote API - make sure all args are validated
4598status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
4599 if (!checkCallingPermission(sManageCameraPermission, nullptr, nullptr)) {
4600 return PERMISSION_DENIED;
4601 }
4602 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
4603 return BAD_VALUE;
4604 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004605 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004606 return handleSetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07004607 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004608 return handleResetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07004609 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004610 return handleGetUidState(args, out, err);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004611 } else if (args.size() >= 2 && args[0] == String16("set-rotate-and-crop")) {
4612 return handleSetRotateAndCrop(args);
4613 } else if (args.size() >= 1 && args[0] == String16("get-rotate-and-crop")) {
4614 return handleGetRotateAndCrop(out);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004615 } else if (args.size() >= 2 && args[0] == String16("set-image-dump-mask")) {
4616 return handleSetImageDumpMask(args);
4617 } else if (args.size() >= 1 && args[0] == String16("get-image-dump-mask")) {
4618 return handleGetImageDumpMask(out);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004619 } else if (args.size() >= 2 && args[0] == String16("set-camera-mute")) {
4620 return handleSetCameraMute(args);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004621 } else if (args.size() >= 2 && args[0] == String16("watch")) {
Avichal Rakesh84147132021-11-11 17:47:11 -08004622 return handleWatchCommand(args, in, out);
Svet Ganova453d0d2018-01-11 15:37:58 -08004623 } else if (args.size() == 1 && args[0] == String16("help")) {
4624 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004625 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08004626 }
4627 printHelp(err);
4628 return BAD_VALUE;
4629}
4630
4631status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004632 String16 packageName = args[1];
4633
Svet Ganova453d0d2018-01-11 15:37:58 -08004634 bool active = false;
4635 if (args[2] == String16("active")) {
4636 active = true;
4637 } else if ((args[2] != String16("idle"))) {
4638 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
4639 return BAD_VALUE;
4640 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004641
4642 int userId = 0;
4643 if (args.size() >= 5 && args[3] == String16("--user")) {
4644 userId = atoi(String8(args[4]));
4645 }
4646
4647 uid_t uid;
4648 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
4649 return BAD_VALUE;
4650 }
4651
4652 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08004653 return NO_ERROR;
4654}
4655
4656status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004657 String16 packageName = args[1];
4658
4659 int userId = 0;
4660 if (args.size() >= 4 && args[2] == String16("--user")) {
4661 userId = atoi(String8(args[3]));
4662 }
4663
4664 uid_t uid;
4665 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004666 return BAD_VALUE;
4667 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004668
4669 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08004670 return NO_ERROR;
4671}
4672
4673status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004674 String16 packageName = args[1];
4675
4676 int userId = 0;
4677 if (args.size() >= 4 && args[2] == String16("--user")) {
4678 userId = atoi(String8(args[3]));
4679 }
4680
4681 uid_t uid;
4682 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004683 return BAD_VALUE;
4684 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004685
4686 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004687 return dprintf(out, "active\n");
4688 } else {
4689 return dprintf(out, "idle\n");
4690 }
4691}
4692
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004693status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
4694 int rotateValue = atoi(String8(args[1]));
4695 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
4696 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
4697 Mutex::Autolock lock(mServiceLock);
4698
4699 mOverrideRotateAndCropMode = rotateValue;
4700
4701 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
4702
4703 const auto clients = mActiveClientManager.getAll();
4704 for (auto& current : clients) {
4705 if (current != nullptr) {
4706 const auto basicClient = current->getValue();
4707 if (basicClient.get() != nullptr) {
4708 basicClient->setRotateAndCropOverride(rotateValue);
4709 }
4710 }
4711 }
4712
4713 return OK;
4714}
4715
4716status_t CameraService::handleGetRotateAndCrop(int out) {
4717 Mutex::Autolock lock(mServiceLock);
4718
4719 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
4720}
4721
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004722status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
4723 char *endPtr;
4724 errno = 0;
4725 String8 maskString8 = String8(args[1]);
4726 long maskValue = strtol(maskString8.c_str(), &endPtr, 10);
4727
4728 if (errno != 0) return BAD_VALUE;
4729 if (endPtr != maskString8.c_str() + maskString8.size()) return BAD_VALUE;
4730 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
4731
4732 Mutex::Autolock lock(mServiceLock);
4733
4734 mImageDumpMask = maskValue;
4735
4736 return OK;
4737}
4738
4739status_t CameraService::handleGetImageDumpMask(int out) {
4740 Mutex::Autolock lock(mServiceLock);
4741
4742 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
4743}
4744
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004745status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
4746 int muteValue = strtol(String8(args[1]), nullptr, 10);
4747 if (errno != 0) return BAD_VALUE;
4748
4749 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
4750 Mutex::Autolock lock(mServiceLock);
4751
4752 mOverrideCameraMuteMode = (muteValue == 1);
4753
4754 const auto clients = mActiveClientManager.getAll();
4755 for (auto& current : clients) {
4756 if (current != nullptr) {
4757 const auto basicClient = current->getValue();
4758 if (basicClient.get() != nullptr) {
4759 if (basicClient->supportsCameraMute()) {
4760 basicClient->setCameraMute(mOverrideCameraMuteMode);
4761 }
4762 }
4763 }
4764 }
4765
4766 return OK;
4767}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004768
Avichal Rakesh84147132021-11-11 17:47:11 -08004769status_t CameraService::handleWatchCommand(const Vector<String16>& args, int inFd, int outFd) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004770 if (args.size() >= 3 && args[1] == String16("start")) {
4771 return startWatchingTags(args, outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004772 } else if (args.size() == 2 && args[1] == String16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004773 return stopWatchingTags(outFd);
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08004774 } else if (args.size() == 2 && args[1] == String16("dump")) {
4775 return printWatchedTags(outFd);
4776 } else if (args.size() >= 2 && args[1] == String16("live")) {
4777 return printWatchedTagsUntilInterrupt(args, inFd, outFd);
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08004778 } else if (args.size() == 2 && args[1] == String16("clear")) {
4779 return clearCachedMonitoredTagDumps(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004780 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004781 dprintf(outFd, "Camera service watch commands:\n"
4782 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
4783 " starts watching the provided tags for clients with provided package\n"
4784 " recognizes tag shorthands like '3a'\n"
4785 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08004786 " dump dumps the monitoring information and exits\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004787 " stop stops watching all tags\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08004788 " live [-n <refresh_interval_ms>]\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004789 " prints the monitored information in real time\n"
Avichal Rakesh84147132021-11-11 17:47:11 -08004790 " Hit return to exit\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08004791 " clear clears all buffers storing information for watch command");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004792 return BAD_VALUE;
4793}
4794
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004795status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
4796 Mutex::Autolock lock(mLogLock);
4797 size_t tagsIdx; // index of '-m'
4798 String16 tags("");
4799 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != String16("-m"); tagsIdx++);
4800 if (tagsIdx < args.size() - 1) {
4801 tags = args[tagsIdx + 1];
4802 } else {
4803 dprintf(outFd, "No tags provided.\n");
4804 return BAD_VALUE;
4805 }
4806
4807 size_t clientsIdx; // index of '-c'
4808 String16 clients = kWatchAllClientsFlag; // watch all clients if no clients are provided
4809 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != String16("-c");
4810 clientsIdx++);
4811 if (clientsIdx < args.size() - 1) {
4812 clients = args[clientsIdx + 1];
4813 }
4814 parseClientsToWatchLocked(String8(clients));
4815
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004816 // track tags to initialize future clients with the monitoring information
4817 mMonitorTags = String8(tags);
4818
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004819 bool serviceLock = tryLock(mServiceLock);
4820 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004821 auto cameraClients = mActiveClientManager.getAll();
4822 for (const auto &clientDescriptor: cameraClients) {
4823 if (clientDescriptor == nullptr) { continue; }
4824 sp<BasicClient> client = clientDescriptor->getValue();
4825 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004826
4827 if (isClientWatchedLocked(client.get())) {
4828 client->startWatchingTags(mMonitorTags, outFd);
4829 numWatchedClients++;
4830 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004831 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004832 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
4833
4834 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004835 return OK;
4836}
4837
4838status_t CameraService::stopWatchingTags(int outFd) {
4839 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004840 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004841 mMonitorTags = String8::empty();
4842
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004843 mWatchedClientPackages.clear();
4844 mWatchedClientsDumpCache.clear();
4845
4846 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004847 auto cameraClients = mActiveClientManager.getAll();
4848 for (const auto &clientDescriptor : cameraClients) {
4849 if (clientDescriptor == nullptr) { continue; }
4850 sp<BasicClient> client = clientDescriptor->getValue();
4851 if (client.get() == nullptr) { continue; }
4852 client->stopWatchingTags(outFd);
4853 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004854 dprintf(outFd, "Stopped watching all clients.\n");
4855 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004856 return OK;
4857}
4858
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08004859status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
4860 Mutex::Autolock lock(mLogLock);
4861 size_t clearedSize = mWatchedClientsDumpCache.size();
4862 mWatchedClientsDumpCache.clear();
4863 dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
4864 return OK;
4865}
4866
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08004867status_t CameraService::printWatchedTags(int outFd) {
4868 Mutex::Autolock logLock(mLogLock);
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08004869 std::set<String16> connectedMonitoredClients;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004870
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08004871 bool printedSomething = false; // tracks if any monitoring information was printed
4872 // (from either cached or active clients)
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004873
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08004874 bool serviceLock = tryLock(mServiceLock);
4875 // get all watched clients that are currently connected
4876 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
4877 if (clientDescriptor == nullptr) { continue; }
4878
4879 sp<BasicClient> client = clientDescriptor->getValue();
4880 if (client.get() == nullptr) { continue; }
4881 if (!isClientWatchedLocked(client.get())) { continue; }
4882
4883 std::vector<std::string> dumpVector;
4884 client->dumpWatchedEventsToVector(dumpVector);
4885
4886 size_t printIdx = dumpVector.size();
4887 if (printIdx == 0) {
4888 continue;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004889 }
4890
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08004891 // Print tag dumps for active client
4892 const String8 &cameraId = clientDescriptor->getKey();
4893 String8 packageName8 = String8(client->getPackageName());
4894 const char *printablePackageName = packageName8.lockBuffer(packageName8.size());
4895 dprintf(outFd, "Client: %s (active)\n", printablePackageName);
4896 while(printIdx > 0) {
4897 printIdx--;
4898 dprintf(outFd, "%s:%s %s", cameraId.string(), printablePackageName,
4899 dumpVector[printIdx].c_str());
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08004900 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08004901 dprintf(outFd, "\n");
4902 packageName8.unlockBuffer();
4903 printedSomething = true;
4904
4905 connectedMonitoredClients.emplace(client->getPackageName());
4906 }
4907 if (serviceLock) { mServiceLock.unlock(); }
4908
4909 // Print entries in mWatchedClientsDumpCache for clients that are not connected
4910 for (const auto &kv: mWatchedClientsDumpCache) {
4911 const String16 &package = kv.first;
4912 if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
4913 continue;
4914 }
4915
4916 dprintf(outFd, "Client: %s (cached)\n", String8(package).string());
4917 dprintf(outFd, "%s\n", kv.second.c_str());
4918 printedSomething = true;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004919 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004920
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08004921 if (!printedSomething) {
4922 dprintf(outFd, "No monitoring information to print.\n");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004923 }
4924
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08004925 return OK;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004926}
4927
Avichal Rakesh84147132021-11-11 17:47:11 -08004928// Print all events in vector `events' that came after lastPrintedEvent
4929void printNewWatchedEvents(int outFd,
4930 const char *cameraId,
4931 const String16 &packageName,
4932 const std::vector<std::string> &events,
4933 const std::string &lastPrintedEvent) {
4934 if (events.empty()) { return; }
4935
4936 // index of lastPrintedEvent in events.
4937 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
4938 size_t lastPrintedIdx;
4939 for (lastPrintedIdx = 0;
4940 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
4941 lastPrintedIdx++);
4942
4943 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
4944
4945 String8 packageName8(packageName);
4946 const char *printablePackageName = packageName8.lockBuffer(packageName8.size());
4947
4948 // print events in chronological order (latest event last)
4949 size_t idxToPrint = lastPrintedIdx;
4950 do {
4951 idxToPrint--;
4952 dprintf(outFd, "%s:%s %s", cameraId, printablePackageName, events[idxToPrint].c_str());
4953 } while (idxToPrint != 0);
4954
4955 packageName8.unlockBuffer();
4956}
4957
4958// Returns true if adb shell cmd watch should be interrupted based on data in inFd. The watch
4959// command should be interrupted if the user presses the return key, or if user loses any way to
4960// signal interrupt.
4961// If timeoutMs == 0, this function will always return false
4962bool shouldInterruptWatchCommand(int inFd, int outFd, long timeoutMs) {
4963 struct timeval startTime;
4964 int startTimeError = gettimeofday(&startTime, nullptr);
4965 if (startTimeError) {
4966 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
4967 return true;
4968 }
4969
4970 const nfds_t numFds = 1;
4971 struct pollfd pollFd = { .fd = inFd, .events = POLLIN, .revents = 0 };
4972
4973 struct timeval currTime;
4974 char buffer[2];
4975 while(true) {
4976 int currTimeError = gettimeofday(&currTime, nullptr);
4977 if (currTimeError) {
4978 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
4979 return true;
4980 }
4981
4982 long elapsedTimeMs = ((currTime.tv_sec - startTime.tv_sec) * 1000L)
4983 + ((currTime.tv_usec - startTime.tv_usec) / 1000L);
4984 int remainingTimeMs = (int) (timeoutMs - elapsedTimeMs);
4985
4986 if (remainingTimeMs <= 0) {
4987 // No user interrupt within timeoutMs, don't interrupt watch command
4988 return false;
4989 }
4990
4991 int numFdsUpdated = poll(&pollFd, numFds, remainingTimeMs);
4992 if (numFdsUpdated < 0) {
4993 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
4994 return true;
4995 }
4996
4997 if (numFdsUpdated == 0) {
4998 // No user input within timeoutMs, don't interrupt watch command
4999 return false;
5000 }
5001
5002 if (!(pollFd.revents & POLLIN)) {
5003 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
5004 return true;
5005 }
5006
5007 ssize_t sizeRead = read(inFd, buffer, sizeof(buffer) - 1);
5008 if (sizeRead < 0) {
5009 dprintf(outFd, "Error reading user input. Exiting.\n");
5010 return true;
5011 }
5012
5013 if (sizeRead == 0) {
5014 // Reached end of input fd (can happen if input is piped)
5015 // User has no way to signal an interrupt, so interrupt here
5016 return true;
5017 }
5018
5019 if (buffer[0] == '\n') {
5020 // User pressed return, interrupt watch command.
5021 return true;
5022 }
5023 }
5024}
5025
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005026status_t CameraService::printWatchedTagsUntilInterrupt(const Vector<String16> &args,
5027 int inFd, int outFd) {
5028 // Figure out refresh interval, if present in args
5029 long refreshTimeoutMs = 1000L; // refresh every 1s by default
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005030 if (args.size() > 2) {
5031 size_t intervalIdx; // index of '-n'
5032 for (intervalIdx = 2; intervalIdx < args.size() && String16("-n") != args[intervalIdx];
5033 intervalIdx++);
5034
5035 size_t intervalValIdx = intervalIdx + 1;
5036 if (intervalValIdx < args.size()) {
5037 refreshTimeoutMs = strtol(String8(args[intervalValIdx].string()), nullptr, 10);
5038 if (errno) { return BAD_VALUE; }
5039 }
5040 }
5041
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005042 // Set min timeout of 10ms. This prevents edge cases in polling when timeout of 0 is passed.
5043 refreshTimeoutMs = refreshTimeoutMs < 10 ? 10 : refreshTimeoutMs;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005044
Avichal Rakesh84147132021-11-11 17:47:11 -08005045 dprintf(outFd, "Press return to exit...\n\n");
Avichal Rakesha14d9832021-11-11 01:41:55 -08005046 std::map<String16, std::string> packageNameToLastEvent;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005047
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005048 while (true) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08005049 bool serviceLock = tryLock(mServiceLock);
5050 auto cameraClients = mActiveClientManager.getAll();
5051 if (serviceLock) { mServiceLock.unlock(); }
5052
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005053 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005054 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005055 if (clientDescriptor == nullptr) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005056
5057 sp<BasicClient> client = clientDescriptor->getValue();
5058 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005059 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005060
Avichal Rakesha14d9832021-11-11 01:41:55 -08005061 const String16 &packageName = client->getPackageName();
5062 // This also initializes the map entries with an empty string
5063 const std::string& lastPrintedEvent = packageNameToLastEvent[packageName];
5064
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005065 std::vector<std::string> latestEvents;
5066 client->dumpWatchedEventsToVector(latestEvents);
5067
5068 if (!latestEvents.empty()) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08005069 String8 cameraId = clientDescriptor->getKey();
5070 const char *printableCameraId = cameraId.lockBuffer(cameraId.size());
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005071 printNewWatchedEvents(outFd,
Avichal Rakesha14d9832021-11-11 01:41:55 -08005072 printableCameraId,
5073 packageName,
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005074 latestEvents,
5075 lastPrintedEvent);
Avichal Rakesha14d9832021-11-11 01:41:55 -08005076 packageNameToLastEvent[packageName] = latestEvents[0];
5077 cameraId.unlockBuffer();
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005078 }
5079 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005080 if (shouldInterruptWatchCommand(inFd, outFd, refreshTimeoutMs)) {
Avichal Rakesh84147132021-11-11 17:47:11 -08005081 break;
5082 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005083 }
5084 return OK;
5085}
5086
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005087void CameraService::parseClientsToWatchLocked(String8 clients) {
5088 mWatchedClientPackages.clear();
5089
5090 const char *allSentinel = String8(kWatchAllClientsFlag).string();
5091
5092 char *tokenized = clients.lockBuffer(clients.size());
5093 char *savePtr;
5094 char *nextClient = strtok_r(tokenized, ",", &savePtr);
5095
5096 while (nextClient != nullptr) {
5097 if (strcmp(nextClient, allSentinel) == 0) {
5098 // Don't need to track any other package if 'all' is present
5099 mWatchedClientPackages.clear();
5100 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
5101 break;
5102 }
5103
5104 // track package names
5105 mWatchedClientPackages.emplace(nextClient);
5106 nextClient = strtok_r(nullptr, ",", &savePtr);
5107 }
5108 clients.unlockBuffer();
5109}
5110
Svet Ganova453d0d2018-01-11 15:37:58 -08005111status_t CameraService::printHelp(int out) {
5112 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07005113 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
5114 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
5115 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005116 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
5117 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
5118 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005119 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
5120 " Valid values 0=OFF, 1=ON for JPEG\n"
5121 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005122 " set-camera-mute <0/1> enable or disable camera muting\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005123 " watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08005124 " help print this message\n");
5125}
5126
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005127bool CameraService::isClientWatched(const BasicClient *client) {
5128 Mutex::Autolock lock(mLogLock);
5129 return isClientWatchedLocked(client);
5130}
5131
5132bool CameraService::isClientWatchedLocked(const BasicClient *client) {
5133 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
5134 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
5135}
5136
Yin-Chia Yehdba03232019-08-19 15:54:28 -07005137int32_t CameraService::updateAudioRestriction() {
5138 Mutex::Autolock lock(mServiceLock);
5139 return updateAudioRestrictionLocked();
5140}
5141
5142int32_t CameraService::updateAudioRestrictionLocked() {
5143 int32_t mode = 0;
5144 // iterate through all active client
5145 for (const auto& i : mActiveClientManager.getAll()) {
5146 const auto clientSp = i->getValue();
5147 mode |= clientSp->getAudioRestriction();
5148 }
5149
5150 bool modeChanged = (mAudioRestriction != mode);
5151 mAudioRestriction = mode;
5152 if (modeChanged) {
5153 mAppOps.setCameraAudioRestriction(mode);
5154 }
5155 return mode;
5156}
5157
Cliff Wu646bd612021-11-23 23:21:29 +08005158status_t CameraService::checkIfInjectionCameraIsPresent(const String8& externalCamId,
5159 sp<BasicClient> clientSp) {
5160 std::unique_ptr<AutoConditionLock> lock =
5161 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
5162 status_t res = NO_ERROR;
5163 if ((res = checkIfDeviceIsUsable(externalCamId)) != NO_ERROR) {
5164 ALOGW("Device %s is not usable!", externalCamId.string());
5165 mInjectionStatusListener->notifyInjectionError(
5166 externalCamId, UNKNOWN_TRANSACTION);
5167 clientSp->notifyError(
5168 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
5169 CaptureResultExtras());
5170
5171 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
5172 // other clients from connecting in mServiceLockWrapper if held
5173 mServiceLock.unlock();
5174
5175 // Clear caller identity temporarily so client disconnect PID checks work correctly
5176 int64_t token = CameraThreadState::clearCallingIdentity();
5177 clientSp->disconnect();
5178 CameraThreadState::restoreCallingIdentity(token);
5179
5180 // Reacquire mServiceLock
5181 mServiceLock.lock();
5182 }
5183
5184 return res;
5185}
5186
Cliff Wud3a05312021-04-26 23:07:31 +08005187void CameraService::clearInjectionParameters() {
5188 {
5189 Mutex::Autolock lock(mInjectionParametersLock);
Cliff Wu646bd612021-11-23 23:21:29 +08005190 mInjectionInitPending = false;
Cliff Wud3a05312021-04-26 23:07:31 +08005191 mInjectionInternalCamId = "";
5192 }
5193 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08005194 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08005195}
5196
Mathias Agopian65ab4712010-07-14 17:59:35 -07005197}; // namespace android