blob: eb24a93dade2f4aa3c6e00b404173fc8a54bb322 [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>
31
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080032#include <android/hardware/ICamera.h>
33#include <android/hardware/ICameraClient.h>
34
Alex Deymo9c2a2c22016-08-25 11:59:14 -070035#include <android-base/macros.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080036#include <android-base/parseint.h>
Jayant Chowdharyb61526c2019-05-13 19:37:42 -070037#include <android-base/stringprintf.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080038#include <binder/ActivityManager.h>
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -080039#include <binder/AppOpsManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070040#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070041#include <binder/MemoryBase.h>
42#include <binder/MemoryHeapBase.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080043#include <binder/PermissionController.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080044#include <binder/IResultReceiver.h>
Steven Moreland89a2c5c2020-01-31 15:02:25 -080045#include <binderthreadstate/CallerUtils.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070046#include <cutils/atomic.h>
Nipun Kwatrab5ca4612010-09-11 19:31:10 -070047#include <cutils/properties.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080048#include <cutils/misc.h>
Mathias Agopiandf712ea2012-02-25 18:48:35 -080049#include <gui/Surface.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070050#include <hardware/hardware.h>
Jayant Chowdharybe543d42018-08-15 13:16:14 -070051#include "hidl/HidlCameraService.h"
52#include <hidl/HidlTransportSupport.h>
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -080053#include <hwbinder/IPCThreadState.h>
Eino-Ville Talvalad89821e2016-04-20 11:23:50 -070054#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070055#include <media/AudioSystem.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080056#include <media/IMediaHTTPService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070057#include <media/mediaplayer.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070058#include <mediautils/BatteryNotifier.h>
Steven Moreland886d7322021-04-02 04:19:45 +000059#include <processinfo/ProcessInfoService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070060#include <utils/Errors.h>
61#include <utils/Log.h>
62#include <utils/String16.h>
Svet Ganov94ec46f2018-06-08 15:03:46 -070063#include <utils/SystemClock.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080064#include <utils/Trace.h>
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080065#include <utils/CallStack.h>
Chien-Yu Chen98a668f2015-12-18 14:10:33 -080066#include <private/android_filesystem_config.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080067#include <system/camera_vendor_tags.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070068#include <system/camera_metadata.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080069
Ruben Brunkb2119af2014-05-09 19:57:56 -070070#include <system/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070071
72#include "CameraService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070073#include "api1/Camera2Client.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070074#include "api2/CameraDeviceClient.h"
Igor Murashkinff3e31d2013-10-23 16:40:06 -070075#include "utils/CameraTraces.h"
Emilian Peevbd8c5032018-02-14 23:05:40 +000076#include "utils/TagMonitor.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070077#include "utils/CameraThreadState.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070078#include "utils/CameraServiceProxyWrapper.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070079
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080080namespace {
81 const char* kPermissionServiceName = "permission";
82}; // namespace anonymous
83
Mathias Agopian65ab4712010-07-14 17:59:35 -070084namespace android {
85
Jayant Chowdharyb61526c2019-05-13 19:37:42 -070086using base::StringPrintf;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080087using binder::Status;
Jayant Chowdharybe543d42018-08-15 13:16:14 -070088using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -080089using hardware::ICamera;
90using hardware::ICameraClient;
91using hardware::ICameraServiceListener;
92using hardware::camera::common::V1_0::CameraDeviceStatus;
93using hardware::camera::common::V1_0::TorchModeStatus;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080094using hardware::camera2::utils::CameraIdAndSessionConfiguration;
95using hardware::camera2::utils::ConcurrentCameraIdCombination;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080096
Mathias Agopian65ab4712010-07-14 17:59:35 -070097// ----------------------------------------------------------------------------
98// Logging support -- this is for debugging only
99// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700100volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700101
Steve Blockb8a80522011-12-20 16:23:08 +0000102#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
103#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700104
105static void setLogLevel(int level) {
106 android_atomic_write(level, &gLogLevel);
107}
108
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800109// Convenience methods for constructing binder::Status objects for error returns
110
111#define STATUS_ERROR(errorCode, errorString) \
112 binder::Status::fromServiceSpecificError(errorCode, \
113 String8::format("%s:%d: %s", __FUNCTION__, __LINE__, errorString))
114
115#define STATUS_ERROR_FMT(errorCode, errorString, ...) \
116 binder::Status::fromServiceSpecificError(errorCode, \
117 String8::format("%s:%d: " errorString, __FUNCTION__, __LINE__, \
118 __VA_ARGS__))
119
Mathias Agopian65ab4712010-07-14 17:59:35 -0700120// ----------------------------------------------------------------------------
121
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700122static const String16 sDumpPermission("android.permission.DUMP");
Svet Ganova453d0d2018-01-11 15:37:58 -0800123static const String16 sManageCameraPermission("android.permission.MANAGE_CAMERA");
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700124static const String16 sCameraPermission("android.permission.CAMERA");
125static const String16 sSystemCameraPermission("android.permission.SYSTEM_CAMERA");
126static const String16
127 sCameraSendSystemEventsPermission("android.permission.CAMERA_SEND_SYSTEM_EVENTS");
Shuzhen Wang695044d2020-03-06 09:02:23 -0800128static const String16 sCameraOpenCloseListenerPermission(
129 "android.permission.CAMERA_OPEN_CLOSE_LISTENER");
Svet Ganova453d0d2018-01-11 15:37:58 -0800130
Eino-Ville Talvala7c602c32021-03-20 17:00:18 -0700131static constexpr int32_t kVendorClientScore = resource_policy::PERCEPTIBLE_APP_ADJ;
132static constexpr int32_t kVendorClientState = ActivityManager::PROCESS_STATE_PERSISTENT_UI;
133
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800134const String8 CameraService::kOfflineDevice("offline-");
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700135
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800136CameraService::CameraService() :
137 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800138 mNumberOfCameras(0),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700139 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700140 mSoundRef(0), mInitialized(false),
141 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000142 ALOGI("CameraService started (pid=%d)", getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800143 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700144}
145
Iliyan Malchev8951a972011-04-14 16:55:59 -0700146void CameraService::onFirstRef()
147{
Ruben Brunkcc776712015-02-17 20:18:47 -0800148 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800149
Iliyan Malchev8951a972011-04-14 16:55:59 -0700150 BnCameraService::onFirstRef();
151
Ruben Brunk99e69712015-05-26 17:25:07 -0700152 // Update battery life tracking if service is restarting
153 BatteryNotifier& notifier(BatteryNotifier::getInstance());
154 notifier.noteResetCamera();
155 notifier.noteResetFlashlight();
156
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800157 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800158
Emilian Peevf53f66e2017-04-11 14:29:43 +0100159 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800160 if (res == OK) {
161 mInitialized = true;
162 }
163
Svet Ganova453d0d2018-01-11 15:37:58 -0800164 mUidPolicy = new UidPolicy(this);
165 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800166 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
167 mSensorPrivacyPolicy->registerSelf();
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700168 mAppOps.setCameraAudioRestriction(mAudioRestriction);
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700169 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
170 if (hcs->registerAsService() != android::OK) {
171 ALOGE("%s: Failed to register default android.frameworks.cameraservice.service@1.0",
172 __FUNCTION__);
173 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700174
175 // This needs to be last call in this function, so that it's as close to
176 // ServiceManager::addService() as possible.
Shuzhen Wang316781a2020-08-18 18:11:01 -0700177 CameraServiceProxyWrapper::pingCameraServiceProxy();
Shuzhen Wang24b44152019-09-20 10:38:11 -0700178 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800179}
180
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800181status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800182 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100183
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800184 std::vector<std::string> deviceIds;
185 {
186 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800187
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800188 if (nullptr == mCameraProviderManager.get()) {
189 mCameraProviderManager = new CameraProviderManager();
190 res = mCameraProviderManager->initialize(this);
191 if (res != OK) {
192 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
193 __FUNCTION__, strerror(-res), res);
194 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100195 }
196 }
197
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800198
199 // Setup vendor tags before we call get_camera_info the first time
200 // because HAL might need to setup static vendor keys in get_camera_info
201 // TODO: maybe put this into CameraProviderManager::initialize()?
202 mCameraProviderManager->setUpVendorTags();
203
204 if (nullptr == mFlashlight.get()) {
205 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700206 }
207
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800208 res = mFlashlight->findFlashUnits();
209 if (res != OK) {
210 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
211 }
212
213 deviceIds = mCameraProviderManager->getCameraDeviceIds();
214 }
215
216
217 for (auto& cameraId : deviceIds) {
218 String8 id8 = String8(cameraId.c_str());
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800219 if (getCameraState(id8) == nullptr) {
220 onDeviceStatusChanged(id8, CameraDeviceStatus::PRESENT);
221 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800222 }
223
224 return OK;
225}
226
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700227void CameraService::broadcastTorchModeStatus(const String8& cameraId, TorchModeStatus status,
228 SystemCameraKind systemCameraKind) {
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800229 Mutex::Autolock lock(mStatusListenerLock);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800230 for (auto& i : mListenerList) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700231 if (shouldSkipStatusUpdates(systemCameraKind, i->isVendorListener(), i->getListenerPid(),
232 i->getListenerUid())) {
233 ALOGV("Skipping torch callback for system-only camera device %s",
234 cameraId.c_str());
235 continue;
236 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700237 i->getListener()->onTorchStatusChanged(mapToInterface(status), String16{cameraId});
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800238 }
239}
240
Mathias Agopian65ab4712010-07-14 17:59:35 -0700241CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800242 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800243 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800244 mSensorPrivacyPolicy->unregisterSelf();
Evan Severson190ad252021-01-07 20:37:15 -0800245
246 for (auto const& [_, policy] : mCameraSensorPrivacyPolicies) {
247 policy->unregisterSelf();
248 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700249}
250
Emilian Peevaee727d2017-05-04 16:35:48 +0100251void CameraService::onNewProviderRegistered() {
252 enumerateProviders();
253}
254
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700255void CameraService::filterAPI1SystemCameraLocked(
256 const std::vector<std::string> &normalDeviceIds) {
257 mNormalDeviceIdsWithoutSystemCamera.clear();
258 for (auto &deviceId : normalDeviceIds) {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700259 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
260 if (getSystemCameraKind(String8(deviceId.c_str()), &deviceKind) != OK) {
261 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, deviceId.c_str());
262 continue;
263 }
264 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700265 // All system camera ids will necessarily come after public camera
266 // device ids as per the HAL interface contract.
267 break;
268 }
269 mNormalDeviceIdsWithoutSystemCamera.push_back(deviceId);
270 }
271 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
272 mNormalDeviceIdsWithoutSystemCamera.size());
273}
274
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700275status_t CameraService::getSystemCameraKind(const String8& cameraId, SystemCameraKind *kind) const {
276 auto state = getCameraState(cameraId);
277 if (state != nullptr) {
278 *kind = state->getSystemCameraKind();
279 return OK;
280 }
281 // Hidden physical camera ids won't have CameraState
282 return mCameraProviderManager->getSystemCameraKind(cameraId.c_str(), kind);
283}
284
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800285void CameraService::updateCameraNumAndIds() {
286 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700287 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
288 // Excludes hidden secure cameras
289 mNumberOfCameras =
290 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
291 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800292 mNormalDeviceIds =
293 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700294 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800295}
296
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100297void CameraService::addStates(const String8 id) {
298 std::string cameraId(id.c_str());
299 hardware::camera::common::V1_0::CameraResourceCost cost;
300 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700301 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100302 if (res != OK) {
303 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
304 return;
305 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700306 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
307 if (res != OK) {
308 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
309 return;
310 }
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100311 std::set<String8> conflicting;
312 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
313 conflicting.emplace(String8(cost.conflictingDevices[i].c_str()));
314 }
315
316 {
317 Mutex::Autolock lock(mCameraStatesLock);
318 mCameraStates.emplace(id, std::make_shared<CameraState>(id, cost.resourceCost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700319 conflicting, deviceKind));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100320 }
321
322 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100323 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100324 mTorchStatusMap.add(id, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800325
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700326 broadcastTorchModeStatus(id, TorchModeStatus::AVAILABLE_OFF, deviceKind);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100327 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800328
329 updateCameraNumAndIds();
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100330 logDeviceAdded(id, "Device added");
331}
332
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100333void CameraService::removeStates(const String8 id) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800334 updateCameraNumAndIds();
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100335 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100336 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100337 mTorchStatusMap.removeItem(id);
338 }
339
340 {
341 Mutex::Autolock lock(mCameraStatesLock);
342 mCameraStates.erase(id);
343 }
344}
345
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800346void CameraService::onDeviceStatusChanged(const String8& id,
347 CameraDeviceStatus newHalStatus) {
348 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
349 id.string(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700350
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800351 StatusInternal newStatus = mapToInternal(newHalStatus);
352
Ruben Brunkcc776712015-02-17 20:18:47 -0800353 std::shared_ptr<CameraState> state = getCameraState(id);
354
355 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700356 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100357 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700358 __FUNCTION__, id.string());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100359
360 // First add as absent to make sure clients are notified below
361 addStates(id);
362
363 updateStatus(newStatus, id);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700364 } else {
365 ALOGE("%s: Bad camera ID %s", __FUNCTION__, id.string());
366 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700367 return;
368 }
369
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800370 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800371
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800372 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800373 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700374 return;
375 }
376
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800377 if (newStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700378 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
379 newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800380
381 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
382 // to this device until the status changes
383 updateStatus(StatusInternal::NOT_PRESENT, id);
384
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800385 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700386 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800387 // Don't do this in updateStatus to avoid deadlock over mServiceLock
388 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700389
Ruben Brunkcc776712015-02-17 20:18:47 -0800390 // Remove cached shim parameters
391 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700392
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800393 // Remove online as well as offline client from the list of active clients,
394 // if they are present
395 clientToDisconnectOnline = removeClientLocked(id);
396 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + id);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700397 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800398
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800399 disconnectClient(id, clientToDisconnectOnline);
400 disconnectClient(kOfflineDevice + id, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700401
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100402 removeStates(id);
Ruben Brunkcc776712015-02-17 20:18:47 -0800403 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800404 if (oldStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700405 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
406 newStatus));
407 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800408 updateStatus(newStatus, id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700409 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800410}
Igor Murashkincba2c162013-03-20 15:56:31 -0700411
Shuzhen Wang43858162020-01-10 13:42:15 -0800412void CameraService::onDeviceStatusChanged(const String8& id,
413 const String8& physicalId,
414 CameraDeviceStatus newHalStatus) {
415 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
416 __FUNCTION__, id.string(), physicalId.string(), newHalStatus);
417
418 StatusInternal newStatus = mapToInternal(newHalStatus);
419
420 std::shared_ptr<CameraState> state = getCameraState(id);
421
422 if (state == nullptr) {
423 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
424 __FUNCTION__, id.string(), physicalId.string());
425 return;
426 }
427
428 StatusInternal logicalCameraStatus = state->getStatus();
429 if (logicalCameraStatus != StatusInternal::PRESENT &&
430 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
431 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
432 __FUNCTION__, physicalId.string(), newHalStatus, logicalCameraStatus);
433 return;
434 }
435
436 bool updated = false;
437 if (newStatus == StatusInternal::PRESENT) {
438 updated = state->removeUnavailablePhysicalId(physicalId);
439 } else {
440 updated = state->addUnavailablePhysicalId(physicalId);
441 }
442
443 if (updated) {
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800444 String8 idCombo = id + " : " + physicalId;
445 if (newStatus == StatusInternal::PRESENT) {
446 logDeviceAdded(idCombo,
447 String8::format("Device status changed to %d", newStatus));
448 } else {
449 logDeviceRemoved(idCombo,
450 String8::format("Device status changed to %d", newStatus));
451 }
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700452 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
453 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
454 if (getSystemCameraKind(id, &deviceKind) != OK) {
455 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.string());
456 return;
457 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800458 String16 id16(id), physicalId16(physicalId);
459 Mutex::Autolock lock(mStatusListenerLock);
460 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700461 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
462 listener->getListenerPid(), listener->getListenerUid())) {
463 ALOGV("Skipping discovery callback for system-only camera device %s",
464 id.c_str());
465 continue;
466 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800467 listener->getListener()->onPhysicalCameraStatusChanged(mapToInterface(newStatus),
468 id16, physicalId16);
469 }
470 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700471}
472
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800473void CameraService::disconnectClient(const String8& id, sp<BasicClient> clientToDisconnect) {
474 if (clientToDisconnect.get() != nullptr) {
475 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
476 __FUNCTION__, id.string());
477 // Notify the client of disconnection
478 clientToDisconnect->notifyError(
479 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
480 CaptureResultExtras{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800481 clientToDisconnect->disconnect();
482 }
483}
484
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800485void CameraService::onTorchStatusChanged(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800486 TorchModeStatus newStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700487 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
488 status_t res = getSystemCameraKind(cameraId, &systemCameraKind);
489 if (res != OK) {
490 ALOGE("%s: Could not get system camera kind for camera id %s", __FUNCTION__,
491 cameraId.string());
492 return;
493 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800494 Mutex::Autolock al(mTorchStatusMutex);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700495 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800496}
497
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800498void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700499 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800500 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
501 __FUNCTION__, cameraId.string(), newStatus);
502
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800503 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800504 status_t res = getTorchStatusLocked(cameraId, &status);
505 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700506 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
507 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800508 return;
509 }
510 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800511 return;
512 }
513
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800514 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800515 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800516 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
517 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800518 return;
519 }
520
Ruben Brunkcc776712015-02-17 20:18:47 -0800521 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700522 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700523 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700524 auto iter = mTorchUidMap.find(cameraId);
525 if (iter != mTorchUidMap.end()) {
526 int oldUid = iter->second.second;
527 int newUid = iter->second.first;
528 BatteryNotifier& notifier(BatteryNotifier::getInstance());
529 if (oldUid != newUid) {
530 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800531 if (status == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700532 notifier.noteFlashlightOff(cameraId, oldUid);
533 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800534 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700535 notifier.noteFlashlightOn(cameraId, newUid);
536 }
537 iter->second.second = newUid;
538 } else {
539 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800540 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700541 notifier.noteFlashlightOn(cameraId, oldUid);
542 } else {
543 notifier.noteFlashlightOff(cameraId, oldUid);
544 }
545 }
546 }
547 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700548 broadcastTorchModeStatus(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800549}
550
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700551static bool hasPermissionsForSystemCamera(int callingPid, int callingUid) {
552 return checkPermission(sSystemCameraPermission, callingPid, callingUid) &&
553 checkPermission(sCameraPermission, callingPid, callingUid);
554}
555
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800556Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700557 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100558 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700559 bool hasSystemCameraPermissions =
560 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
561 CameraThreadState::getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700562 switch (type) {
563 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700564 if (hasSystemCameraPermissions) {
565 *numCameras = static_cast<int>(mNormalDeviceIds.size());
566 } else {
567 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
568 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800569 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700570 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700571 if (hasSystemCameraPermissions) {
572 *numCameras = mNumberOfCameras;
573 } else {
574 *numCameras = mNumberOfCamerasWithoutSystemCamera;
575 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800576 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700577 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800578 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700579 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800580 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
581 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700582 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800583 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700584}
585
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800586Status CameraService::getCameraInfo(int cameraId,
587 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700588 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100589 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700590 std::string cameraIdStr = cameraIdIntToStrLocked(cameraId);
591 if (shouldRejectSystemCameraConnection(String8(cameraIdStr.c_str()))) {
592 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
593 "characteristics for system only device %s: ", cameraIdStr.c_str());
594 }
Emilian Peevaee727d2017-05-04 16:35:48 +0100595
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800596 if (!mInitialized) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800597 return STATUS_ERROR(ERROR_DISCONNECTED,
598 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -0700599 }
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700600 bool hasSystemCameraPermissions =
601 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
602 CameraThreadState::getCallingUid());
603 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
604 if (hasSystemCameraPermissions) {
605 cameraIdBound = mNumberOfCameras;
606 }
607 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800608 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
609 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700610 }
611
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800612 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800613 status_t err = mCameraProviderManager->getCameraInfo(
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700614 cameraIdStr.c_str(), cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100615 if (err != OK) {
616 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
617 "Error retrieving camera info from device %d: %s (%d)", cameraId,
618 strerror(-err), err);
Ruben Brunkcc776712015-02-17 20:18:47 -0800619 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100620
Ruben Brunkcc776712015-02-17 20:18:47 -0800621 return ret;
622}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700623
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800624std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700625 const std::vector<std::string> *deviceIds = &mNormalDeviceIdsWithoutSystemCamera;
626 auto callingPid = CameraThreadState::getCallingPid();
627 auto callingUid = CameraThreadState::getCallingUid();
628 if (checkPermission(sSystemCameraPermission, callingPid, callingUid) ||
629 getpid() == callingPid) {
630 deviceIds = &mNormalDeviceIds;
631 }
632 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(deviceIds->size())) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800633 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700634 __FUNCTION__, cameraIdInt, deviceIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800635 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800636 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800637
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700638 return (*deviceIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800639}
640
641String8 CameraService::cameraIdIntToStr(int cameraIdInt) {
642 Mutex::Autolock lock(mServiceLock);
643 return String8(cameraIdIntToStrLocked(cameraIdInt).c_str());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800644}
645
646Status CameraService::getCameraCharacteristics(const String16& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800647 CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700648 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700649 if (!cameraInfo) {
650 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800651 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -0700652 }
653
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800654 if (!mInitialized) {
655 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800656 return STATUS_ERROR(ERROR_DISCONNECTED,
657 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -0700658 }
659
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700660 if (shouldRejectSystemCameraConnection(String8(cameraId))) {
661 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
662 "characteristics for system only device %s: ", String8(cameraId).string());
663 }
664
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800665 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800666
Emilian Peevf53f66e2017-04-11 14:29:43 +0100667 status_t res = mCameraProviderManager->getCameraCharacteristics(
668 String8(cameraId).string(), cameraInfo);
669 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700670 if (res == NAME_NOT_FOUND) {
671 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
672 "characteristics for unknown device %s: %s (%d)", String8(cameraId).string(),
673 strerror(-res), res);
674 } else {
675 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
676 "characteristics for device %s: %s (%d)", String8(cameraId).string(),
677 strerror(-res), res);
678 }
Ruben Brunkb2119af2014-05-09 19:57:56 -0700679 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700680 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
681 if (getSystemCameraKind(String8(cameraId), &deviceKind) != OK) {
682 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, String8(cameraId).string());
683 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera kind "
684 "for device %s", String8(cameraId).string());
685 }
Jayant Chowdhary12361932018-08-27 14:46:13 -0700686 int callingPid = CameraThreadState::getCallingPid();
687 int callingUid = CameraThreadState::getCallingUid();
Emilian Peeve20c6372018-08-14 18:45:53 +0100688 std::vector<int32_t> tagsRemoved;
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700689 // If it's not calling from cameraserver, check the permission only if
690 // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
691 // it would've already been checked in shouldRejectSystemCameraConnection.
Emilian Peeve20c6372018-08-14 18:45:53 +0100692 if ((callingPid != getpid()) &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700693 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700694 !checkPermission(sCameraPermission, callingPid, callingUid)) {
Emilian Peeve20c6372018-08-14 18:45:53 +0100695 res = cameraInfo->removePermissionEntries(
696 mCameraProviderManager->getProviderTagIdLocked(String8(cameraId).string()),
697 &tagsRemoved);
698 if (res != OK) {
699 cameraInfo->clear();
700 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
701 " characteristics needing camera permission for device %s: %s (%d)",
702 String8(cameraId).string(), strerror(-res), res);
703 }
704 }
705
706 if (!tagsRemoved.empty()) {
707 res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
708 tagsRemoved.data(), tagsRemoved.size());
709 if (res != OK) {
710 cameraInfo->clear();
711 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
712 "keys needing permission for device %s: %s (%d)", String8(cameraId).string(),
713 strerror(-res), res);
714 }
715 }
716
Zhijun He2b59be82013-09-25 10:14:30 -0700717 return ret;
718}
719
Ruben Brunkcc776712015-02-17 20:18:47 -0800720String8 CameraService::getFormattedCurrentTime() {
721 time_t now = time(nullptr);
722 char formattedTime[64];
723 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
724 return String8(formattedTime);
725}
726
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800727Status CameraService::getCameraVendorTagDescriptor(
728 /*out*/
729 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700730 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800731 if (!mInitialized) {
732 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800733 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800734 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -0800735 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
736 if (globalDescriptor != nullptr) {
737 *desc = *(globalDescriptor.get());
738 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800739 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800740}
741
Emilian Peev71c73a22017-03-21 16:35:51 +0000742Status CameraService::getCameraVendorTagCache(
743 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
744 ATRACE_CALL();
745 if (!mInitialized) {
746 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
747 return STATUS_ERROR(ERROR_DISCONNECTED,
748 "Camera subsystem not available");
749 }
750 sp<VendorTagDescriptorCache> globalCache =
751 VendorTagDescriptorCache::getGlobalVendorTagCache();
752 if (globalCache != nullptr) {
753 *cache = *(globalCache.get());
754 }
755 return Status::ok();
756}
757
Emilian Peevb91f1802021-03-23 14:50:28 -0700758int CameraService::getDeviceVersion(const String8& cameraId, int* facing, int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700759 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800760
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800761 int deviceVersion = 0;
762
Emilian Peevf53f66e2017-04-11 14:29:43 +0100763 status_t res;
764 hardware::hidl_version maxVersion{0,0};
765 res = mCameraProviderManager->getHighestSupportedVersion(cameraId.string(),
766 &maxVersion);
767 if (res != OK) return -1;
768 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800769
Emilian Peevf53f66e2017-04-11 14:29:43 +0100770 hardware::CameraInfo info;
771 if (facing) {
772 res = mCameraProviderManager->getCameraInfo(cameraId.string(), &info);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -0800773 if (res != OK) return -1;
Emilian Peevf53f66e2017-04-11 14:29:43 +0100774 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -0700775 if (orientation) {
776 *orientation = info.orientation;
777 }
Igor Murashkin634a5152013-02-20 17:15:11 -0800778 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100779
Igor Murashkin634a5152013-02-20 17:15:11 -0800780 return deviceVersion;
781}
782
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800783Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700784 switch(err) {
785 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800786 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800787 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800788 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
789 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800790 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800791 return STATUS_ERROR(ERROR_DISCONNECTED,
792 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700793 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800794 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
795 "Camera HAL encountered error %d: %s",
796 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700797 }
Igor Murashkinbfc99152013-02-27 12:55:20 -0800798}
799
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800800Status CameraService::makeClient(const sp<CameraService>& cameraService,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800801 const sp<IInterface>& cameraCb, const String16& packageName,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700802 const std::optional<String16>& featureId, const String8& cameraId,
803 int api1CameraId, int facing, int clientPid, uid_t clientUid, int servicePid,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800804 int deviceVersion, apiLevel effectiveApiLevel,
Ruben Brunkcc776712015-02-17 20:18:47 -0800805 /*out*/sp<BasicClient>* client) {
806
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700807 // Create CameraClient based on device version reported by the HAL.
808 switch(deviceVersion) {
809 case CAMERA_DEVICE_API_VERSION_1_0:
810 ALOGE("Camera using old HAL version: %d", deviceVersion);
811 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
812 "Camera device \"%s\" HAL version %d no longer supported",
813 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800814 break;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700815 case CAMERA_DEVICE_API_VERSION_3_0:
816 case CAMERA_DEVICE_API_VERSION_3_1:
817 case CAMERA_DEVICE_API_VERSION_3_2:
818 case CAMERA_DEVICE_API_VERSION_3_3:
819 case CAMERA_DEVICE_API_VERSION_3_4:
820 case CAMERA_DEVICE_API_VERSION_3_5:
821 case CAMERA_DEVICE_API_VERSION_3_6:
Shuzhen Wang83bff122020-11-20 15:51:39 -0800822 case CAMERA_DEVICE_API_VERSION_3_7:
Ruben Brunkcc776712015-02-17 20:18:47 -0800823 if (effectiveApiLevel == API_1) { // Camera1 API route
824 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800825 *client = new Camera2Client(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800826 cameraId, api1CameraId,
827 facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700828 servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800829 } else { // Camera2 API route
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800830 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
831 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800832 *client = new CameraDeviceClient(cameraService, tmp, packageName, featureId,
833 cameraId, facing, clientPid, clientUid, servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800834 }
835 break;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700836 default:
Ruben Brunkcc776712015-02-17 20:18:47 -0800837 // Should not be reachable
838 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800839 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800840 "Camera device \"%s\" has unknown HAL version %d",
841 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800842 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800843 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800844}
845
Ruben Brunk6267b532015-04-30 17:44:07 -0700846String8 CameraService::toString(std::set<userid_t> intSet) {
847 String8 s("");
848 bool first = true;
849 for (userid_t i : intSet) {
850 if (first) {
851 s.appendFormat("%d", i);
852 first = false;
853 } else {
854 s.appendFormat(", %d", i);
855 }
856 }
857 return s;
858}
859
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800860int32_t CameraService::mapToInterface(TorchModeStatus status) {
861 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
862 switch (status) {
863 case TorchModeStatus::NOT_AVAILABLE:
864 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
865 break;
866 case TorchModeStatus::AVAILABLE_OFF:
867 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
868 break;
869 case TorchModeStatus::AVAILABLE_ON:
870 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
871 break;
872 default:
873 ALOGW("Unknown new flash status: %d", status);
874 }
875 return serviceStatus;
876}
877
878CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
879 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
880 switch (status) {
881 case CameraDeviceStatus::NOT_PRESENT:
882 serviceStatus = StatusInternal::NOT_PRESENT;
883 break;
884 case CameraDeviceStatus::PRESENT:
885 serviceStatus = StatusInternal::PRESENT;
886 break;
887 case CameraDeviceStatus::ENUMERATING:
888 serviceStatus = StatusInternal::ENUMERATING;
889 break;
890 default:
891 ALOGW("Unknown new HAL device status: %d", status);
892 }
893 return serviceStatus;
894}
895
896int32_t CameraService::mapToInterface(StatusInternal status) {
897 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
898 switch (status) {
899 case StatusInternal::NOT_PRESENT:
900 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
901 break;
902 case StatusInternal::PRESENT:
903 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
904 break;
905 case StatusInternal::ENUMERATING:
906 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
907 break;
908 case StatusInternal::NOT_AVAILABLE:
909 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
910 break;
911 case StatusInternal::UNKNOWN:
912 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
913 break;
914 default:
915 ALOGW("Unknown new internal device status: %d", status);
916 }
917 return serviceStatus;
918}
919
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800920Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -0700921 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700922
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800923 String16 internalPackageName("cameraserver");
Ruben Brunkcc776712015-02-17 20:18:47 -0800924 String8 id = String8::format("%d", cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800925 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800926 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800927 if (!(ret = connectHelper<ICameraClient,Client>(
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800928 sp<ICameraClient>{nullptr}, id, cameraId,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +0900929 internalPackageName, {}, uid, USE_CALLING_PID,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700930 API_1, /*shimUpdateOnly*/ true, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800931 ).isOk()) {
932 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
Ruben Brunkb2119af2014-05-09 19:57:56 -0700933 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800934 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700935}
936
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800937Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -0700938 /*out*/
939 CameraParameters* parameters) {
940
941 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
942
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800943 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -0700944
945 if (parameters == NULL) {
946 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800947 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -0700948 }
949
Ruben Brunkcc776712015-02-17 20:18:47 -0800950 String8 id = String8::format("%d", cameraId);
951
952 // Check if we already have parameters
953 {
954 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -0700955 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -0800956 auto cameraState = getCameraState(id);
957 if (cameraState == nullptr) {
958 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800959 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
960 "Invalid camera ID: %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -0800961 }
962 CameraParameters p = cameraState->getShimParams();
963 if (!p.isEmpty()) {
964 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800965 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700966 }
967 }
968
Jayant Chowdhary12361932018-08-27 14:46:13 -0700969 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -0800970 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -0700971 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800972 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800973 // Error already logged by callee
974 return ret;
975 }
976
977 // Check for parameters again
978 {
979 // Scope for service lock
980 Mutex::Autolock lock(mServiceLock);
981 auto cameraState = getCameraState(id);
982 if (cameraState == nullptr) {
983 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800984 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
985 "Invalid camera ID: %s", id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -0700986 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800987 CameraParameters p = cameraState->getShimParams();
988 if (!p.isEmpty()) {
989 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800990 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700991 }
992 }
993
Ruben Brunkcc776712015-02-17 20:18:47 -0800994 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
995 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800996 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -0700997}
998
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800999// Can camera service trust the caller based on the calling UID?
1000static bool isTrustedCallingUid(uid_t uid) {
1001 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001002 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001003 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001004 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001005 return true;
1006 default:
1007 return false;
1008 }
1009}
1010
Nicholas Sauera3620332019-04-03 14:05:17 -07001011static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1012 PermissionController pc;
1013 uid = pc.getPackageUid(packageName, 0);
1014 if (uid <= 0) {
1015 ALOGE("Unknown package: '%s'", String8(packageName).string());
1016 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
1017 return BAD_VALUE;
1018 }
1019
1020 if (userId < 0) {
1021 ALOGE("Invalid user: %d", userId);
1022 dprintf(err, "Invalid user: %d\n", userId);
1023 return BAD_VALUE;
1024 }
1025
1026 uid = multiuser_get_uid(userId, uid);
1027 return NO_ERROR;
1028}
1029
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001030Status CameraService::validateConnectLocked(const String8& cameraId,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001031 const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
1032 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001033
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001034#ifdef __BRILLO__
1035 UNUSED(clientName8);
1036 UNUSED(clientUid);
1037 UNUSED(clientPid);
1038 UNUSED(originalClientPid);
1039#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001040 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1041 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001042 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001043 return allowed;
1044 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001045#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001046
Jayant Chowdhary12361932018-08-27 14:46:13 -07001047 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001048
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001049 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001050 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1051 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001052 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1053 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001054 }
1055
Ruben Brunkcc776712015-02-17 20:18:47 -08001056 if (getCameraState(cameraId) == nullptr) {
1057 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1058 cameraId.string());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001059 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1060 "No camera device with ID \"%s\" available", cameraId.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001061 }
1062
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001063 status_t err = checkIfDeviceIsUsable(cameraId);
1064 if (err != NO_ERROR) {
1065 switch(err) {
1066 case -ENODEV:
1067 case -EBUSY:
1068 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1069 "No camera device with ID \"%s\" currently available", cameraId.string());
1070 default:
1071 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1072 "Unknown error connecting to ID \"%s\"", cameraId.string());
1073 }
1074 }
1075 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001076}
1077
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001078Status CameraService::validateClientPermissionsLocked(const String8& cameraId,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001079 const String8& clientName8, int& clientUid, int& clientPid,
1080 /*out*/int& originalClientPid) const {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001081 int callingPid = CameraThreadState::getCallingPid();
1082 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001083
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001084 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001085 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001086 clientUid = callingUid;
1087 } else if (!isTrustedCallingUid(callingUid)) {
1088 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1089 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001090 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1091 "Untrusted caller (calling PID %d, UID %d) trying to "
1092 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1093 callingPid, callingUid, cameraId.string(),
1094 clientName8.string(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001095 }
1096
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001097 // Check if we can trust clientPid
1098 if (clientPid == USE_CALLING_PID) {
1099 clientPid = callingPid;
1100 } else if (!isTrustedCallingUid(callingUid)) {
1101 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1102 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001103 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1104 "Untrusted caller (calling PID %d, UID %d) trying to "
1105 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1106 callingPid, callingUid, cameraId.string(),
1107 clientName8.string(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001108 }
1109
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001110 if (shouldRejectSystemCameraConnection(cameraId)) {
1111 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1112 cameraId.c_str());
1113 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
1114 "available", cameraId.string());
1115 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001116 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1117 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1118 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
1119 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
1120 "found while trying to query device kind", cameraId.string());
1121
1122 }
1123
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001124 // If it's not calling from cameraserver, check the permission if the
1125 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1126 // android.permission.SYSTEM_CAMERA for system only camera devices).
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001127 if (callingPid != getpid() &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001128 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001129 !checkPermission(sCameraPermission, clientPid, clientUid)) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001130 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001131 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1132 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
1133 clientName8.string(), clientUid, clientPid, cameraId.string());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001134 }
1135
Svet Ganova453d0d2018-01-11 15:37:58 -08001136 // Make sure the UID is in an active state to use the camera
Svet Ganov7b4ab782018-03-25 12:48:10 -07001137 if (!mUidPolicy->isUidActive(callingUid, String16(clientName8))) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001138 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001139 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1140 clientPid, clientUid);
1141 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001142 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1143 "calling UID %d proc state %" PRId32 ")",
1144 clientName8.string(), clientUid, clientPid, cameraId.string(),
1145 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001146 }
1147
Michael Grooverd1d435a2018-12-18 17:39:42 -08001148 // If sensor privacy is enabled then prevent access to the camera
1149 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1150 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1151 return STATUS_ERROR_FMT(ERROR_DISABLED,
1152 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
1153 "is enabled", clientName8.string(), clientUid, clientPid, cameraId.string());
1154 }
1155
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001156 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1157 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001158 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001159 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001160
Ruben Brunk6267b532015-04-30 17:44:07 -07001161 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001162
Ruben Brunka8ca9152015-04-07 14:23:40 -07001163 // Only allow clients who are being used by the current foreground device user, unless calling
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001164 // from our own process OR the caller is using the cameraserver's HIDL interface.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001165 if (getCurrentServingCall() != BinderCallType::HWBINDER && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001166 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001167 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1168 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
1169 toString(mAllowedUsers).string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001170 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1171 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
1172 clientUserId, cameraId.string());
Ruben Brunk36597b22015-03-20 22:15:57 -07001173 }
1174
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001175 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001176}
1177
1178status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
1179 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001180 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001181 if (cameraState == nullptr) {
1182 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1183 cameraId.string());
1184 return -ENODEV;
1185 }
1186
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001187 StatusInternal currentStatus = cameraState->getStatus();
1188 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001189 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
1190 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001191 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001192 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001193 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
1194 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001195 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001196 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001197
Ruben Brunkcc776712015-02-17 20:18:47 -08001198 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001199}
1200
Ruben Brunkcc776712015-02-17 20:18:47 -08001201void CameraService::finishConnectLocked(const sp<BasicClient>& client,
1202 const CameraService::DescriptorPtr& desc) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001203
Ruben Brunkcc776712015-02-17 20:18:47 -08001204 // Make a descriptor for the incoming client
1205 auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
1206 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1207
1208 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
1209 String8(client->getPackageName()));
1210
1211 if (evicted.size() > 0) {
1212 // This should never happen - clients should already have been removed in disconnect
1213 for (auto& i : evicted) {
1214 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
1215 __FUNCTION__, i->getKey().string());
1216 }
1217
1218 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1219 __FUNCTION__);
1220 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001221
1222 // And register a death notification for the client callback. Do
1223 // this last to avoid Binder policy where a nested Binder
1224 // transaction might be pre-empted to service the client death
1225 // notification if the client process dies before linkToDeath is
1226 // invoked.
1227 sp<IBinder> remoteCallback = client->getRemote();
1228 if (remoteCallback != nullptr) {
1229 remoteCallback->linkToDeath(this);
1230 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001231}
1232
1233status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
1234 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
1235 /*out*/
1236 sp<BasicClient>* client,
1237 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001238 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001239 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001240 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001241 DescriptorPtr clientDescriptor;
1242 {
1243 if (effectiveApiLevel == API_1) {
1244 // If we are using API1, any existing client for this camera ID with the same remote
1245 // should be returned rather than evicted to allow MediaRecorder to work properly.
1246
1247 auto current = mActiveClientManager.get(cameraId);
1248 if (current != nullptr) {
1249 auto clientSp = current->getValue();
1250 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001251 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
1252 ALOGW("CameraService connect called from same client, but with a different"
1253 " API level, evicting prior client...");
1254 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001255 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001256 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001257 *client = clientSp;
1258 return NO_ERROR;
1259 }
1260 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001261 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001262 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001263
Ruben Brunkcc776712015-02-17 20:18:47 -08001264 // Get current active client PIDs
1265 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1266 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001267
Emilian Peev8131a262017-02-01 12:33:43 +00001268 std::vector<int> priorityScores(ownerPids.size());
1269 std::vector<int> states(ownerPids.size());
Igor Murashkine6800ce2013-03-04 17:25:57 -08001270
Emilian Peev8131a262017-02-01 12:33:43 +00001271 // Get priority scores of all active PIDs
1272 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1273 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1274 /*out*/&priorityScores[0]);
1275 if (err != OK) {
1276 ALOGE("%s: Priority score query failed: %d",
1277 __FUNCTION__, err);
1278 return err;
1279 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001280
Ruben Brunkcc776712015-02-17 20:18:47 -08001281 // Update all active clients' priorities
Emilian Peev8131a262017-02-01 12:33:43 +00001282 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
Ruben Brunkcc776712015-02-17 20:18:47 -08001283 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
Emilian Peev8131a262017-02-01 12:33:43 +00001284 pidToPriorityMap.emplace(ownerPids[i],
Jayant Chowdharyc578a502019-05-08 10:57:54 -07001285 resource_policy::ClientPriority(priorityScores[i], states[i],
1286 /* isVendorClient won't get copied over*/ false));
Ruben Brunkcc776712015-02-17 20:18:47 -08001287 }
1288 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001289
Ruben Brunkcc776712015-02-17 20:18:47 -08001290 // Get state for the given cameraId
1291 auto state = getCameraState(cameraId);
1292 if (state == nullptr) {
1293 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1294 clientPid, cameraId.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001295 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001296 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001297 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001298
1299 // Make descriptor for incoming client
Shuzhen Wang2db86ff2018-04-25 01:11:17 +00001300 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001301 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1302 state->getConflicting(),
Emilian Peev8131a262017-02-01 12:33:43 +00001303 priorityScores[priorityScores.size() - 1],
1304 clientPid,
1305 states[states.size() - 1]);
Ruben Brunkcc776712015-02-17 20:18:47 -08001306
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001307 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1308
Ruben Brunkcc776712015-02-17 20:18:47 -08001309 // Find clients that would be evicted
1310 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1311
1312 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1313 // background, so we cannot do evictions
1314 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1315 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1316 " priority).", clientPid);
1317
1318 sp<BasicClient> clientSp = clientDescriptor->getValue();
1319 String8 curTime = getFormattedCurrentTime();
1320 auto incompatibleClients =
1321 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1322
1323 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Emilian Peev8131a262017-02-01 12:33:43 +00001324 "(PID %d, score %d state %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001325 cameraId.string(), packageName.string(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001326 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001327
1328 for (auto& i : incompatibleClients) {
1329 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001330 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
1331 i->getKey().string(),
1332 String8{i->getValue()->getPackageName()}.string(),
1333 i->getOwnerId(), i->getPriority().getScore(),
1334 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001335 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00001336 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(),
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001337 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001338 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001339 }
1340
1341 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001342 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001343 mEventLog.add(msg);
1344
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001345 auto current = mActiveClientManager.get(cameraId);
1346 if (current != nullptr) {
1347 return -EBUSY; // CAMERA_IN_USE
1348 } else {
1349 return -EUSERS; // MAX_CAMERAS_IN_USE
1350 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001351 }
1352
1353 for (auto& i : evicted) {
1354 sp<BasicClient> clientSp = i->getValue();
1355 if (clientSp.get() == nullptr) {
1356 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1357
1358 // TODO: Remove this
1359 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1360 __FUNCTION__);
1361 mActiveClientManager.remove(i);
1362 continue;
1363 }
1364
1365 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1366 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001367 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001368
Ruben Brunkcc776712015-02-17 20:18:47 -08001369 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001370 logEvent(String8::format("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00001371 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1372 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001373 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
Emilian Peev8131a262017-02-01 12:33:43 +00001374 i->getOwnerId(), i->getPriority().getScore(),
1375 i->getPriority().getState(), cameraId.string(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001376 packageName.string(), clientPid, clientPriority.getScore(),
1377 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08001378
1379 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001380 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001381 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001382 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001383 }
1384
Ruben Brunkcc776712015-02-17 20:18:47 -08001385 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1386 // other clients from connecting in mServiceLockWrapper if held
1387 mServiceLock.unlock();
1388
1389 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07001390 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001391
1392 // Destroy evicted clients
1393 for (auto& i : evictedClients) {
1394 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001395 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001396 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001397
Jayant Chowdhary12361932018-08-27 14:46:13 -07001398 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08001399
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001400 for (const auto& i : evictedClients) {
1401 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1402 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1403 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1404 if (ret == TIMED_OUT) {
1405 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1406 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1407 mActiveClientManager.toString().string());
1408 return -EBUSY;
1409 }
1410 if (ret != NO_ERROR) {
1411 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1412 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1413 ret, mActiveClientManager.toString().string());
1414 return ret;
1415 }
1416 }
1417
1418 evictedClients.clear();
1419
Ruben Brunkcc776712015-02-17 20:18:47 -08001420 // Once clients have been disconnected, relock
1421 mServiceLock.lock();
1422
1423 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1424 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1425 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001426 }
1427
Ruben Brunkcc776712015-02-17 20:18:47 -08001428 *partial = clientDescriptor;
1429 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001430}
1431
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001432Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001433 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001434 int api1CameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001435 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001436 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001437 int clientPid,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001438 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001439 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001440
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001441 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001442 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001443
1444 String8 id = cameraIdIntToStr(api1CameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001445 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001446 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001447 clientPackageName, {}, clientUid, clientPid, API_1,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001448 /*shimUpdateOnly*/ false, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001449
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001450 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001451 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001452 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001453 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001454 }
1455
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001456 *device = client;
1457 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001458}
1459
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001460bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
1461 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001462 // If the client is not a vendor client, don't add listener if
1463 // a) the camera is a publicly hidden secure camera OR
1464 // b) the camera is a system only camera and the client doesn't
1465 // have android.permission.SYSTEM_CAMERA permissions.
1466 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
1467 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1468 !hasPermissionsForSystemCamera(clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001469 return true;
1470 }
1471 return false;
1472}
1473
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001474bool CameraService::shouldRejectSystemCameraConnection(const String8& cameraId) const {
1475 // Rules for rejection:
1476 // 1) If cameraserver tries to access this camera device, accept the
1477 // connection.
1478 // 2) The camera device is a publicly hidden secure camera device AND some
1479 // component is trying to access it on a non-hwbinder thread (generally a non HAL client),
1480 // reject it.
1481 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
1482 // and the serving thread is a non hwbinder thread, the client must have
1483 // android.permission.SYSTEM_CAMERA permissions to connect.
1484
1485 int cPid = CameraThreadState::getCallingPid();
1486 int cUid = CameraThreadState::getCallingUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001487 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
1488 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001489 // This isn't a known camera ID, so it's not a system camera
1490 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
1491 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001492 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001493
1494 // (1) Cameraserver trying to connect, accept.
1495 if (CameraThreadState::getCallingPid() == getpid()) {
1496 return false;
1497 }
1498 // (2)
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001499 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001500 systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
1501 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
1502 return true;
1503 }
1504 // (3) Here we only check for permissions if it is a system only camera device. This is since
1505 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
1506 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
1507 // same behavior for system camera devices.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001508 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001509 systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1510 !hasPermissionsForSystemCamera(cPid, cUid)) {
1511 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
1512 cameraId.c_str());
1513 return true;
1514 }
1515
1516 return false;
1517}
1518
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001519Status CameraService::connectDevice(
1520 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001521 const String16& cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001522 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001523 const std::optional<String16>& clientFeatureId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001524 int clientUid,
1525 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001526 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001527
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001528 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001529 Status ret = Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001530 String8 id = String8(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001531 sp<CameraDeviceClient> client = nullptr;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001532 String16 clientPackageNameAdj = clientPackageName;
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001533
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001534 if (getCurrentServingCall() == BinderCallType::HWBINDER) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001535 std::string vendorClient =
1536 StringPrintf("vendor.client.pid<%d>", CameraThreadState::getCallingPid());
1537 clientPackageNameAdj = String16(vendorClient.c_str());
1538 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001539 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001540 /*api1CameraId*/-1, clientPackageNameAdj, clientFeatureId,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001541 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08001542
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001543 if(!ret.isOk()) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001544 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageNameAdj),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001545 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001546 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001547 }
1548
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001549 *device = client;
1550 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001551}
1552
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001553template<class CALLBACK, class CLIENT>
1554Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001555 int api1CameraId, const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001556 const std::optional<String16>& clientFeatureId, int clientUid, int clientPid,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001557 apiLevel effectiveApiLevel, bool shimUpdateOnly,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001558 /*out*/sp<CLIENT>& device) {
1559 binder::Status ret = binder::Status::ok();
1560
1561 String8 clientName8(clientPackageName);
1562
1563 int originalClientPid = 0;
1564
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001565 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001566 "Camera API version %d", clientPid, clientName8.string(), cameraId.string(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001567 static_cast<int>(effectiveApiLevel));
1568
Shuzhen Wang316781a2020-08-18 18:11:01 -07001569 nsecs_t openTimeNs = systemTime();
1570
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001571 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001572 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07001573 int orientation = 0;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001574 bool isNdk = (clientPackageName.size() == 0);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001575 {
1576 // Acquire mServiceLock and prevent other clients from connecting
1577 std::unique_ptr<AutoConditionLock> lock =
1578 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1579
1580 if (lock == nullptr) {
1581 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
1582 , clientPid);
1583 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1584 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
1585 cameraId.string(), clientName8.string(), clientPid);
1586 }
1587
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07001588 // Enforce client permissions and do basic validity checks
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001589 if(!(ret = validateConnectLocked(cameraId, clientName8,
1590 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
1591 return ret;
1592 }
1593
1594 // Check the shim parameters after acquiring lock, if they have already been updated and
1595 // we were doing a shim update, return immediately
1596 if (shimUpdateOnly) {
1597 auto cameraState = getCameraState(cameraId);
1598 if (cameraState != nullptr) {
1599 if (!cameraState->getShimParams().isEmpty()) return ret;
1600 }
1601 }
1602
1603 status_t err;
1604
1605 sp<BasicClient> clientTmp = nullptr;
1606 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
1607 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
1608 IInterface::asBinder(cameraCb), clientName8, /*out*/&clientTmp,
1609 /*out*/&partial)) != NO_ERROR) {
1610 switch (err) {
1611 case -ENODEV:
1612 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1613 "No camera device with ID \"%s\" currently available",
1614 cameraId.string());
1615 case -EBUSY:
1616 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1617 "Higher-priority client using camera, ID \"%s\" currently unavailable",
1618 cameraId.string());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001619 case -EUSERS:
1620 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1621 "Too many cameras already open, cannot open camera \"%s\"",
1622 cameraId.string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001623 default:
1624 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1625 "Unexpected error %s (%d) opening camera \"%s\"",
1626 strerror(-err), err, cameraId.string());
1627 }
1628 }
1629
1630 if (clientTmp.get() != nullptr) {
1631 // Handle special case for API1 MediaRecorder where the existing client is returned
1632 device = static_cast<CLIENT*>(clientTmp.get());
1633 return ret;
1634 }
1635
1636 // give flashlight a chance to close devices if necessary.
1637 mFlashlight->prepareDeviceOpen(cameraId);
1638
Emilian Peevb91f1802021-03-23 14:50:28 -07001639 int deviceVersion = getDeviceVersion(cameraId, /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08001640 if (facing == -1) {
1641 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.string());
1642 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1643 "Unable to get camera device \"%s\" facing", cameraId.string());
1644 }
1645
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001646 sp<BasicClient> tmp = nullptr;
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001647 if(!(ret = makeClient(this, cameraCb, clientPackageName, clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001648 cameraId, api1CameraId, facing,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001649 clientPid, clientUid, getpid(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001650 deviceVersion, effectiveApiLevel,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001651 /*out*/&tmp)).isOk()) {
1652 return ret;
1653 }
1654 client = static_cast<CLIENT*>(tmp.get());
1655
1656 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
1657 __FUNCTION__);
1658
Emilian Peevbd8c5032018-02-14 23:05:40 +00001659 err = client->initialize(mCameraProviderManager, mMonitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001660 if (err != OK) {
1661 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001662 // Errors could be from the HAL module open call or from AppOpsManager
1663 switch(err) {
1664 case BAD_VALUE:
1665 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1666 "Illegal argument to HAL module for camera \"%s\"", cameraId.string());
1667 case -EBUSY:
1668 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1669 "Camera \"%s\" is already open", cameraId.string());
1670 case -EUSERS:
1671 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1672 "Too many cameras already open, cannot open camera \"%s\"",
1673 cameraId.string());
1674 case PERMISSION_DENIED:
1675 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1676 "No permission to open camera \"%s\"", cameraId.string());
1677 case -EACCES:
1678 return STATUS_ERROR_FMT(ERROR_DISABLED,
1679 "Camera \"%s\" disabled by policy", cameraId.string());
1680 case -ENODEV:
1681 default:
1682 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1683 "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
1684 strerror(-err), err);
1685 }
1686 }
1687
1688 // Update shim paremeters for legacy clients
1689 if (effectiveApiLevel == API_1) {
1690 // Assume we have always received a Client subclass for API1
1691 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
1692 String8 rawParams = shimClient->getParameters();
1693 CameraParameters params(rawParams);
1694
1695 auto cameraState = getCameraState(cameraId);
1696 if (cameraState != nullptr) {
1697 cameraState->setShimParams(params);
1698 } else {
1699 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
1700 __FUNCTION__, cameraId.string());
1701 }
1702 }
1703
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001704 // Set rotate-and-crop override behavior
1705 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
1706 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
Emilian Peevb91f1802021-03-23 14:50:28 -07001707 } else if (CameraServiceProxyWrapper::isRotateAndCropOverrideNeeded(clientPackageName,
1708 orientation, facing)) {
1709 client->setRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_90);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001710 }
1711
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08001712 // Set camera muting behavior
1713 if (client->supportsCameraMute()) {
Evan Severson190ad252021-01-07 20:37:15 -08001714 client->setCameraMute(mOverrideCameraMuteMode ||
1715 isUserSensorPrivacyEnabledForUid(clientUid));
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08001716 }
1717
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001718 if (shimUpdateOnly) {
1719 // If only updating legacy shim parameters, immediately disconnect client
1720 mServiceLock.unlock();
1721 client->disconnect();
1722 mServiceLock.lock();
1723 } else {
1724 // Otherwise, add client to active clients list
1725 finishConnectLocked(client, partial);
1726 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001727
1728 client->setImageDumpMask(mImageDumpMask);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001729 } // lock is destroyed, allow further connect calls
1730
1731 // Important: release the mutex here so the client can call back into the service from its
1732 // destructor (can be at the end of the call)
1733 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001734
1735 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
1736 CameraServiceProxyWrapper::logOpen(cameraId, facing, clientPackageName,
1737 effectiveApiLevel, isNdk, openLatencyMs);
1738
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001739 return ret;
1740}
1741
Emilian Peevb2bc5a42019-11-20 16:02:14 -08001742status_t CameraService::addOfflineClient(String8 cameraId, sp<BasicClient> offlineClient) {
1743 if (offlineClient.get() == nullptr) {
1744 return BAD_VALUE;
1745 }
1746
1747 {
1748 // Acquire mServiceLock and prevent other clients from connecting
1749 std::unique_ptr<AutoConditionLock> lock =
1750 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1751
1752 if (lock == nullptr) {
1753 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
1754 , __FUNCTION__, offlineClient->getClientPid());
1755 return TIMED_OUT;
1756 }
1757
1758 auto onlineClientDesc = mActiveClientManager.get(cameraId);
1759 if (onlineClientDesc.get() == nullptr) {
1760 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
1761 cameraId.c_str());
1762 return BAD_VALUE;
1763 }
1764
1765 // Offline clients do not evict or conflict with other online devices. Resource sharing
1766 // conflicts are handled by the camera provider which will either succeed or fail before
1767 // reaching this method.
1768 const auto& onlinePriority = onlineClientDesc->getPriority();
1769 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
1770 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
1771 /*conflictingKeys*/ std::set<String8>(), onlinePriority.getScore(),
1772 onlineClientDesc->getOwnerId(), onlinePriority.getState());
1773
1774 // Allow only one offline device per camera
1775 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
1776 if (!incompatibleClients.empty()) {
1777 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
1778 return BAD_VALUE;
1779 }
1780
1781 auto err = offlineClient->initialize(mCameraProviderManager, mMonitorTags);
1782 if (err != OK) {
1783 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
1784 return err;
1785 }
1786
1787 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
1788 if (evicted.size() > 0) {
1789 for (auto& i : evicted) {
1790 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
1791 __FUNCTION__, i->getKey().string());
1792 }
1793
1794 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
1795 "properly", __FUNCTION__);
1796
1797 return BAD_VALUE;
1798 }
1799
1800 logConnectedOffline(offlineClientDesc->getKey(),
1801 static_cast<int>(offlineClientDesc->getOwnerId()),
1802 String8(offlineClient->getPackageName()));
1803
1804 sp<IBinder> remoteCallback = offlineClient->getRemote();
1805 if (remoteCallback != nullptr) {
1806 remoteCallback->linkToDeath(this);
1807 }
1808 } // lock is destroyed, allow further connect calls
1809
1810 return OK;
1811}
1812
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001813Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001814 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001815 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001816
1817 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07001818 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001819 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001820 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1821 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001822 }
1823
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001824 String8 id = String8(cameraId.string());
Jayant Chowdhary12361932018-08-27 14:46:13 -07001825 int uid = CameraThreadState::getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001826
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07001827 if (shouldRejectSystemCameraConnection(id)) {
1828 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
1829 " for system only device %s: ", id.string());
1830 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001831 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08001832 auto state = getCameraState(id);
1833 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001834 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001835 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1836 "Camera ID \"%s\" is a not valid camera ID", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001837 }
1838
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001839 StatusInternal cameraStatus = state->getStatus();
1840 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001841 cameraStatus != StatusInternal::NOT_AVAILABLE) {
1842 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001843 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1844 "Camera ID \"%s\" is a not valid camera ID", id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001845 }
1846
1847 {
1848 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001849 TorchModeStatus status;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001850 status_t err = getTorchStatusLocked(id, &status);
1851 if (err != OK) {
1852 if (err == NAME_NOT_FOUND) {
1853 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1854 "Camera \"%s\" does not have a flash unit", id.string());
1855 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001856 ALOGE("%s: getting current torch status failed for camera %s",
1857 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001858 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1859 "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
1860 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001861 }
1862
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001863 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001864 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001865 ALOGE("%s: torch mode of camera %s is not available because "
1866 "camera is in use", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001867 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1868 "Torch for camera \"%s\" is not available due to an existing camera user",
1869 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001870 } else {
1871 ALOGE("%s: torch mode of camera %s is not available due to "
1872 "insufficient resources", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001873 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1874 "Torch for camera \"%s\" is not available due to insufficient resources",
1875 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001876 }
1877 }
1878 }
1879
Ruben Brunk99e69712015-05-26 17:25:07 -07001880 {
1881 // Update UID map - this is used in the torch status changed callbacks, so must be done
1882 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07001883 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -07001884 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
1885 mTorchUidMap[id].first = uid;
1886 mTorchUidMap[id].second = uid;
1887 } else {
1888 // Set the pending UID
1889 mTorchUidMap[id].first = uid;
1890 }
1891 }
1892
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001893 status_t err = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07001894
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001895 if (err != OK) {
1896 int32_t errorCode;
1897 String8 msg;
1898 switch (err) {
1899 case -ENOSYS:
1900 msg = String8::format("Camera \"%s\" has no flashlight",
1901 id.string());
1902 errorCode = ERROR_ILLEGAL_ARGUMENT;
1903 break;
1904 default:
1905 msg = String8::format(
1906 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
1907 id.string(), enabled, strerror(-err), err);
1908 errorCode = ERROR_INVALID_OPERATION;
1909 }
1910 ALOGE("%s: %s", __FUNCTION__, msg.string());
1911 return STATUS_ERROR(errorCode, msg.string());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001912 }
1913
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001914 {
1915 // update the link to client's death
1916 Mutex::Autolock al(mTorchClientMapMutex);
1917 ssize_t index = mTorchClientMap.indexOfKey(id);
1918 if (enabled) {
1919 if (index == NAME_NOT_FOUND) {
1920 mTorchClientMap.add(id, clientBinder);
1921 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07001922 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001923 mTorchClientMap.replaceValueAt(index, clientBinder);
1924 }
1925 clientBinder->linkToDeath(this);
1926 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07001927 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001928 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001929 }
1930
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07001931 int clientPid = CameraThreadState::getCallingPid();
1932 const char *id_cstr = id.c_str();
1933 const char *torchState = enabled ? "on" : "off";
1934 ALOGI("Torch for camera id %s turned %s for client PID %d", id_cstr, torchState, clientPid);
1935 logTorchEvent(id_cstr, torchState , clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001936 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001937}
1938
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001939Status CameraService::notifySystemEvent(int32_t eventId,
1940 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001941 const int pid = CameraThreadState::getCallingPid();
1942 const int selfPid = getpid();
1943
1944 // Permission checks
1945 if (pid != selfPid) {
1946 // Ensure we're being called by system_server, or similar process with
1947 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001948 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001949 const int uid = CameraThreadState::getCallingUid();
1950 ALOGE("Permission Denial: cannot send updates to camera service about system"
1951 " events from pid=%d, uid=%d", pid, uid);
1952 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09001953 "No permission to send updates to camera service about system events"
1954 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001955 }
1956 }
1957
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001958 ATRACE_CALL();
1959
Ruben Brunk36597b22015-03-20 22:15:57 -07001960 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001961 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001962 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07001963 // from a system server crash
1964 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08001965 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001966 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07001967 break;
1968 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001969 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07001970 default: {
1971 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
1972 eventId);
1973 break;
1974 }
1975 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001976 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07001977}
1978
Emilian Peev53722fa2019-02-22 17:47:20 -08001979void CameraService::notifyMonitoredUids() {
1980 Mutex::Autolock lock(mStatusListenerLock);
1981
1982 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001983 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Emilian Peev53722fa2019-02-22 17:47:20 -08001984 if (!ret.isOk()) {
1985 ALOGE("%s: Failed to trigger permission callback: %d", __FUNCTION__,
1986 ret.exceptionCode());
1987 }
1988 }
1989}
1990
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08001991Status CameraService::notifyDeviceStateChange(int64_t newState) {
1992 const int pid = CameraThreadState::getCallingPid();
1993 const int selfPid = getpid();
1994
1995 // Permission checks
1996 if (pid != selfPid) {
1997 // Ensure we're being called by system_server, or similar process with
1998 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001999 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002000 const int uid = CameraThreadState::getCallingUid();
2001 ALOGE("Permission Denial: cannot send updates to camera service about device"
2002 " state changes from pid=%d, uid=%d", pid, uid);
2003 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2004 "No permission to send updates to camera service about device state"
2005 " changes from pid=%d, uid=%d", pid, uid);
2006 }
2007 }
2008
2009 ATRACE_CALL();
2010
2011 using hardware::camera::provider::V2_5::DeviceState;
2012 hardware::hidl_bitfield<DeviceState> newDeviceState{};
2013 if (newState & ICameraService::DEVICE_STATE_BACK_COVERED) {
2014 newDeviceState |= DeviceState::BACK_COVERED;
2015 }
2016 if (newState & ICameraService::DEVICE_STATE_FRONT_COVERED) {
2017 newDeviceState |= DeviceState::FRONT_COVERED;
2018 }
2019 if (newState & ICameraService::DEVICE_STATE_FOLDED) {
2020 newDeviceState |= DeviceState::FOLDED;
2021 }
2022 // Only map vendor bits directly
2023 uint64_t vendorBits = static_cast<uint64_t>(newState) & 0xFFFFFFFF00000000l;
2024 newDeviceState |= vendorBits;
2025
2026 ALOGV("%s: New device state 0x%" PRIx64, __FUNCTION__, newDeviceState);
2027 Mutex::Autolock l(mServiceLock);
2028 mCameraProviderManager->notifyDeviceStateChange(newDeviceState);
2029
2030 return Status::ok();
2031}
2032
Jayant Chowdharycad23c22020-03-10 15:04:59 -07002033 Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002034 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
2035 ATRACE_CALL();
2036 if (!concurrentCameraIds) {
2037 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
2038 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
2039 }
2040
2041 if (!mInitialized) {
2042 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2043 return STATUS_ERROR(ERROR_DISCONNECTED,
2044 "Camera subsystem is not available");
2045 }
2046 // First call into the provider and get the set of concurrent camera
2047 // combinations
2048 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07002049 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002050 for (auto &combination : concurrentCameraCombinations) {
2051 std::vector<std::string> validCombination;
2052 for (auto &cameraId : combination) {
2053 // if the camera state is not present, skip
2054 String8 cameraIdStr(cameraId.c_str());
2055 auto state = getCameraState(cameraIdStr);
2056 if (state == nullptr) {
2057 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
2058 continue;
2059 }
2060 StatusInternal status = state->getStatus();
2061 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
2062 continue;
2063 }
2064 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
2065 continue;
2066 }
2067 validCombination.push_back(cameraId);
2068 }
2069 if (validCombination.size() != 0) {
2070 concurrentCameraIds->push_back(std::move(validCombination));
2071 }
2072 }
2073 return Status::ok();
2074}
2075
2076Status CameraService::isConcurrentSessionConfigurationSupported(
2077 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
2078 /*out*/bool* isSupported) {
2079 if (!isSupported) {
2080 ALOGE("%s: isSupported is NULL", __FUNCTION__);
2081 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
2082 }
2083
2084 if (!mInitialized) {
2085 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2086 return STATUS_ERROR(ERROR_DISCONNECTED,
2087 "Camera subsystem is not available");
2088 }
2089
2090 // Check for camera permissions
2091 int callingPid = CameraThreadState::getCallingPid();
2092 int callingUid = CameraThreadState::getCallingUid();
2093 if ((callingPid != getpid()) && !checkPermission(sCameraPermission, callingPid, callingUid)) {
2094 ALOGE("%s: pid %d doesn't have camera permissions", __FUNCTION__, callingPid);
2095 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2096 "android.permission.CAMERA needed to call"
2097 "isConcurrentSessionConfigurationSupported");
2098 }
2099
2100 status_t res =
2101 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
2102 cameraIdsAndSessionConfigurations, isSupported);
2103 if (res != OK) {
2104 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
2105 "support %s (%d)", strerror(-res), res);
2106 }
2107 return Status::ok();
2108}
2109
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002110Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
2111 /*out*/
2112 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002113 return addListenerHelper(listener, cameraStatuses);
2114}
2115
2116Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
2117 /*out*/
2118 std::vector<hardware::CameraStatus> *cameraStatuses,
2119 bool isVendorListener) {
2120
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002121 ATRACE_CALL();
2122
Igor Murashkinbfc99152013-02-27 12:55:20 -08002123 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08002124
Ruben Brunk3450ba72015-06-16 11:00:37 -07002125 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002126 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002127 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002128 }
2129
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002130 auto clientUid = CameraThreadState::getCallingUid();
2131 auto clientPid = CameraThreadState::getCallingPid();
Shuzhen Wang695044d2020-03-06 09:02:23 -08002132 bool openCloseCallbackAllowed = checkPermission(sCameraOpenCloseListenerPermission,
2133 clientPid, clientUid);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002134
Igor Murashkinbfc99152013-02-27 12:55:20 -08002135 Mutex::Autolock lock(mServiceLock);
2136
Ruben Brunkcc776712015-02-17 20:18:47 -08002137 {
2138 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08002139 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002140 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002141 ALOGW("%s: Tried to add listener %p which was already subscribed",
2142 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002143 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08002144 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002145 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002146
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002147 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08002148 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
2149 openCloseCallbackAllowed);
Emilian Peev53722fa2019-02-22 17:47:20 -08002150 auto ret = serviceListener->initialize();
2151 if (ret != NO_ERROR) {
2152 String8 msg = String8::format("Failed to initialize service listener: %s (%d)",
2153 strerror(-ret), ret);
2154 ALOGE("%s: %s", __FUNCTION__, msg.string());
2155 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
2156 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002157 // The listener still needs to be added to the list of listeners, regardless of what
2158 // permissions the listener process has / whether it is a vendor listener. Since it might be
2159 // eligible to listen to other camera ids.
2160 mListenerList.emplace_back(serviceListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08002161 mUidPolicy->registerMonitorUid(clientUid);
Igor Murashkinbfc99152013-02-27 12:55:20 -08002162 }
2163
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002164 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07002165 {
Ruben Brunkcc776712015-02-17 20:18:47 -08002166 Mutex::Autolock lock(mCameraStatesLock);
2167 for (auto& i : mCameraStates) {
Shuzhen Wang43858162020-01-10 13:42:15 -08002168 cameraStatuses->emplace_back(i.first,
2169 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds());
Igor Murashkincba2c162013-03-20 15:56:31 -07002170 }
2171 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002172 // Remove the camera statuses that should be hidden from the client, we do
2173 // this after collecting the states in order to avoid holding
2174 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
2175 // the same time.
2176 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
2177 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
2178 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
2179 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
2180 ALOGE("%s: Invalid camera id %s, skipping status update",
2181 __FUNCTION__, s.cameraId.c_str());
2182 return true;
2183 }
2184 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
2185 clientUid);}), cameraStatuses->end());
2186
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002187 //cameraStatuses will have non-eligible camera ids removed.
2188 std::set<String16> idsChosenForCallback;
2189 for (const auto &s : *cameraStatuses) {
2190 idsChosenForCallback.insert(String16(s.cameraId));
2191 }
Igor Murashkincba2c162013-03-20 15:56:31 -07002192
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002193 /*
2194 * Immediately signal current torch status to this listener only
2195 * This may be a subset of all the devices, so don't include it in the response directly
2196 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002197 {
2198 Mutex::Autolock al(mTorchStatusMutex);
2199 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002200 String16 id = String16(mTorchStatusMap.keyAt(i).string());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002201 // The camera id is visible to the client. Fine to send torch
2202 // callback.
2203 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
2204 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
2205 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002206 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002207 }
2208
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002209 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08002210}
Ruben Brunkcc776712015-02-17 20:18:47 -08002211
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002212Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002213 ATRACE_CALL();
2214
Igor Murashkinbfc99152013-02-27 12:55:20 -08002215 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
2216
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002217 if (listener == 0) {
2218 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002219 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002220 }
2221
Igor Murashkinbfc99152013-02-27 12:55:20 -08002222 Mutex::Autolock lock(mServiceLock);
2223
Ruben Brunkcc776712015-02-17 20:18:47 -08002224 {
2225 Mutex::Autolock lock(mStatusListenerLock);
2226 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002227 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
2228 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid());
2229 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08002230 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002231 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002232 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002233 }
2234 }
2235
2236 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
2237 __FUNCTION__, listener.get());
2238
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002239 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08002240}
2241
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002242Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002243
2244 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002245 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
2246
2247 if (parameters == NULL) {
2248 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002249 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07002250 }
2251
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002252 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002253
2254 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002255 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07002256 // Error logged by caller
2257 return ret;
2258 }
2259
2260 String8 shimParamsString8 = shimParams.flatten();
2261 String16 shimParamsString16 = String16(shimParamsString8);
2262
2263 *parameters = shimParamsString16;
2264
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002265 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07002266}
2267
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002268Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
2269 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002270 ATRACE_CALL();
2271
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002272 const String8 id = String8(cameraId);
2273
2274 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002275
2276 switch (apiVersion) {
2277 case API_VERSION_1:
2278 case API_VERSION_2:
2279 break;
2280 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002281 String8 msg = String8::format("Unknown API version %d", apiVersion);
2282 ALOGE("%s: %s", __FUNCTION__, msg.string());
2283 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002284 }
2285
Emilian Peev28ad2ea2017-02-07 16:14:32 +00002286 int deviceVersion = getDeviceVersion(id);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002287 switch (deviceVersion) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002288 case CAMERA_DEVICE_API_VERSION_1_0:
2289 case CAMERA_DEVICE_API_VERSION_3_0:
2290 case CAMERA_DEVICE_API_VERSION_3_1:
2291 if (apiVersion == API_VERSION_2) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002292 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without shim",
2293 __FUNCTION__, id.string(), deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002294 *isSupported = false;
2295 } else { // if (apiVersion == API_VERSION_1) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002296 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always supported",
2297 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002298 *isSupported = true;
2299 }
2300 break;
2301 case CAMERA_DEVICE_API_VERSION_3_2:
2302 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -07002303 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002304 case CAMERA_DEVICE_API_VERSION_3_5:
Yin-Chia Yeh56d98ba2020-01-16 16:57:14 -08002305 case CAMERA_DEVICE_API_VERSION_3_6:
Shuzhen Wang83bff122020-11-20 15:51:39 -08002306 case CAMERA_DEVICE_API_VERSION_3_7:
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002307 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
2308 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002309 *isSupported = true;
2310 break;
2311 case -1: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002312 String8 msg = String8::format("Unknown camera ID %s", id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002313 ALOGE("%s: %s", __FUNCTION__, msg.string());
2314 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002315 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002316 default: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002317 String8 msg = String8::format("Unknown device version %x for device %s",
2318 deviceVersion, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002319 ALOGE("%s: %s", __FUNCTION__, msg.string());
2320 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
2321 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07002322 }
2323
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002324 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002325}
2326
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002327Status CameraService::isHiddenPhysicalCamera(const String16& cameraId,
2328 /*out*/ bool *isSupported) {
2329 ATRACE_CALL();
2330
2331 const String8 id = String8(cameraId);
2332
2333 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
2334 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(id.string());
2335
2336 return Status::ok();
2337}
2338
Ruben Brunkcc776712015-02-17 20:18:47 -08002339void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002340 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002341 for (auto& i : mActiveClientManager.getAll()) {
2342 auto clientSp = i->getValue();
2343 if (clientSp.get() == client) {
2344 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08002345 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07002346 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002347 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08002348}
2349
Ruben Brunkcc776712015-02-17 20:18:47 -08002350bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002351 bool ret = false;
2352 {
2353 // Acquire mServiceLock and prevent other clients from connecting
2354 std::unique_ptr<AutoConditionLock> lock =
2355 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08002356
Igor Murashkin634a5152013-02-20 17:15:11 -08002357
Ruben Brunkcc776712015-02-17 20:18:47 -08002358 std::vector<sp<BasicClient>> evicted;
2359 for (auto& i : mActiveClientManager.getAll()) {
2360 auto clientSp = i->getValue();
2361 if (clientSp.get() == nullptr) {
2362 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2363 mActiveClientManager.remove(i);
2364 continue;
2365 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08002366 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002367 mActiveClientManager.remove(i);
2368 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08002369
Ruben Brunkcc776712015-02-17 20:18:47 -08002370 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002371 clientSp->notifyError(
2372 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002373 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08002374 }
2375 }
2376
Ruben Brunkcc776712015-02-17 20:18:47 -08002377 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2378 // other clients from connecting in mServiceLockWrapper if held
2379 mServiceLock.unlock();
2380
Ruben Brunk36597b22015-03-20 22:15:57 -07002381 // Do not clear caller identity, remote caller should be client proccess
2382
Ruben Brunkcc776712015-02-17 20:18:47 -08002383 for (auto& i : evicted) {
2384 if (i.get() != nullptr) {
2385 i->disconnect();
2386 ret = true;
2387 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002388 }
2389
Ruben Brunkcc776712015-02-17 20:18:47 -08002390 // Reacquire mServiceLock
2391 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08002392
Ruben Brunkcc776712015-02-17 20:18:47 -08002393 } // lock is destroyed, allow further connect calls
2394
2395 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07002396}
2397
Ruben Brunkcc776712015-02-17 20:18:47 -08002398std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
2399 const String8& cameraId) const {
2400 std::shared_ptr<CameraState> state;
2401 {
2402 Mutex::Autolock lock(mCameraStatesLock);
2403 auto iter = mCameraStates.find(cameraId);
2404 if (iter != mCameraStates.end()) {
2405 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002406 }
2407 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002408 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002409}
2410
Ruben Brunkcc776712015-02-17 20:18:47 -08002411sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
2412 // Remove from active clients list
2413 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
2414 if (clientDescriptorPtr == nullptr) {
2415 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
2416 cameraId.string());
2417 return sp<BasicClient>{nullptr};
2418 }
2419
2420 return clientDescriptorPtr->getValue();
Keun young Parkd8973a72012-03-28 14:13:09 -07002421}
2422
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002423void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07002424 // Acquire mServiceLock and prevent other clients from connecting
2425 std::unique_ptr<AutoConditionLock> lock =
2426 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
2427
Ruben Brunk6267b532015-04-30 17:44:07 -07002428 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002429 for (size_t i = 0; i < newUserIds.size(); i++) {
2430 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07002431 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002432 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07002433 return;
2434 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002435 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07002436 }
2437
Ruben Brunka8ca9152015-04-07 14:23:40 -07002438
Ruben Brunk6267b532015-04-30 17:44:07 -07002439 if (newAllowedUsers == mAllowedUsers) {
2440 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
2441 return;
2442 }
2443
2444 logUserSwitch(mAllowedUsers, newAllowedUsers);
2445
2446 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07002447
2448 // Current user has switched, evict all current clients.
2449 std::vector<sp<BasicClient>> evicted;
2450 for (auto& i : mActiveClientManager.getAll()) {
2451 auto clientSp = i->getValue();
2452
2453 if (clientSp.get() == nullptr) {
2454 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2455 continue;
2456 }
2457
Ruben Brunk6267b532015-04-30 17:44:07 -07002458 // Don't evict clients that are still allowed.
2459 uid_t clientUid = clientSp->getClientUid();
2460 userid_t clientUserId = multiuser_get_user_id(clientUid);
2461 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
2462 continue;
2463 }
2464
Ruben Brunk36597b22015-03-20 22:15:57 -07002465 evicted.push_back(clientSp);
2466
2467 String8 curTime = getFormattedCurrentTime();
2468
2469 ALOGE("Evicting conflicting client for camera ID %s due to user change",
2470 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07002471
Ruben Brunk36597b22015-03-20 22:15:57 -07002472 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002473 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00002474 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
2475 " to user switch.", i->getKey().string(),
2476 String8{clientSp->getPackageName()}.string(),
2477 i->getOwnerId(), i->getPriority().getScore(),
2478 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07002479
2480 }
2481
2482 // Do not hold mServiceLock while disconnecting clients, but retain the condition
2483 // blocking other clients from connecting in mServiceLockWrapper if held.
2484 mServiceLock.unlock();
2485
2486 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07002487 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07002488
2489 for (auto& i : evicted) {
2490 i->disconnect();
2491 }
2492
Jayant Chowdhary12361932018-08-27 14:46:13 -07002493 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07002494
2495 // Reacquire mServiceLock
2496 mServiceLock.lock();
2497}
Ruben Brunkcc776712015-02-17 20:18:47 -08002498
Ruben Brunka8ca9152015-04-07 14:23:40 -07002499void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002500 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07002501 Mutex::Autolock l(mLogLock);
2502 mEventLog.add(String8::format("%s : %s", curTime.string(), event));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002503}
2504
Ruben Brunka8ca9152015-04-07 14:23:40 -07002505void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002506 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002507 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002508 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002509 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002510}
2511
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002512void CameraService::logDisconnectedOffline(const char* cameraId, int clientPid,
2513 const char* clientPackage) {
2514 // Log the clients evicted
2515 logEvent(String8::format("DISCONNECT offline device %s client for package %s (PID %d)",
2516 cameraId, clientPackage, clientPid));
2517}
2518
Ruben Brunka8ca9152015-04-07 14:23:40 -07002519void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002520 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002521 // Log the clients evicted
2522 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002523 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002524}
2525
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002526void CameraService::logConnectedOffline(const char* cameraId, int clientPid,
2527 const char* clientPackage) {
2528 // Log the clients evicted
2529 logEvent(String8::format("CONNECT offline device %s client for package %s (PID %d)", cameraId,
2530 clientPackage, clientPid));
2531}
2532
Ruben Brunka8ca9152015-04-07 14:23:40 -07002533void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002534 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002535 // Log the client rejected
2536 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002537 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002538}
2539
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002540void CameraService::logTorchEvent(const char* cameraId, const char *torchState, int clientPid) {
2541 // Log torch event
2542 logEvent(String8::format("Torch for camera id %s turned %s for client PID %d", cameraId,
2543 torchState, clientPid));
2544}
2545
Ruben Brunk6267b532015-04-30 17:44:07 -07002546void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
2547 const std::set<userid_t>& newUserIds) {
2548 String8 newUsers = toString(newUserIds);
2549 String8 oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002550 if (oldUsers.size() == 0) {
2551 oldUsers = "<None>";
2552 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07002553 // Log the new and old users
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002554 logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
Ruben Brunk6267b532015-04-30 17:44:07 -07002555 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002556}
2557
2558void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
2559 // Log the device removal
2560 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
2561}
2562
2563void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
2564 // Log the device removal
2565 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
2566}
2567
2568void CameraService::logClientDied(int clientPid, const char* reason) {
2569 // Log the device removal
2570 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07002571}
2572
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002573void CameraService::logServiceError(const char* msg, int errorCode) {
2574 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002575 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002576}
2577
Ruben Brunk36597b22015-03-20 22:15:57 -07002578status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
2579 uint32_t flags) {
2580
Mathias Agopian65ab4712010-07-14 17:59:35 -07002581 // Permission checks
2582 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002583 case SHELL_COMMAND_TRANSACTION: {
2584 int in = data.readFileDescriptor();
2585 int out = data.readFileDescriptor();
2586 int err = data.readFileDescriptor();
2587 int argc = data.readInt32();
2588 Vector<String16> args;
2589 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
2590 args.add(data.readString16());
2591 }
2592 sp<IBinder> unusedCallback;
2593 sp<IResultReceiver> resultReceiver;
2594 status_t status;
2595 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
2596 return status;
2597 }
2598 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
2599 return status;
2600 }
2601 status = shellCommand(in, out, err, args);
2602 if (resultReceiver != nullptr) {
2603 resultReceiver->send(status);
2604 }
2605 return NO_ERROR;
2606 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002607 }
2608
2609 return BnCameraService::onTransact(code, data, reply, flags);
2610}
2611
Mathias Agopian65ab4712010-07-14 17:59:35 -07002612// We share the media players for shutter and recording sound for all clients.
2613// A reference count is kept to determine when we will actually release the
2614// media players.
2615
Jaekyun Seokef498052018-03-23 13:09:44 +09002616sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
2617 sp<MediaPlayer> mp = new MediaPlayer();
2618 status_t error;
2619 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08002620 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09002621 error = mp->prepare();
2622 }
2623 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00002624 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09002625 mp->disconnect();
2626 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002627 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002628 }
2629 return mp;
2630}
2631
username5755fea2018-12-27 09:48:08 +08002632void CameraService::increaseSoundRef() {
2633 Mutex::Autolock lock(mSoundLock);
2634 mSoundRef++;
2635}
2636
2637void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002638 ATRACE_CALL();
2639
username5755fea2018-12-27 09:48:08 +08002640 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
2641 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
2642 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
2643 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
2644 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
2645 }
2646 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
2647 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
2648 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
2649 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002650 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08002651 }
2652 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
2653 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
2654 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
2655 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
2656 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002657 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002658}
2659
username5755fea2018-12-27 09:48:08 +08002660void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002661 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002662 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002663 if (--mSoundRef) return;
2664
2665 for (int i = 0; i < NUM_SOUNDS; i++) {
2666 if (mSoundPlayer[i] != 0) {
2667 mSoundPlayer[i]->disconnect();
2668 mSoundPlayer[i].clear();
2669 }
2670 }
2671}
2672
2673void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002674 ATRACE_CALL();
2675
Mathias Agopian65ab4712010-07-14 17:59:35 -07002676 LOG1("playSound(%d)", kind);
2677 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002678 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002679 sp<MediaPlayer> player = mSoundPlayer[kind];
2680 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08002681 player->seekTo(0);
2682 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002683 }
2684}
2685
2686// ----------------------------------------------------------------------------
2687
2688CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07002689 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002690 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09002691 const std::optional<String16>& clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002692 const String8& cameraIdStr,
2693 int api1CameraId, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002694 int clientPid, uid_t clientUid,
2695 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002696 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08002697 IInterface::asBinder(cameraClient),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002698 clientPackageName, clientFeatureId,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002699 cameraIdStr, cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002700 clientPid, clientUid,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002701 servicePid),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002702 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08002703{
Jayant Chowdhary12361932018-08-27 14:46:13 -07002704 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002705 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002706
Igor Murashkin44cfcf02013-03-01 16:22:28 -08002707 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002708
username5755fea2018-12-27 09:48:08 +08002709 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002710
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002711 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002712}
2713
Mathias Agopian65ab4712010-07-14 17:59:35 -07002714// tear down the client
2715CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002716 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08002717 mDestructionStarted = true;
2718
username5755fea2018-12-27 09:48:08 +08002719 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002720 // unconditionally disconnect. function is idempotent
2721 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002722}
2723
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002724sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
2725
Igor Murashkin634a5152013-02-20 17:15:11 -08002726CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002727 const sp<IBinder>& remoteCallback,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09002728 const String16& clientPackageName, const std::optional<String16>& clientFeatureId,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002729 const String8& cameraIdStr, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002730 int clientPid, uid_t clientUid,
2731 int servicePid):
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002732 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing),
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09002733 mClientPackageName(clientPackageName), mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002734 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002735 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07002736 mDisconnected(false), mUidIsTrusted(false),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002737 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002738 mRemoteBinder(remoteCallback)
Igor Murashkin634a5152013-02-20 17:15:11 -08002739{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002740 if (sCameraService == nullptr) {
2741 sCameraService = cameraService;
2742 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002743 mOpsActive = false;
Igor Murashkin634a5152013-02-20 17:15:11 -08002744 mDestructionStarted = false;
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08002745
2746 // In some cases the calling code has no access to the package it runs under.
2747 // For example, NDK camera API.
2748 // In this case we will get the packages for the calling UID and pick the first one
2749 // for attributing the app op. This will work correctly for runtime permissions
2750 // as for legacy apps we will toggle the app op for all packages in the UID.
2751 // The caveat is that the operation may be attributed to the wrong package and
2752 // stats based on app ops may be slightly off.
2753 if (mClientPackageName.size() <= 0) {
2754 sp<IServiceManager> sm = defaultServiceManager();
2755 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
2756 if (binder == 0) {
2757 ALOGE("Cannot get permission service");
2758 // Leave mClientPackageName unchanged (empty) and the further interaction
2759 // with camera will fail in BasicClient::startCameraOps
2760 return;
2761 }
2762
2763 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
2764 Vector<String16> packages;
2765
2766 permCtrl->getPackagesForUid(mClientUid, packages);
2767
2768 if (packages.isEmpty()) {
2769 ALOGE("No packages for calling UID");
2770 // Leave mClientPackageName unchanged (empty) and the further interaction
2771 // with camera will fail in BasicClient::startCameraOps
2772 return;
2773 }
2774 mClientPackageName = packages[0];
2775 }
Steven Moreland89a2c5c2020-01-31 15:02:25 -08002776 if (getCurrentServingCall() != BinderCallType::HWBINDER) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002777 mAppOpsManager = std::make_unique<AppOpsManager>();
2778 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07002779
2780 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08002781}
2782
2783CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002784 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08002785 mDestructionStarted = true;
2786}
2787
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002788binder::Status CameraService::BasicClient::disconnect() {
2789 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002790 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002791 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07002792 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07002793 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002794
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002795 sCameraService->removeByClient(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002796 sCameraService->logDisconnected(mCameraIdStr, mClientPid, String8(mClientPackageName));
Peter Kalauskasa29c1352018-10-10 12:05:42 -07002797 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
2798 mCameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002799
2800 sp<IBinder> remote = getRemote();
2801 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002802 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08002803 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002804
2805 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07002806 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002807 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
2808 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
2809 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002810
Igor Murashkincba2c162013-03-20 15:56:31 -07002811 // client shouldn't be able to call into us anymore
2812 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002813
2814 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08002815}
2816
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002817status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
2818 // No dumping of clients directly over Binder,
2819 // must go through CameraService::dump
2820 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07002821 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002822 return OK;
2823}
2824
Ruben Brunkcc776712015-02-17 20:18:47 -08002825String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002826 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08002827}
2828
2829
2830int CameraService::BasicClient::getClientPid() const {
2831 return mClientPid;
2832}
2833
Ruben Brunk6267b532015-04-30 17:44:07 -07002834uid_t CameraService::BasicClient::getClientUid() const {
2835 return mClientUid;
2836}
2837
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002838bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
2839 // Defaults to API2.
2840 return level == API_2;
2841}
2842
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002843status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002844 {
2845 Mutex::Autolock l(mAudioRestrictionLock);
2846 mAudioRestriction = mode;
2847 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002848 sCameraService->updateAudioRestriction();
2849 return OK;
2850}
2851
2852int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002853 return sCameraService->updateAudioRestriction();
2854}
2855
2856int32_t CameraService::BasicClient::getAudioRestriction() const {
2857 Mutex::Autolock l(mAudioRestrictionLock);
2858 return mAudioRestriction;
2859}
2860
2861bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
2862 switch (mode) {
2863 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
2864 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
2865 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
2866 return true;
2867 default:
2868 return false;
2869 }
2870}
2871
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002872status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002873 ATRACE_CALL();
2874
Igor Murashkine6800ce2013-03-04 17:25:57 -08002875 {
2876 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002877 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08002878 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002879 if (mAppOpsManager != nullptr) {
2880 // Notify app ops that the camera is not available
2881 mOpsCallback = new OpsCallback(this);
2882 int32_t res;
2883 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
2884 mClientPackageName, mOpsCallback);
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002885 res = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
2886 mClientPackageName, /*startIfModeDefault*/ false, mClientFeatureId,
2887 String16("start camera ") + String16(mCameraIdStr));
Igor Murashkine6800ce2013-03-04 17:25:57 -08002888
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002889 if (res == AppOpsManager::MODE_ERRORED) {
2890 ALOGI("Camera %s: Access for \"%s\" has been revoked",
2891 mCameraIdStr.string(), String8(mClientPackageName).string());
2892 return PERMISSION_DENIED;
2893 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002894
Shuzhen Wang2c656792020-04-13 17:36:49 -07002895 // If the calling Uid is trusted (a native service), the AppOpsManager could
2896 // return MODE_IGNORED. Do not treat such case as error.
2897 if (!mUidIsTrusted && res == AppOpsManager::MODE_IGNORED) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002898 ALOGI("Camera %s: Access for \"%s\" has been restricted",
2899 mCameraIdStr.string(), String8(mClientPackageName).string());
2900 // Return the same error as for device policy manager rejection
2901 return -EACCES;
2902 }
Svetoslav28e8ef72015-05-11 19:21:31 -07002903 }
2904
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002905 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002906
2907 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002908 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002909
Emilian Peev53722fa2019-02-22 17:47:20 -08002910 sCameraService->mUidPolicy->registerMonitorUid(mClientUid);
2911
Shuzhen Wang695044d2020-03-06 09:02:23 -08002912 // Notify listeners of camera open/close status
2913 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
2914
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002915 return OK;
2916}
2917
2918status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002919 ATRACE_CALL();
2920
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002921 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002922 if (mOpsActive) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002923 // Notify app ops that the camera is available again
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002924 if (mAppOpsManager != nullptr) {
2925 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002926 mClientPackageName, mClientFeatureId);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002927 mOpsActive = false;
2928 }
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002929 // This function is called when a client disconnects. This should
2930 // release the camera, but actually only if it was in a proper
2931 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002932 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002933 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002934
Ruben Brunkcc776712015-02-17 20:18:47 -08002935 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002936 sCameraService->updateStatus(StatusInternal::PRESENT,
2937 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002938 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002939 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002940 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
2941 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002942 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002943 mOpsCallback.clear();
2944
Emilian Peev53722fa2019-02-22 17:47:20 -08002945 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid);
2946
Shuzhen Wang695044d2020-03-06 09:02:23 -08002947 // Notify listeners of camera open/close status
2948 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
2949
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002950 return OK;
2951}
2952
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002953void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002954 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002955 if (mAppOpsManager == nullptr) {
2956 return;
2957 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002958 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002959 if (op != AppOpsManager::OP_CAMERA) {
2960 ALOGW("Unexpected app ops notification received: %d", op);
2961 return;
2962 }
2963
2964 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002965 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002966 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002967 ALOGV("checkOp returns: %d, %s ", res,
2968 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
2969 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
2970 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
2971 "UNKNOWN");
2972
Shuzhen Wang64900852021-02-05 09:03:29 -08002973 if (res == AppOpsManager::MODE_ERRORED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002974 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002975 String8(mClientPackageName).string());
Svet Ganova453d0d2018-01-11 15:37:58 -08002976 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08002977 } else if (res == AppOpsManager::MODE_IGNORED) {
2978 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
2979 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d",
2980 mCameraIdStr.string(), String8(mClientPackageName).string(),
2981 mUidIsTrusted, isUidActive);
2982 // If the calling Uid is trusted (a native service), or the client Uid is active (WAR for
2983 // b/175320666), the AppOpsManager could return MODE_IGNORED. Do not treat such cases as
2984 // error.
2985 if (!mUidIsTrusted && !isUidActive) {
2986 block();
2987 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002988 }
2989}
2990
Svet Ganova453d0d2018-01-11 15:37:58 -08002991void CameraService::BasicClient::block() {
2992 ATRACE_CALL();
2993
2994 // Reset the client PID to allow server-initiated disconnect,
2995 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07002996 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08002997 CaptureResultExtras resultExtras; // a dummy result (invalid)
2998 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
2999 disconnect();
3000}
3001
Mathias Agopian65ab4712010-07-14 17:59:35 -07003002// ----------------------------------------------------------------------------
3003
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003004void CameraService::Client::notifyError(int32_t errorCode,
Jianing Weicb0652e2014-03-12 18:29:36 -07003005 const CaptureResultExtras& resultExtras) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08003006 (void) resultExtras;
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003007 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07003008 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
3009 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
3010 api1ErrorCode = CAMERA_ERROR_DISABLED;
3011 }
3012 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003013 } else {
3014 ALOGE("mRemoteCallback is NULL!!");
3015 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003016}
3017
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003018// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003019binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003020 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003021 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08003022}
3023
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003024bool CameraService::Client::canCastToApiClient(apiLevel level) const {
3025 return level == API_1;
3026}
3027
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003028CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
3029 mClient(client) {
3030}
3031
3032void CameraService::Client::OpsCallback::opChanged(int32_t op,
3033 const String16& packageName) {
3034 sp<BasicClient> client = mClient.promote();
3035 if (client != NULL) {
3036 client->opChanged(op, packageName);
3037 }
3038}
3039
Mathias Agopian65ab4712010-07-14 17:59:35 -07003040// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08003041// UidPolicy
3042// ----------------------------------------------------------------------------
3043
3044void CameraService::UidPolicy::registerSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003045 Mutex::Autolock _l(mUidLock);
3046
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003047 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07003048 status_t res = mAm.linkToDeath(this);
3049 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08003050 | ActivityManager::UID_OBSERVER_IDLE
Emilian Peev53722fa2019-02-22 17:47:20 -08003051 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganova453d0d2018-01-11 15:37:58 -08003052 ActivityManager::PROCESS_STATE_UNKNOWN,
3053 String16("cameraserver"));
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003054 if (res == OK) {
3055 mRegistered = true;
3056 ALOGV("UidPolicy: Registered with ActivityManager");
3057 }
Svet Ganova453d0d2018-01-11 15:37:58 -08003058}
3059
3060void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003061 Mutex::Autolock _l(mUidLock);
3062
Steven Moreland2f348142019-07-02 15:59:07 -07003063 mAm.unregisterUidObserver(this);
3064 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003065 mRegistered = false;
3066 mActiveUids.clear();
3067 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08003068}
3069
3070void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
3071 onUidIdle(uid, disabled);
3072}
3073
3074void CameraService::UidPolicy::onUidActive(uid_t uid) {
3075 Mutex::Autolock _l(mUidLock);
3076 mActiveUids.insert(uid);
3077}
3078
3079void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
3080 bool deleted = false;
3081 {
3082 Mutex::Autolock _l(mUidLock);
3083 if (mActiveUids.erase(uid) > 0) {
3084 deleted = true;
3085 }
3086 }
3087 if (deleted) {
3088 sp<CameraService> service = mService.promote();
3089 if (service != nullptr) {
3090 service->blockClientsForUid(uid);
3091 }
3092 }
3093}
3094
Emilian Peev53722fa2019-02-22 17:47:20 -08003095void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07003096 int64_t procStateSeq __unused, int32_t capability __unused) {
Emilian Peev53722fa2019-02-22 17:47:20 -08003097 bool procStateChange = false;
3098 {
3099 Mutex::Autolock _l(mUidLock);
3100 if ((mMonitoredUids.find(uid) != mMonitoredUids.end()) &&
3101 (mMonitoredUids[uid].first != procState)) {
3102 mMonitoredUids[uid].first = procState;
3103 procStateChange = true;
3104 }
3105 }
3106
3107 if (procStateChange) {
3108 sp<CameraService> service = mService.promote();
3109 if (service != nullptr) {
3110 service->notifyMonitoredUids();
3111 }
3112 }
3113}
3114
3115void CameraService::UidPolicy::registerMonitorUid(uid_t uid) {
3116 Mutex::Autolock _l(mUidLock);
3117 auto it = mMonitoredUids.find(uid);
3118 if (it != mMonitoredUids.end()) {
3119 it->second.second++;
3120 } else {
3121 mMonitoredUids.emplace(
3122 std::pair<uid_t, std::pair<int32_t, size_t>> (uid,
3123 std::pair<int32_t, size_t> (ActivityManager::PROCESS_STATE_NONEXISTENT, 1)));
3124 }
3125}
3126
3127void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid) {
3128 Mutex::Autolock _l(mUidLock);
3129 auto it = mMonitoredUids.find(uid);
3130 if (it != mMonitoredUids.end()) {
3131 it->second.second--;
3132 if (it->second.second == 0) {
3133 mMonitoredUids.erase(it);
3134 }
3135 } else {
3136 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
3137 }
3138}
3139
Svet Ganov7b4ab782018-03-25 12:48:10 -07003140bool CameraService::UidPolicy::isUidActive(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003141 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003142 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003143}
3144
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003145static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
3146static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003147
Svet Ganov7b4ab782018-03-25 12:48:10 -07003148bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003149 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003150 // If activity manager is unreachable, assume everything is active
3151 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003152 return true;
3153 }
3154 auto it = mOverrideUids.find(uid);
3155 if (it != mOverrideUids.end()) {
3156 return it->second;
3157 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003158 bool active = mActiveUids.find(uid) != mActiveUids.end();
3159 if (!active) {
3160 // We want active UIDs to always access camera with their first attempt since
3161 // there is no guarantee the app is robustly written and would retry getting
3162 // the camera on failure. The inverse case is not a problem as we would take
3163 // camera away soon once we get the callback that the uid is no longer active.
3164 ActivityManager am;
3165 // Okay to access with a lock held as UID changes are dispatched without
3166 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07003167 int64_t startTimeMillis = 0;
3168 do {
3169 // TODO: Fix this b/109950150!
3170 // Okay this is a hack. There is a race between the UID turning active and
3171 // activity being resumed. The proper fix is very risky, so we temporary add
3172 // some polling which should happen pretty rarely anyway as the race is hard
3173 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003174 active = mActiveUids.find(uid) != mActiveUids.end();
Hui Yu12c7ec72020-05-04 17:40:52 +00003175 if (!active) active = am.isUidActive(uid, callingPackage);
Svet Ganov94ec46f2018-06-08 15:03:46 -07003176 if (active) {
3177 break;
3178 }
3179 if (startTimeMillis <= 0) {
3180 startTimeMillis = uptimeMillis();
3181 }
3182 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003183 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003184 if (remainingTimeMillis <= 0) {
3185 break;
3186 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003187 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
3188
3189 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003190 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003191 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003192 } while (true);
3193
Svet Ganov7b4ab782018-03-25 12:48:10 -07003194 if (active) {
3195 // Now that we found out the UID is actually active, cache that
3196 mActiveUids.insert(uid);
3197 }
3198 }
3199 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08003200}
3201
Varun Shahb42f1eb2019-04-16 14:45:13 -07003202int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
3203 Mutex::Autolock _l(mUidLock);
3204 return getProcStateLocked(uid);
3205}
3206
3207int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
3208 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
3209 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
3210 procState = mMonitoredUids[uid].first;
3211 }
3212 return procState;
3213}
3214
Svet Ganov7b4ab782018-03-25 12:48:10 -07003215void CameraService::UidPolicy::UidPolicy::addOverrideUid(uid_t uid,
3216 String16 callingPackage, bool active) {
3217 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08003218}
3219
Svet Ganov7b4ab782018-03-25 12:48:10 -07003220void CameraService::UidPolicy::removeOverrideUid(uid_t uid, String16 callingPackage) {
3221 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08003222}
3223
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003224void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
3225 Mutex::Autolock _l(mUidLock);
3226 ALOGV("UidPolicy: ActivityManager has died");
3227 mRegistered = false;
3228 mActiveUids.clear();
3229}
3230
Svet Ganov7b4ab782018-03-25 12:48:10 -07003231void CameraService::UidPolicy::updateOverrideUid(uid_t uid, String16 callingPackage,
3232 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003233 bool wasActive = false;
3234 bool isActive = false;
3235 {
3236 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003237 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003238 mOverrideUids.erase(uid);
3239 if (insert) {
3240 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
3241 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003242 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003243 }
3244 if (wasActive != isActive && !isActive) {
3245 sp<CameraService> service = mService.promote();
3246 if (service != nullptr) {
3247 service->blockClientsForUid(uid);
3248 }
3249 }
3250}
3251
3252// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08003253// SensorPrivacyPolicy
3254// ----------------------------------------------------------------------------
3255void CameraService::SensorPrivacyPolicy::registerSelf() {
3256 Mutex::Autolock _l(mSensorPrivacyLock);
3257 if (mRegistered) {
3258 return;
3259 }
Steven Moreland3cf67172020-01-29 11:44:22 -08003260 mSpm.addSensorPrivacyListener(this);
3261 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
3262 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003263 if (res == OK) {
3264 mRegistered = true;
3265 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
3266 }
3267}
3268
Evan Severson190ad252021-01-07 20:37:15 -08003269status_t CameraService::SensorPrivacyPolicy::registerSelfForIndividual(int userId) {
3270 Mutex::Autolock _l(mSensorPrivacyLock);
3271 if (mRegistered) {
3272 return OK;
3273 }
3274
3275 status_t res = mSpm.addIndividualSensorPrivacyListener(userId,
3276 SensorPrivacyManager::INDIVIDUAL_SENSOR_CAMERA, this);
3277 if (res != OK) {
3278 ALOGE("Unable to register camera privacy listener: %s (%d)", strerror(-res), res);
3279 return res;
3280 }
3281
3282 res = mSpm.isIndividualSensorPrivacyEnabled(userId,
3283 SensorPrivacyManager::INDIVIDUAL_SENSOR_CAMERA, mSensorPrivacyEnabled);
3284 if (res != OK) {
3285 ALOGE("Unable to check camera privacy: %s (%d)", strerror(-res), res);
3286 return res;
3287 }
3288
3289 res = mSpm.linkToDeath(this);
3290 if (res != OK) {
3291 ALOGE("Register link to death failed for sensor privacy: %s (%d)", strerror(-res), res);
3292 return res;
3293 }
3294
3295 mRegistered = true;
Evan Seversondd51a012021-02-03 09:15:21 -08003296 mIsIndividual = true;
3297 mUserId = userId;
Evan Severson190ad252021-01-07 20:37:15 -08003298 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
3299 return OK;
3300}
3301
Michael Grooverd1d435a2018-12-18 17:39:42 -08003302void CameraService::SensorPrivacyPolicy::unregisterSelf() {
3303 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08003304 mSpm.removeSensorPrivacyListener(this);
3305 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003306 mRegistered = false;
3307 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
3308}
3309
3310bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
3311 Mutex::Autolock _l(mSensorPrivacyLock);
3312 return mSensorPrivacyEnabled;
3313}
3314
3315binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
3316 {
3317 Mutex::Autolock _l(mSensorPrivacyLock);
3318 mSensorPrivacyEnabled = enabled;
3319 }
3320 // if sensor privacy is enabled then block all clients from accessing the camera
Evan Severson190ad252021-01-07 20:37:15 -08003321 sp<CameraService> service = mService.promote();
3322 if (service != nullptr) {
Evan Seversondd51a012021-02-03 09:15:21 -08003323 if (mIsIndividual) {
3324 service->setMuteForAllClients(mUserId, enabled);
Evan Severson190ad252021-01-07 20:37:15 -08003325 } else {
3326 if (enabled) {
3327 service->blockAllClients();
3328 }
Michael Grooverd1d435a2018-12-18 17:39:42 -08003329 }
3330 }
3331 return binder::Status::ok();
3332}
3333
3334void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
3335 Mutex::Autolock _l(mSensorPrivacyLock);
3336 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
3337 mRegistered = false;
3338}
3339
3340// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003341// CameraState
3342// ----------------------------------------------------------------------------
3343
3344CameraService::CameraState::CameraState(const String8& id, int cost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003345 const std::set<String8>& conflicting, SystemCameraKind systemCameraKind) : mId(id),
3346 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
3347 mSystemCameraKind(systemCameraKind) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08003348
3349CameraService::CameraState::~CameraState() {}
3350
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003351CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003352 Mutex::Autolock lock(mStatusLock);
3353 return mStatus;
3354}
3355
Shuzhen Wang43858162020-01-10 13:42:15 -08003356std::vector<String8> CameraService::CameraState::getUnavailablePhysicalIds() const {
3357 Mutex::Autolock lock(mStatusLock);
3358 std::vector<String8> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
3359 return res;
3360}
3361
Ruben Brunkcc776712015-02-17 20:18:47 -08003362CameraParameters CameraService::CameraState::getShimParams() const {
3363 return mShimParams;
3364}
3365
3366void CameraService::CameraState::setShimParams(const CameraParameters& params) {
3367 mShimParams = params;
3368}
3369
3370int CameraService::CameraState::getCost() const {
3371 return mCost;
3372}
3373
3374std::set<String8> CameraService::CameraState::getConflicting() const {
3375 return mConflicting;
3376}
3377
3378String8 CameraService::CameraState::getId() const {
3379 return mId;
3380}
3381
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003382SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
3383 return mSystemCameraKind;
3384}
3385
Shuzhen Wang43858162020-01-10 13:42:15 -08003386bool CameraService::CameraState::addUnavailablePhysicalId(const String8& physicalId) {
3387 Mutex::Autolock lock(mStatusLock);
3388 auto result = mUnavailablePhysicalIds.insert(physicalId);
3389 return result.second;
3390}
3391
3392bool CameraService::CameraState::removeUnavailablePhysicalId(const String8& physicalId) {
3393 Mutex::Autolock lock(mStatusLock);
3394 auto count = mUnavailablePhysicalIds.erase(physicalId);
3395 return count > 0;
3396}
3397
Ruben Brunkcc776712015-02-17 20:18:47 -08003398// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07003399// ClientEventListener
3400// ----------------------------------------------------------------------------
3401
3402void CameraService::ClientEventListener::onClientAdded(
3403 const resource_policy::ClientDescriptor<String8,
3404 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003405 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003406 if (basicClient.get() != nullptr) {
3407 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3408 notifier.noteStartCamera(descriptor.getKey(),
3409 static_cast<int>(basicClient->getClientUid()));
3410 }
3411}
3412
3413void CameraService::ClientEventListener::onClientRemoved(
3414 const resource_policy::ClientDescriptor<String8,
3415 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003416 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003417 if (basicClient.get() != nullptr) {
3418 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3419 notifier.noteStopCamera(descriptor.getKey(),
3420 static_cast<int>(basicClient->getClientUid()));
3421 }
3422}
3423
3424
3425// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003426// CameraClientManager
3427// ----------------------------------------------------------------------------
3428
Ruben Brunk99e69712015-05-26 17:25:07 -07003429CameraService::CameraClientManager::CameraClientManager() {
3430 setListener(std::make_shared<ClientEventListener>());
3431}
3432
Ruben Brunkcc776712015-02-17 20:18:47 -08003433CameraService::CameraClientManager::~CameraClientManager() {}
3434
3435sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
3436 const String8& id) const {
3437 auto descriptor = get(id);
3438 if (descriptor == nullptr) {
3439 return sp<BasicClient>{nullptr};
3440 }
3441 return descriptor->getValue();
3442}
3443
3444String8 CameraService::CameraClientManager::toString() const {
3445 auto all = getAll();
3446 String8 ret("[");
3447 bool hasAny = false;
3448 for (auto& i : all) {
3449 hasAny = true;
3450 String8 key = i->getKey();
3451 int32_t cost = i->getCost();
3452 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00003453 int32_t score = i->getPriority().getScore();
3454 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08003455 auto conflicting = i->getConflicting();
3456 auto clientSp = i->getValue();
3457 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07003458 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08003459 if (clientSp.get() != nullptr) {
3460 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07003461 uid_t clientUid = clientSp->getClientUid();
3462 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003463 }
Emilian Peev8131a262017-02-01 12:33:43 +00003464 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
3465 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08003466
Ruben Brunk6267b532015-04-30 17:44:07 -07003467 if (clientSp.get() != nullptr) {
3468 ret.appendFormat("User Id: %d, ", clientUserId);
3469 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003470 if (packageName.size() != 0) {
3471 ret.appendFormat("Client Package Name: %s", packageName.string());
3472 }
3473
3474 ret.append(", Conflicting Client Devices: {");
3475 for (auto& j : conflicting) {
3476 ret.appendFormat("%s, ", j.string());
3477 }
3478 ret.append("})");
3479 }
3480 if (hasAny) ret.append("\n");
3481 ret.append("]\n");
3482 return ret;
3483}
3484
3485CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3486 const String8& key, const sp<BasicClient>& value, int32_t cost,
Emilian Peev8131a262017-02-01 12:33:43 +00003487 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
3488 int32_t state) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003489
Steven Moreland89a2c5c2020-01-31 15:02:25 -08003490 bool isVendorClient = getCurrentServingCall() == BinderCallType::HWBINDER;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003491 int32_t score_adj = isVendorClient ? kVendorClientScore : score;
3492 int32_t state_adj = isVendorClient ? kVendorClientState: state;
3493
Ruben Brunkcc776712015-02-17 20:18:47 -08003494 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003495 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj, isVendorClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08003496}
3497
3498CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3499 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
3500 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00003501 partial->getConflicting(), partial->getPriority().getScore(),
3502 partial->getOwnerId(), partial->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08003503}
3504
3505// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07003506
3507static const int kDumpLockRetries = 50;
3508static const int kDumpLockSleep = 60000;
3509
3510static bool tryLock(Mutex& mutex)
3511{
3512 bool locked = false;
3513 for (int i = 0; i < kDumpLockRetries; ++i) {
3514 if (mutex.tryLock() == NO_ERROR) {
3515 locked = true;
3516 break;
3517 }
3518 usleep(kDumpLockSleep);
3519 }
3520 return locked;
3521}
3522
3523status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003524 ATRACE_CALL();
3525
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003526 if (checkCallingPermission(sDumpPermission) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003527 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07003528 CameraThreadState::getCallingPid(),
3529 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003530 return NO_ERROR;
3531 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003532 bool locked = tryLock(mServiceLock);
3533 // failed to lock - CameraService is probably deadlocked
3534 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003535 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003536 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003537
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003538 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003539 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07003540
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003541 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003542 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08003543
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003544 if (locked) mServiceLock.unlock();
3545 return NO_ERROR;
3546 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003547 dprintf(fd, "\n== Service global info: ==\n\n");
3548 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003549 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07003550 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
3551 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003552 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
3553 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
3554 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003555 String8 activeClientString = mActiveClientManager.toString();
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003556 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
3557 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003558
3559 dumpEventLog(fd);
3560
3561 bool stateLocked = tryLock(mCameraStatesLock);
3562 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003563 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003564 }
3565
Emilian Peevbd8c5032018-02-14 23:05:40 +00003566 int argSize = args.size();
3567 for (int i = 0; i < argSize; i++) {
3568 if (args[i] == TagMonitor::kMonitorOption) {
3569 if (i + 1 < argSize) {
3570 mMonitorTags = String8(args[i + 1]);
3571 }
3572 break;
3573 }
3574 }
3575
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003576 for (auto& state : mCameraStates) {
3577 String8 cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003578
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003579 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003580
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003581 CameraParameters p = state.second->getShimParams();
3582 if (!p.isEmpty()) {
3583 dprintf(fd, " Camera1 API shim is using parameters:\n ");
3584 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003585 }
3586
3587 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08003588 if (clientDescriptor != nullptr) {
3589 dprintf(fd, " Device %s is open. Client instance dump:\n",
3590 cameraId.string());
3591 dprintf(fd, " Client priority score: %d state: %d\n",
3592 clientDescriptor->getPriority().getScore(),
3593 clientDescriptor->getPriority().getState());
3594 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
3595
3596 auto client = clientDescriptor->getValue();
3597 dprintf(fd, " Client package: %s\n",
3598 String8(client->getPackageName()).string());
3599
3600 client->dumpClient(fd, args);
3601 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003602 dprintf(fd, " Device %s is closed, no client instance\n",
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003603 cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003604 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003605
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003606 }
3607
3608 if (stateLocked) mCameraStatesLock.unlock();
3609
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003610 if (locked) mServiceLock.unlock();
3611
Emilian Peevf53f66e2017-04-11 14:29:43 +01003612 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003613
3614 dprintf(fd, "\n== Vendor tags: ==\n\n");
3615
3616 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
3617 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00003618 sp<VendorTagDescriptorCache> cache =
3619 VendorTagDescriptorCache::getGlobalVendorTagCache();
3620 if (cache == NULL) {
3621 dprintf(fd, "No vendor tags.\n");
3622 } else {
3623 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
3624 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003625 } else {
3626 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
3627 }
3628
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003629 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003630 dprintf(fd, "\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003631 camera3::CameraTraces::dump(fd, args);
3632
3633 // Process dump arguments, if any
3634 int n = args.size();
3635 String16 verboseOption("-v");
3636 String16 unreachableOption("--unreachable");
3637 for (int i = 0; i < n; i++) {
3638 if (args[i] == verboseOption) {
3639 // change logging level
3640 if (i + 1 >= n) continue;
3641 String8 levelStr(args[i+1]);
3642 int level = atoi(levelStr.string());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003643 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003644 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003645 } else if (args[i] == unreachableOption) {
3646 // Dump memory analysis
3647 // TODO - should limit be an argument parameter?
3648 UnreachableMemoryInfo info;
3649 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
3650 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003651 dprintf(fd, "\n== Unable to dump unreachable memory. "
3652 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003653 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003654 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003655 std::string s = info.ToString(/*log_contents*/ true);
3656 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003657 }
3658 }
3659 }
3660 return NO_ERROR;
3661}
3662
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003663void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003664 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003665
3666 Mutex::Autolock l(mLogLock);
3667 for (const auto& msg : mEventLog) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003668 dprintf(fd, " %s\n", msg.string());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003669 }
3670
3671 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003672 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003673 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003674 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003675 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003676 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003677}
3678
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003679void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003680 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003681 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
3682 if (mTorchClientMap[i] == who) {
3683 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003684 String8 cameraId = mTorchClientMap.keyAt(i);
3685 status_t res = mFlashlight->setTorchMode(cameraId, false);
3686 if (res) {
3687 ALOGE("%s: torch client died but couldn't turn off torch: "
3688 "%s (%d)", __FUNCTION__, strerror(-res), res);
3689 return;
3690 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003691 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003692 break;
3693 }
3694 }
3695}
3696
Ruben Brunkcc776712015-02-17 20:18:47 -08003697/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003698
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003699 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07003700 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
3701 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003702 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003703 // PID here is approximate and can be wrong.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003704 logClientDied(CameraThreadState::getCallingPid(), String8("Binder died unexpectedly"));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003705
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003706 // check torch client
3707 handleTorchClientBinderDied(who);
3708
3709 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08003710 if(!evictClientIdByRemote(who)) {
3711 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003712 return;
3713 }
3714
Ruben Brunkcc776712015-02-17 20:18:47 -08003715 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
3716 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003717}
3718
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003719void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003720 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08003721}
3722
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003723void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
3724 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003725 // Do not lock mServiceLock here or can get into a deadlock from
3726 // connect() -> disconnect -> updateStatus
3727
3728 auto state = getCameraState(cameraId);
3729
3730 if (state == nullptr) {
3731 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
3732 cameraId.string());
3733 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07003734 }
3735
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003736 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
3737 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3738 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3739 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
3740 return;
3741 }
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003742 bool supportsHAL3 = false;
3743 // supportsCameraApi also holds mInterfaceMutex, we can't call it in the
3744 // HIDL onStatusChanged wrapper call (we'll hold mStatusListenerLock and
3745 // mInterfaceMutex together, which can lead to deadlocks)
3746 binder::Status sRet =
3747 supportsCameraApi(String16(cameraId), hardware::ICameraService::API_VERSION_2,
3748 &supportsHAL3);
3749 if (!sRet.isOk()) {
3750 ALOGW("%s: Failed to determine if device supports HAL3 %s, supportsCameraApi call failed",
3751 __FUNCTION__, cameraId.string());
3752 return;
3753 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003754
3755 // Collect the logical cameras without holding mStatusLock in updateStatus
3756 // as that can lead to a deadlock(b/162192331).
3757 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08003758 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08003759 // of the listeners with both the mStatusLock and mStatusListenerLock held
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003760 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind, &supportsHAL3,
3761 &logicalCameraIds]
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003762 (const String8& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003763
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003764 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003765 // Update torch status if it has a flash unit.
3766 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003767 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003768 if (getTorchStatusLocked(cameraId, &torchStatus) !=
3769 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003770 TorchModeStatus newTorchStatus =
3771 status == StatusInternal::PRESENT ?
3772 TorchModeStatus::AVAILABLE_OFF :
3773 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003774 if (torchStatus != newTorchStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003775 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003776 }
3777 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003778 }
3779
3780 Mutex::Autolock lock(mStatusListenerLock);
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003781 notifyPhysicalCameraStatusLocked(mapToInterface(status), String16(cameraId),
3782 logicalCameraIds, deviceKind);
Shuzhen Wang43858162020-01-10 13:42:15 -08003783
Ruben Brunkcc776712015-02-17 20:18:47 -08003784 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003785 bool isVendorListener = listener->isVendorListener();
3786 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
3787 listener->getListenerPid(), listener->getListenerUid()) ||
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07003788 (isVendorListener && !supportsHAL3)) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003789 ALOGV("Skipping discovery callback for system-only camera/HAL1 device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003790 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003791 continue;
3792 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003793 listener->getListener()->onStatusChanged(mapToInterface(status),
Emilian Peev53722fa2019-02-22 17:47:20 -08003794 String16(cameraId));
Ruben Brunkcc776712015-02-17 20:18:47 -08003795 }
3796 });
Igor Murashkincba2c162013-03-20 15:56:31 -07003797}
3798
Shuzhen Wang695044d2020-03-06 09:02:23 -08003799void CameraService::updateOpenCloseStatus(const String8& cameraId, bool open,
3800 const String16& clientPackageName) {
3801 Mutex::Autolock lock(mStatusListenerLock);
3802
3803 for (const auto& it : mListenerList) {
3804 if (!it->isOpenCloseCallbackAllowed()) {
3805 continue;
3806 }
3807
3808 binder::Status ret;
3809 String16 cameraId64(cameraId);
3810 if (open) {
3811 ret = it->getListener()->onCameraOpened(cameraId64, clientPackageName);
3812 } else {
3813 ret = it->getListener()->onCameraClosed(cameraId64);
3814 }
3815 if (!ret.isOk()) {
3816 ALOGE("%s: Failed to trigger onCameraOpened/onCameraClosed callback: %d", __FUNCTION__,
3817 ret.exceptionCode());
3818 }
3819 }
3820}
3821
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003822template<class Func>
3823void CameraService::CameraState::updateStatus(StatusInternal status,
3824 const String8& cameraId,
3825 std::initializer_list<StatusInternal> rejectSourceStates,
3826 Func onStatusUpdatedLocked) {
3827 Mutex::Autolock lock(mStatusLock);
3828 StatusInternal oldStatus = mStatus;
3829 mStatus = status;
3830
3831 if (oldStatus == status) {
3832 return;
3833 }
3834
3835 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
3836 cameraId.string(), oldStatus, status);
3837
3838 if (oldStatus == StatusInternal::NOT_PRESENT &&
3839 (status != StatusInternal::PRESENT &&
3840 status != StatusInternal::ENUMERATING)) {
3841
3842 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
3843 __FUNCTION__);
3844 mStatus = oldStatus;
3845 return;
3846 }
3847
3848 /**
3849 * Sometimes we want to conditionally do a transition.
3850 * For example if a client disconnects, we want to go to PRESENT
3851 * only if we weren't already in NOT_PRESENT or ENUMERATING.
3852 */
3853 for (auto& rejectStatus : rejectSourceStates) {
3854 if (oldStatus == rejectStatus) {
3855 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
3856 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
3857 mStatus = oldStatus;
3858 return;
3859 }
3860 }
3861
3862 onStatusUpdatedLocked(cameraId, status);
3863}
3864
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003865status_t CameraService::getTorchStatusLocked(
3866 const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003867 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003868 if (!status) {
3869 return BAD_VALUE;
3870 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003871 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3872 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003873 // invalid camera ID or the camera doesn't have a flash unit
3874 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003875 }
3876
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003877 *status = mTorchStatusMap.valueAt(index);
3878 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003879}
3880
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003881status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003882 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003883 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3884 if (index == NAME_NOT_FOUND) {
3885 return BAD_VALUE;
3886 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003887 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003888
3889 return OK;
3890}
3891
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003892std::list<String16> CameraService::getLogicalCameras(
3893 const String8& physicalCameraId) {
3894 std::list<String16> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08003895 Mutex::Autolock lock(mCameraStatesLock);
3896 for (const auto& state : mCameraStates) {
3897 std::vector<std::string> physicalCameraIds;
3898 if (!mCameraProviderManager->isLogicalCamera(state.first.c_str(), &physicalCameraIds)) {
3899 // This is not a logical multi-camera.
3900 continue;
3901 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003902 if (std::find(physicalCameraIds.begin(), physicalCameraIds.end(), physicalCameraId.c_str())
Shuzhen Wang43858162020-01-10 13:42:15 -08003903 == physicalCameraIds.end()) {
3904 // cameraId is not a physical camera of this logical multi-camera.
3905 continue;
3906 }
3907
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003908 retList.emplace_back(String16(state.first));
3909 }
3910 return retList;
3911}
3912
3913void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
3914 const String16& physicalCameraId, const std::list<String16>& logicalCameraIds,
3915 SystemCameraKind deviceKind) {
3916 // mStatusListenerLock is expected to be locked
3917 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08003918 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003919 // Note: we check only the deviceKind of the physical camera id
3920 // since, logical camera ids and their physical camera ids are
3921 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07003922 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
3923 listener->getListenerPid(), listener->getListenerUid())) {
3924 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003925 String8(physicalCameraId).c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07003926 continue;
3927 }
Shuzhen Wang43858162020-01-10 13:42:15 -08003928 listener->getListener()->onPhysicalCameraStatusChanged(status,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003929 logicalCameraId, physicalCameraId);
Shuzhen Wang43858162020-01-10 13:42:15 -08003930 }
3931 }
3932}
3933
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003934
Svet Ganova453d0d2018-01-11 15:37:58 -08003935void CameraService::blockClientsForUid(uid_t uid) {
3936 const auto clients = mActiveClientManager.getAll();
3937 for (auto& current : clients) {
3938 if (current != nullptr) {
3939 const auto basicClient = current->getValue();
3940 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
3941 basicClient->block();
3942 }
3943 }
3944 }
3945}
3946
Michael Grooverd1d435a2018-12-18 17:39:42 -08003947void CameraService::blockAllClients() {
3948 const auto clients = mActiveClientManager.getAll();
3949 for (auto& current : clients) {
3950 if (current != nullptr) {
3951 const auto basicClient = current->getValue();
3952 if (basicClient.get() != nullptr) {
3953 basicClient->block();
3954 }
3955 }
3956 }
3957}
3958
Evan Severson190ad252021-01-07 20:37:15 -08003959void CameraService::setMuteForAllClients(userid_t userId, bool enabled) {
3960 const auto clients = mActiveClientManager.getAll();
3961 for (auto& current : clients) {
3962 if (current != nullptr) {
3963 const auto basicClient = current->getValue();
3964 if (basicClient.get() != nullptr
3965 && multiuser_get_user_id(basicClient->getClientUid()) == userId) {
3966 basicClient->setCameraMute(enabled);
3967 }
3968 }
3969 }
3970}
3971
Svet Ganova453d0d2018-01-11 15:37:58 -08003972// NOTE: This is a remote API - make sure all args are validated
3973status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
3974 if (!checkCallingPermission(sManageCameraPermission, nullptr, nullptr)) {
3975 return PERMISSION_DENIED;
3976 }
3977 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
3978 return BAD_VALUE;
3979 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003980 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003981 return handleSetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07003982 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003983 return handleResetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07003984 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003985 return handleGetUidState(args, out, err);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003986 } else if (args.size() >= 2 && args[0] == String16("set-rotate-and-crop")) {
3987 return handleSetRotateAndCrop(args);
3988 } else if (args.size() >= 1 && args[0] == String16("get-rotate-and-crop")) {
3989 return handleGetRotateAndCrop(out);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08003990 } else if (args.size() >= 2 && args[0] == String16("set-image-dump-mask")) {
3991 return handleSetImageDumpMask(args);
3992 } else if (args.size() >= 1 && args[0] == String16("get-image-dump-mask")) {
3993 return handleGetImageDumpMask(out);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003994 } else if (args.size() >= 2 && args[0] == String16("set-camera-mute")) {
3995 return handleSetCameraMute(args);
Svet Ganova453d0d2018-01-11 15:37:58 -08003996 } else if (args.size() == 1 && args[0] == String16("help")) {
3997 printHelp(out);
3998 return NO_ERROR;
3999 }
4000 printHelp(err);
4001 return BAD_VALUE;
4002}
4003
4004status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004005 String16 packageName = args[1];
4006
Svet Ganova453d0d2018-01-11 15:37:58 -08004007 bool active = false;
4008 if (args[2] == String16("active")) {
4009 active = true;
4010 } else if ((args[2] != String16("idle"))) {
4011 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
4012 return BAD_VALUE;
4013 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004014
4015 int userId = 0;
4016 if (args.size() >= 5 && args[3] == String16("--user")) {
4017 userId = atoi(String8(args[4]));
4018 }
4019
4020 uid_t uid;
4021 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
4022 return BAD_VALUE;
4023 }
4024
4025 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08004026 return NO_ERROR;
4027}
4028
4029status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004030 String16 packageName = args[1];
4031
4032 int userId = 0;
4033 if (args.size() >= 4 && args[2] == String16("--user")) {
4034 userId = atoi(String8(args[3]));
4035 }
4036
4037 uid_t uid;
4038 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004039 return BAD_VALUE;
4040 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004041
4042 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08004043 return NO_ERROR;
4044}
4045
4046status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004047 String16 packageName = args[1];
4048
4049 int userId = 0;
4050 if (args.size() >= 4 && args[2] == String16("--user")) {
4051 userId = atoi(String8(args[3]));
4052 }
4053
4054 uid_t uid;
4055 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004056 return BAD_VALUE;
4057 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004058
4059 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004060 return dprintf(out, "active\n");
4061 } else {
4062 return dprintf(out, "idle\n");
4063 }
4064}
4065
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004066status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
4067 int rotateValue = atoi(String8(args[1]));
4068 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
4069 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
4070 Mutex::Autolock lock(mServiceLock);
4071
4072 mOverrideRotateAndCropMode = rotateValue;
4073
4074 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
4075
4076 const auto clients = mActiveClientManager.getAll();
4077 for (auto& current : clients) {
4078 if (current != nullptr) {
4079 const auto basicClient = current->getValue();
4080 if (basicClient.get() != nullptr) {
4081 basicClient->setRotateAndCropOverride(rotateValue);
4082 }
4083 }
4084 }
4085
4086 return OK;
4087}
4088
4089status_t CameraService::handleGetRotateAndCrop(int out) {
4090 Mutex::Autolock lock(mServiceLock);
4091
4092 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
4093}
4094
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004095status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
4096 char *endPtr;
4097 errno = 0;
4098 String8 maskString8 = String8(args[1]);
4099 long maskValue = strtol(maskString8.c_str(), &endPtr, 10);
4100
4101 if (errno != 0) return BAD_VALUE;
4102 if (endPtr != maskString8.c_str() + maskString8.size()) return BAD_VALUE;
4103 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
4104
4105 Mutex::Autolock lock(mServiceLock);
4106
4107 mImageDumpMask = maskValue;
4108
4109 return OK;
4110}
4111
4112status_t CameraService::handleGetImageDumpMask(int out) {
4113 Mutex::Autolock lock(mServiceLock);
4114
4115 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
4116}
4117
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004118status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
4119 int muteValue = strtol(String8(args[1]), nullptr, 10);
4120 if (errno != 0) return BAD_VALUE;
4121
4122 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
4123 Mutex::Autolock lock(mServiceLock);
4124
4125 mOverrideCameraMuteMode = (muteValue == 1);
4126
4127 const auto clients = mActiveClientManager.getAll();
4128 for (auto& current : clients) {
4129 if (current != nullptr) {
4130 const auto basicClient = current->getValue();
4131 if (basicClient.get() != nullptr) {
4132 if (basicClient->supportsCameraMute()) {
4133 basicClient->setCameraMute(mOverrideCameraMuteMode);
4134 }
4135 }
4136 }
4137 }
4138
4139 return OK;
4140}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004141
Svet Ganova453d0d2018-01-11 15:37:58 -08004142status_t CameraService::printHelp(int out) {
4143 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07004144 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
4145 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
4146 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004147 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
4148 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
4149 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004150 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
4151 " Valid values 0=OFF, 1=ON for JPEG\n"
4152 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004153 " set-camera-mute <0/1> enable or disable camera muting\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08004154 " help print this message\n");
4155}
4156
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004157int32_t CameraService::updateAudioRestriction() {
4158 Mutex::Autolock lock(mServiceLock);
4159 return updateAudioRestrictionLocked();
4160}
4161
4162int32_t CameraService::updateAudioRestrictionLocked() {
4163 int32_t mode = 0;
4164 // iterate through all active client
4165 for (const auto& i : mActiveClientManager.getAll()) {
4166 const auto clientSp = i->getValue();
4167 mode |= clientSp->getAudioRestriction();
4168 }
4169
4170 bool modeChanged = (mAudioRestriction != mode);
4171 mAudioRestriction = mode;
4172 if (modeChanged) {
4173 mAppOps.setCameraAudioRestriction(mode);
4174 }
4175 return mode;
4176}
4177
Evan Severson190ad252021-01-07 20:37:15 -08004178bool CameraService::isUserSensorPrivacyEnabledForUid(uid_t uid) {
4179 userid_t userId = multiuser_get_user_id(uid);
4180 if (mCameraSensorPrivacyPolicies.find(userId) == mCameraSensorPrivacyPolicies.end()) {
4181 sp<SensorPrivacyPolicy> userPolicy = new SensorPrivacyPolicy(this);
4182 if (userPolicy->registerSelfForIndividual(userId) != OK) {
4183 return false;
4184 }
4185 mCameraSensorPrivacyPolicies[userId] = userPolicy;
4186 }
4187 return mCameraSensorPrivacyPolicies[userId]->isSensorPrivacyEnabled();
4188}
4189
Mathias Agopian65ab4712010-07-14 17:59:35 -07004190}; // namespace android