blob: 6ac61cbe64fd5561b1bdbc84391073c2bb1d1bb6 [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>
Ruben Brunkcc776712015-02-17 20:18:47 -080044#include <binder/ProcessInfoService.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080045#include <binder/IResultReceiver.h>
Steven Moreland89a2c5c2020-01-31 15:02:25 -080046#include <binderthreadstate/CallerUtils.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070047#include <cutils/atomic.h>
Nipun Kwatrab5ca4612010-09-11 19:31:10 -070048#include <cutils/properties.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080049#include <cutils/misc.h>
Mathias Agopiandf712ea2012-02-25 18:48:35 -080050#include <gui/Surface.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070051#include <hardware/hardware.h>
Jayant Chowdharybe543d42018-08-15 13:16:14 -070052#include "hidl/HidlCameraService.h"
53#include <hidl/HidlTransportSupport.h>
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -080054#include <hwbinder/IPCThreadState.h>
Eino-Ville Talvalad89821e2016-04-20 11:23:50 -070055#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070056#include <media/AudioSystem.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080057#include <media/IMediaHTTPService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070058#include <media/mediaplayer.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070059#include <mediautils/BatteryNotifier.h>
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{
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -0700148
Ruben Brunkcc776712015-02-17 20:18:47 -0800149 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800150
Iliyan Malchev8951a972011-04-14 16:55:59 -0700151 BnCameraService::onFirstRef();
152
Ruben Brunk99e69712015-05-26 17:25:07 -0700153 // Update battery life tracking if service is restarting
154 BatteryNotifier& notifier(BatteryNotifier::getInstance());
155 notifier.noteResetCamera();
156 notifier.noteResetFlashlight();
157
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800158 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800159
Emilian Peevf53f66e2017-04-11 14:29:43 +0100160 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800161 if (res == OK) {
162 mInitialized = true;
163 }
164
Svet Ganova453d0d2018-01-11 15:37:58 -0800165 mUidPolicy = new UidPolicy(this);
166 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800167 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
168 mSensorPrivacyPolicy->registerSelf();
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700169 mAppOps.setCameraAudioRestriction(mAudioRestriction);
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700170 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
171 if (hcs->registerAsService() != android::OK) {
172 ALOGE("%s: Failed to register default android.frameworks.cameraservice.service@1.0",
173 __FUNCTION__);
174 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700175
176 // This needs to be last call in this function, so that it's as close to
177 // ServiceManager::addService() as possible.
Shuzhen Wang316781a2020-08-18 18:11:01 -0700178 CameraServiceProxyWrapper::pingCameraServiceProxy();
Shuzhen Wang24b44152019-09-20 10:38:11 -0700179 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800180}
181
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800182status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800183 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100184
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800185 std::vector<std::string> deviceIds;
186 {
187 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800188
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800189 if (nullptr == mCameraProviderManager.get()) {
190 mCameraProviderManager = new CameraProviderManager();
191 res = mCameraProviderManager->initialize(this);
192 if (res != OK) {
193 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
194 __FUNCTION__, strerror(-res), res);
195 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100196 }
197 }
198
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800199
200 // Setup vendor tags before we call get_camera_info the first time
201 // because HAL might need to setup static vendor keys in get_camera_info
202 // TODO: maybe put this into CameraProviderManager::initialize()?
203 mCameraProviderManager->setUpVendorTags();
204
205 if (nullptr == mFlashlight.get()) {
206 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700207 }
208
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800209 res = mFlashlight->findFlashUnits();
210 if (res != OK) {
211 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
212 }
213
214 deviceIds = mCameraProviderManager->getCameraDeviceIds();
215 }
216
217
218 for (auto& cameraId : deviceIds) {
219 String8 id8 = String8(cameraId.c_str());
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800220 if (getCameraState(id8) == nullptr) {
221 onDeviceStatusChanged(id8, CameraDeviceStatus::PRESENT);
222 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800223 }
224
225 return OK;
226}
227
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800228void CameraService::broadcastTorchModeStatus(const String8& cameraId, TorchModeStatus status) {
229 Mutex::Autolock lock(mStatusListenerLock);
230
231 for (auto& i : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700232 i->getListener()->onTorchStatusChanged(mapToInterface(status), String16{cameraId});
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800233 }
234}
235
Mathias Agopian65ab4712010-07-14 17:59:35 -0700236CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800237 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800238 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800239 mSensorPrivacyPolicy->unregisterSelf();
Evan Severson190ad252021-01-07 20:37:15 -0800240
241 for (auto const& [_, policy] : mCameraSensorPrivacyPolicies) {
242 policy->unregisterSelf();
243 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700244}
245
Emilian Peevaee727d2017-05-04 16:35:48 +0100246void CameraService::onNewProviderRegistered() {
247 enumerateProviders();
248}
249
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700250void CameraService::filterAPI1SystemCameraLocked(
251 const std::vector<std::string> &normalDeviceIds) {
252 mNormalDeviceIdsWithoutSystemCamera.clear();
253 for (auto &deviceId : normalDeviceIds) {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700254 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
255 if (getSystemCameraKind(String8(deviceId.c_str()), &deviceKind) != OK) {
256 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, deviceId.c_str());
257 continue;
258 }
259 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700260 // All system camera ids will necessarily come after public camera
261 // device ids as per the HAL interface contract.
262 break;
263 }
264 mNormalDeviceIdsWithoutSystemCamera.push_back(deviceId);
265 }
266 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
267 mNormalDeviceIdsWithoutSystemCamera.size());
268}
269
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700270status_t CameraService::getSystemCameraKind(const String8& cameraId, SystemCameraKind *kind) const {
271 auto state = getCameraState(cameraId);
272 if (state != nullptr) {
273 *kind = state->getSystemCameraKind();
274 return OK;
275 }
276 // Hidden physical camera ids won't have CameraState
277 return mCameraProviderManager->getSystemCameraKind(cameraId.c_str(), kind);
278}
279
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800280void CameraService::updateCameraNumAndIds() {
281 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700282 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
283 // Excludes hidden secure cameras
284 mNumberOfCameras =
285 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
286 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800287 mNormalDeviceIds =
288 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700289 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800290}
291
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100292void CameraService::addStates(const String8 id) {
293 std::string cameraId(id.c_str());
294 hardware::camera::common::V1_0::CameraResourceCost cost;
295 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700296 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100297 if (res != OK) {
298 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
299 return;
300 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700301 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
302 if (res != OK) {
303 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
304 return;
305 }
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100306 std::set<String8> conflicting;
307 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
308 conflicting.emplace(String8(cost.conflictingDevices[i].c_str()));
309 }
310
311 {
312 Mutex::Autolock lock(mCameraStatesLock);
313 mCameraStates.emplace(id, std::make_shared<CameraState>(id, cost.resourceCost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700314 conflicting, deviceKind));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100315 }
316
317 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100318 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100319 mTorchStatusMap.add(id, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800320
321 broadcastTorchModeStatus(id, TorchModeStatus::AVAILABLE_OFF);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100322 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800323
324 updateCameraNumAndIds();
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100325 logDeviceAdded(id, "Device added");
326}
327
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100328void CameraService::removeStates(const String8 id) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800329 updateCameraNumAndIds();
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100330 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100331 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100332 mTorchStatusMap.removeItem(id);
333 }
334
335 {
336 Mutex::Autolock lock(mCameraStatesLock);
337 mCameraStates.erase(id);
338 }
339}
340
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800341void CameraService::onDeviceStatusChanged(const String8& id,
342 CameraDeviceStatus newHalStatus) {
343 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
344 id.string(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700345
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800346 StatusInternal newStatus = mapToInternal(newHalStatus);
347
Ruben Brunkcc776712015-02-17 20:18:47 -0800348 std::shared_ptr<CameraState> state = getCameraState(id);
349
350 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700351 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100352 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700353 __FUNCTION__, id.string());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100354
355 // First add as absent to make sure clients are notified below
356 addStates(id);
357
358 updateStatus(newStatus, id);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700359 } else {
360 ALOGE("%s: Bad camera ID %s", __FUNCTION__, id.string());
361 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700362 return;
363 }
364
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800365 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800366
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800367 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800368 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700369 return;
370 }
371
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800372 if (newStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700373 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
374 newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800375
376 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
377 // to this device until the status changes
378 updateStatus(StatusInternal::NOT_PRESENT, id);
379
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800380 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700381 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800382 // Don't do this in updateStatus to avoid deadlock over mServiceLock
383 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700384
Ruben Brunkcc776712015-02-17 20:18:47 -0800385 // Remove cached shim parameters
386 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700387
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800388 // Remove online as well as offline client from the list of active clients,
389 // if they are present
390 clientToDisconnectOnline = removeClientLocked(id);
391 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + id);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700392 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800393
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800394 disconnectClient(id, clientToDisconnectOnline);
395 disconnectClient(kOfflineDevice + id, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700396
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100397 removeStates(id);
Ruben Brunkcc776712015-02-17 20:18:47 -0800398 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800399 if (oldStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700400 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
401 newStatus));
402 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800403 updateStatus(newStatus, id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700404 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800405}
Igor Murashkincba2c162013-03-20 15:56:31 -0700406
Shuzhen Wang43858162020-01-10 13:42:15 -0800407void CameraService::onDeviceStatusChanged(const String8& id,
408 const String8& physicalId,
409 CameraDeviceStatus newHalStatus) {
410 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
411 __FUNCTION__, id.string(), physicalId.string(), newHalStatus);
412
413 StatusInternal newStatus = mapToInternal(newHalStatus);
414
415 std::shared_ptr<CameraState> state = getCameraState(id);
416
417 if (state == nullptr) {
418 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
419 __FUNCTION__, id.string(), physicalId.string());
420 return;
421 }
422
423 StatusInternal logicalCameraStatus = state->getStatus();
424 if (logicalCameraStatus != StatusInternal::PRESENT &&
425 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
426 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
427 __FUNCTION__, physicalId.string(), newHalStatus, logicalCameraStatus);
428 return;
429 }
430
431 bool updated = false;
432 if (newStatus == StatusInternal::PRESENT) {
433 updated = state->removeUnavailablePhysicalId(physicalId);
434 } else {
435 updated = state->addUnavailablePhysicalId(physicalId);
436 }
437
438 if (updated) {
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800439 String8 idCombo = id + " : " + physicalId;
440 if (newStatus == StatusInternal::PRESENT) {
441 logDeviceAdded(idCombo,
442 String8::format("Device status changed to %d", newStatus));
443 } else {
444 logDeviceRemoved(idCombo,
445 String8::format("Device status changed to %d", newStatus));
446 }
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700447 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
448 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
449 if (getSystemCameraKind(id, &deviceKind) != OK) {
450 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.string());
451 return;
452 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800453 String16 id16(id), physicalId16(physicalId);
454 Mutex::Autolock lock(mStatusListenerLock);
455 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700456 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
457 listener->getListenerPid(), listener->getListenerUid())) {
458 ALOGV("Skipping discovery callback for system-only camera device %s",
459 id.c_str());
460 continue;
461 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800462 listener->getListener()->onPhysicalCameraStatusChanged(mapToInterface(newStatus),
463 id16, physicalId16);
464 }
465 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700466}
467
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800468void CameraService::disconnectClient(const String8& id, sp<BasicClient> clientToDisconnect) {
469 if (clientToDisconnect.get() != nullptr) {
470 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
471 __FUNCTION__, id.string());
472 // Notify the client of disconnection
473 clientToDisconnect->notifyError(
474 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
475 CaptureResultExtras{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800476 clientToDisconnect->disconnect();
477 }
478}
479
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800480void CameraService::onTorchStatusChanged(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800481 TorchModeStatus newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800482 Mutex::Autolock al(mTorchStatusMutex);
483 onTorchStatusChangedLocked(cameraId, newStatus);
484}
485
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800486void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800487 TorchModeStatus newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800488 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
489 __FUNCTION__, cameraId.string(), newStatus);
490
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800491 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800492 status_t res = getTorchStatusLocked(cameraId, &status);
493 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700494 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
495 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800496 return;
497 }
498 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800499 return;
500 }
501
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800502 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800503 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800504 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
505 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800506 return;
507 }
508
Ruben Brunkcc776712015-02-17 20:18:47 -0800509 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700510 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700511 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700512 auto iter = mTorchUidMap.find(cameraId);
513 if (iter != mTorchUidMap.end()) {
514 int oldUid = iter->second.second;
515 int newUid = iter->second.first;
516 BatteryNotifier& notifier(BatteryNotifier::getInstance());
517 if (oldUid != newUid) {
518 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800519 if (status == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700520 notifier.noteFlashlightOff(cameraId, oldUid);
521 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800522 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700523 notifier.noteFlashlightOn(cameraId, newUid);
524 }
525 iter->second.second = newUid;
526 } else {
527 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800528 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700529 notifier.noteFlashlightOn(cameraId, oldUid);
530 } else {
531 notifier.noteFlashlightOff(cameraId, oldUid);
532 }
533 }
534 }
535 }
536
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800537 broadcastTorchModeStatus(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800538}
539
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700540static bool hasPermissionsForSystemCamera(int callingPid, int callingUid) {
541 return checkPermission(sSystemCameraPermission, callingPid, callingUid) &&
542 checkPermission(sCameraPermission, callingPid, callingUid);
543}
544
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800545Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700546 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100547 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700548 bool hasSystemCameraPermissions =
549 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
550 CameraThreadState::getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700551 switch (type) {
552 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700553 if (hasSystemCameraPermissions) {
554 *numCameras = static_cast<int>(mNormalDeviceIds.size());
555 } else {
556 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
557 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800558 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700559 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700560 if (hasSystemCameraPermissions) {
561 *numCameras = mNumberOfCameras;
562 } else {
563 *numCameras = mNumberOfCamerasWithoutSystemCamera;
564 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800565 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700566 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800567 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700568 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800569 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
570 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700571 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800572 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700573}
574
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800575Status CameraService::getCameraInfo(int cameraId,
576 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700577 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100578 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700579 std::string cameraIdStr = cameraIdIntToStrLocked(cameraId);
580 if (shouldRejectSystemCameraConnection(String8(cameraIdStr.c_str()))) {
581 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
582 "characteristics for system only device %s: ", cameraIdStr.c_str());
583 }
Emilian Peevaee727d2017-05-04 16:35:48 +0100584
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800585 if (!mInitialized) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800586 return STATUS_ERROR(ERROR_DISCONNECTED,
587 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -0700588 }
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700589 bool hasSystemCameraPermissions =
590 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
591 CameraThreadState::getCallingUid());
592 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
593 if (hasSystemCameraPermissions) {
594 cameraIdBound = mNumberOfCameras;
595 }
596 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800597 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
598 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700599 }
600
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800601 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800602 status_t err = mCameraProviderManager->getCameraInfo(
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700603 cameraIdStr.c_str(), cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100604 if (err != OK) {
605 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
606 "Error retrieving camera info from device %d: %s (%d)", cameraId,
607 strerror(-err), err);
Ruben Brunkcc776712015-02-17 20:18:47 -0800608 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100609
Ruben Brunkcc776712015-02-17 20:18:47 -0800610 return ret;
611}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700612
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800613std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700614 const std::vector<std::string> *deviceIds = &mNormalDeviceIdsWithoutSystemCamera;
615 auto callingPid = CameraThreadState::getCallingPid();
616 auto callingUid = CameraThreadState::getCallingUid();
617 if (checkPermission(sSystemCameraPermission, callingPid, callingUid) ||
618 getpid() == callingPid) {
619 deviceIds = &mNormalDeviceIds;
620 }
621 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(deviceIds->size())) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800622 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700623 __FUNCTION__, cameraIdInt, deviceIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800624 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800625 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800626
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700627 return (*deviceIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800628}
629
630String8 CameraService::cameraIdIntToStr(int cameraIdInt) {
631 Mutex::Autolock lock(mServiceLock);
632 return String8(cameraIdIntToStrLocked(cameraIdInt).c_str());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800633}
634
635Status CameraService::getCameraCharacteristics(const String16& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800636 CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700637 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700638 if (!cameraInfo) {
639 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800640 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -0700641 }
642
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800643 if (!mInitialized) {
644 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800645 return STATUS_ERROR(ERROR_DISCONNECTED,
646 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -0700647 }
648
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700649 if (shouldRejectSystemCameraConnection(String8(cameraId))) {
650 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
651 "characteristics for system only device %s: ", String8(cameraId).string());
652 }
653
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800654 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800655
Emilian Peevf53f66e2017-04-11 14:29:43 +0100656 status_t res = mCameraProviderManager->getCameraCharacteristics(
657 String8(cameraId).string(), cameraInfo);
658 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700659 if (res == NAME_NOT_FOUND) {
660 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
661 "characteristics for unknown device %s: %s (%d)", String8(cameraId).string(),
662 strerror(-res), res);
663 } else {
664 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
665 "characteristics for device %s: %s (%d)", String8(cameraId).string(),
666 strerror(-res), res);
667 }
Ruben Brunkb2119af2014-05-09 19:57:56 -0700668 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700669 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
670 if (getSystemCameraKind(String8(cameraId), &deviceKind) != OK) {
671 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, String8(cameraId).string());
672 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera kind "
673 "for device %s", String8(cameraId).string());
674 }
Jayant Chowdhary12361932018-08-27 14:46:13 -0700675 int callingPid = CameraThreadState::getCallingPid();
676 int callingUid = CameraThreadState::getCallingUid();
Emilian Peeve20c6372018-08-14 18:45:53 +0100677 std::vector<int32_t> tagsRemoved;
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700678 // If it's not calling from cameraserver, check the permission only if
679 // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
680 // it would've already been checked in shouldRejectSystemCameraConnection.
Emilian Peeve20c6372018-08-14 18:45:53 +0100681 if ((callingPid != getpid()) &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700682 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700683 !checkPermission(sCameraPermission, callingPid, callingUid)) {
Emilian Peeve20c6372018-08-14 18:45:53 +0100684 res = cameraInfo->removePermissionEntries(
685 mCameraProviderManager->getProviderTagIdLocked(String8(cameraId).string()),
686 &tagsRemoved);
687 if (res != OK) {
688 cameraInfo->clear();
689 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
690 " characteristics needing camera permission for device %s: %s (%d)",
691 String8(cameraId).string(), strerror(-res), res);
692 }
693 }
694
695 if (!tagsRemoved.empty()) {
696 res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
697 tagsRemoved.data(), tagsRemoved.size());
698 if (res != OK) {
699 cameraInfo->clear();
700 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
701 "keys needing permission for device %s: %s (%d)", String8(cameraId).string(),
702 strerror(-res), res);
703 }
704 }
705
Zhijun He2b59be82013-09-25 10:14:30 -0700706 return ret;
707}
708
Ruben Brunkcc776712015-02-17 20:18:47 -0800709String8 CameraService::getFormattedCurrentTime() {
710 time_t now = time(nullptr);
711 char formattedTime[64];
712 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
713 return String8(formattedTime);
714}
715
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800716Status CameraService::getCameraVendorTagDescriptor(
717 /*out*/
718 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700719 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800720 if (!mInitialized) {
721 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800722 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800723 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -0800724 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
725 if (globalDescriptor != nullptr) {
726 *desc = *(globalDescriptor.get());
727 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800728 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800729}
730
Emilian Peev71c73a22017-03-21 16:35:51 +0000731Status CameraService::getCameraVendorTagCache(
732 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
733 ATRACE_CALL();
734 if (!mInitialized) {
735 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
736 return STATUS_ERROR(ERROR_DISCONNECTED,
737 "Camera subsystem not available");
738 }
739 sp<VendorTagDescriptorCache> globalCache =
740 VendorTagDescriptorCache::getGlobalVendorTagCache();
741 if (globalCache != nullptr) {
742 *cache = *(globalCache.get());
743 }
744 return Status::ok();
745}
746
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -0700747void CameraService::clearCachedVariables() {
748 BasicClient::BasicClient::sCameraService = nullptr;
749}
750
Emilian Peevb91f1802021-03-23 14:50:28 -0700751int CameraService::getDeviceVersion(const String8& cameraId, int* facing, int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700752 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800753
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800754 int deviceVersion = 0;
755
Emilian Peevf53f66e2017-04-11 14:29:43 +0100756 status_t res;
757 hardware::hidl_version maxVersion{0,0};
758 res = mCameraProviderManager->getHighestSupportedVersion(cameraId.string(),
759 &maxVersion);
760 if (res != OK) return -1;
761 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800762
Emilian Peevf53f66e2017-04-11 14:29:43 +0100763 hardware::CameraInfo info;
764 if (facing) {
765 res = mCameraProviderManager->getCameraInfo(cameraId.string(), &info);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -0800766 if (res != OK) return -1;
Emilian Peevf53f66e2017-04-11 14:29:43 +0100767 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -0700768 if (orientation) {
769 *orientation = info.orientation;
770 }
Igor Murashkin634a5152013-02-20 17:15:11 -0800771 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100772
Igor Murashkin634a5152013-02-20 17:15:11 -0800773 return deviceVersion;
774}
775
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800776Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700777 switch(err) {
778 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800779 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800780 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800781 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
782 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800783 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800784 return STATUS_ERROR(ERROR_DISCONNECTED,
785 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700786 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800787 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
788 "Camera HAL encountered error %d: %s",
789 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700790 }
Igor Murashkinbfc99152013-02-27 12:55:20 -0800791}
792
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800793Status CameraService::makeClient(const sp<CameraService>& cameraService,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800794 const sp<IInterface>& cameraCb, const String16& packageName,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700795 const std::optional<String16>& featureId, const String8& cameraId,
796 int api1CameraId, int facing, int clientPid, uid_t clientUid, int servicePid,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800797 int deviceVersion, apiLevel effectiveApiLevel,
Ruben Brunkcc776712015-02-17 20:18:47 -0800798 /*out*/sp<BasicClient>* client) {
799
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700800 // Create CameraClient based on device version reported by the HAL.
801 switch(deviceVersion) {
802 case CAMERA_DEVICE_API_VERSION_1_0:
803 ALOGE("Camera using old HAL version: %d", deviceVersion);
804 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
805 "Camera device \"%s\" HAL version %d no longer supported",
806 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800807 break;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700808 case CAMERA_DEVICE_API_VERSION_3_0:
809 case CAMERA_DEVICE_API_VERSION_3_1:
810 case CAMERA_DEVICE_API_VERSION_3_2:
811 case CAMERA_DEVICE_API_VERSION_3_3:
812 case CAMERA_DEVICE_API_VERSION_3_4:
813 case CAMERA_DEVICE_API_VERSION_3_5:
814 case CAMERA_DEVICE_API_VERSION_3_6:
Shuzhen Wang83bff122020-11-20 15:51:39 -0800815 case CAMERA_DEVICE_API_VERSION_3_7:
Ruben Brunkcc776712015-02-17 20:18:47 -0800816 if (effectiveApiLevel == API_1) { // Camera1 API route
817 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800818 *client = new Camera2Client(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800819 cameraId, api1CameraId,
820 facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700821 servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800822 } else { // Camera2 API route
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800823 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
824 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800825 *client = new CameraDeviceClient(cameraService, tmp, packageName, featureId,
826 cameraId, facing, clientPid, clientUid, servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800827 }
828 break;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700829 default:
Ruben Brunkcc776712015-02-17 20:18:47 -0800830 // Should not be reachable
831 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800832 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800833 "Camera device \"%s\" has unknown HAL version %d",
834 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800835 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800836 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800837}
838
Ruben Brunk6267b532015-04-30 17:44:07 -0700839String8 CameraService::toString(std::set<userid_t> intSet) {
840 String8 s("");
841 bool first = true;
842 for (userid_t i : intSet) {
843 if (first) {
844 s.appendFormat("%d", i);
845 first = false;
846 } else {
847 s.appendFormat(", %d", i);
848 }
849 }
850 return s;
851}
852
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800853int32_t CameraService::mapToInterface(TorchModeStatus status) {
854 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
855 switch (status) {
856 case TorchModeStatus::NOT_AVAILABLE:
857 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
858 break;
859 case TorchModeStatus::AVAILABLE_OFF:
860 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
861 break;
862 case TorchModeStatus::AVAILABLE_ON:
863 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
864 break;
865 default:
866 ALOGW("Unknown new flash status: %d", status);
867 }
868 return serviceStatus;
869}
870
871CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
872 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
873 switch (status) {
874 case CameraDeviceStatus::NOT_PRESENT:
875 serviceStatus = StatusInternal::NOT_PRESENT;
876 break;
877 case CameraDeviceStatus::PRESENT:
878 serviceStatus = StatusInternal::PRESENT;
879 break;
880 case CameraDeviceStatus::ENUMERATING:
881 serviceStatus = StatusInternal::ENUMERATING;
882 break;
883 default:
884 ALOGW("Unknown new HAL device status: %d", status);
885 }
886 return serviceStatus;
887}
888
889int32_t CameraService::mapToInterface(StatusInternal status) {
890 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
891 switch (status) {
892 case StatusInternal::NOT_PRESENT:
893 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
894 break;
895 case StatusInternal::PRESENT:
896 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
897 break;
898 case StatusInternal::ENUMERATING:
899 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
900 break;
901 case StatusInternal::NOT_AVAILABLE:
902 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
903 break;
904 case StatusInternal::UNKNOWN:
905 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
906 break;
907 default:
908 ALOGW("Unknown new internal device status: %d", status);
909 }
910 return serviceStatus;
911}
912
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800913Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -0700914 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700915
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800916 String16 internalPackageName("cameraserver");
Ruben Brunkcc776712015-02-17 20:18:47 -0800917 String8 id = String8::format("%d", cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800918 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800919 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800920 if (!(ret = connectHelper<ICameraClient,Client>(
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800921 sp<ICameraClient>{nullptr}, id, cameraId,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +0900922 internalPackageName, {}, uid, USE_CALLING_PID,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700923 API_1, /*shimUpdateOnly*/ true, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800924 ).isOk()) {
925 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
Ruben Brunkb2119af2014-05-09 19:57:56 -0700926 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800927 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700928}
929
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800930Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -0700931 /*out*/
932 CameraParameters* parameters) {
933
934 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
935
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800936 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -0700937
938 if (parameters == NULL) {
939 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800940 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -0700941 }
942
Ruben Brunkcc776712015-02-17 20:18:47 -0800943 String8 id = String8::format("%d", cameraId);
944
945 // Check if we already have parameters
946 {
947 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -0700948 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -0800949 auto cameraState = getCameraState(id);
950 if (cameraState == nullptr) {
951 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800952 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
953 "Invalid camera ID: %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -0800954 }
955 CameraParameters p = cameraState->getShimParams();
956 if (!p.isEmpty()) {
957 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800958 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700959 }
960 }
961
Jayant Chowdhary12361932018-08-27 14:46:13 -0700962 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -0800963 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -0700964 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800965 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800966 // Error already logged by callee
967 return ret;
968 }
969
970 // Check for parameters again
971 {
972 // Scope for service lock
973 Mutex::Autolock lock(mServiceLock);
974 auto cameraState = getCameraState(id);
975 if (cameraState == nullptr) {
976 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800977 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
978 "Invalid camera ID: %s", id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -0700979 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800980 CameraParameters p = cameraState->getShimParams();
981 if (!p.isEmpty()) {
982 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800983 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700984 }
985 }
986
Ruben Brunkcc776712015-02-17 20:18:47 -0800987 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
988 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800989 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -0700990}
991
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800992// Can camera service trust the caller based on the calling UID?
993static bool isTrustedCallingUid(uid_t uid) {
994 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -0700995 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800996 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -0700997 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800998 return true;
999 default:
1000 return false;
1001 }
1002}
1003
Nicholas Sauera3620332019-04-03 14:05:17 -07001004static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1005 PermissionController pc;
1006 uid = pc.getPackageUid(packageName, 0);
1007 if (uid <= 0) {
1008 ALOGE("Unknown package: '%s'", String8(packageName).string());
1009 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
1010 return BAD_VALUE;
1011 }
1012
1013 if (userId < 0) {
1014 ALOGE("Invalid user: %d", userId);
1015 dprintf(err, "Invalid user: %d\n", userId);
1016 return BAD_VALUE;
1017 }
1018
1019 uid = multiuser_get_uid(userId, uid);
1020 return NO_ERROR;
1021}
1022
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001023Status CameraService::validateConnectLocked(const String8& cameraId,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001024 const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
1025 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001026
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001027#ifdef __BRILLO__
1028 UNUSED(clientName8);
1029 UNUSED(clientUid);
1030 UNUSED(clientPid);
1031 UNUSED(originalClientPid);
1032#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001033 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1034 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001035 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001036 return allowed;
1037 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001038#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001039
Jayant Chowdhary12361932018-08-27 14:46:13 -07001040 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001041
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001042 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001043 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1044 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001045 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1046 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001047 }
1048
Ruben Brunkcc776712015-02-17 20:18:47 -08001049 if (getCameraState(cameraId) == nullptr) {
1050 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1051 cameraId.string());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001052 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1053 "No camera device with ID \"%s\" available", cameraId.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001054 }
1055
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001056 status_t err = checkIfDeviceIsUsable(cameraId);
1057 if (err != NO_ERROR) {
1058 switch(err) {
1059 case -ENODEV:
1060 case -EBUSY:
1061 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1062 "No camera device with ID \"%s\" currently available", cameraId.string());
1063 default:
1064 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1065 "Unknown error connecting to ID \"%s\"", cameraId.string());
1066 }
1067 }
1068 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001069}
1070
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001071Status CameraService::validateClientPermissionsLocked(const String8& cameraId,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001072 const String8& clientName8, int& clientUid, int& clientPid,
1073 /*out*/int& originalClientPid) const {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001074 int callingPid = CameraThreadState::getCallingPid();
1075 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001076
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001077 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001078 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001079 clientUid = callingUid;
1080 } else if (!isTrustedCallingUid(callingUid)) {
1081 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1082 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001083 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1084 "Untrusted caller (calling PID %d, UID %d) trying to "
1085 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1086 callingPid, callingUid, cameraId.string(),
1087 clientName8.string(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001088 }
1089
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001090 // Check if we can trust clientPid
1091 if (clientPid == USE_CALLING_PID) {
1092 clientPid = callingPid;
1093 } else if (!isTrustedCallingUid(callingUid)) {
1094 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1095 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001096 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1097 "Untrusted caller (calling PID %d, UID %d) trying to "
1098 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1099 callingPid, callingUid, cameraId.string(),
1100 clientName8.string(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001101 }
1102
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001103 if (shouldRejectSystemCameraConnection(cameraId)) {
1104 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1105 cameraId.c_str());
1106 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
1107 "available", cameraId.string());
1108 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001109 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1110 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1111 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
1112 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
1113 "found while trying to query device kind", cameraId.string());
1114
1115 }
1116
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001117 // If it's not calling from cameraserver, check the permission if the
1118 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1119 // android.permission.SYSTEM_CAMERA for system only camera devices).
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001120 if (callingPid != getpid() &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001121 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001122 !checkPermission(sCameraPermission, clientPid, clientUid)) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001123 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001124 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1125 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
1126 clientName8.string(), clientUid, clientPid, cameraId.string());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001127 }
1128
Svet Ganova453d0d2018-01-11 15:37:58 -08001129 // Make sure the UID is in an active state to use the camera
Svet Ganov7b4ab782018-03-25 12:48:10 -07001130 if (!mUidPolicy->isUidActive(callingUid, String16(clientName8))) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001131 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001132 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1133 clientPid, clientUid);
1134 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001135 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1136 "calling UID %d proc state %" PRId32 ")",
1137 clientName8.string(), clientUid, clientPid, cameraId.string(),
1138 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001139 }
1140
Michael Grooverd1d435a2018-12-18 17:39:42 -08001141 // If sensor privacy is enabled then prevent access to the camera
1142 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1143 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1144 return STATUS_ERROR_FMT(ERROR_DISABLED,
1145 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
1146 "is enabled", clientName8.string(), clientUid, clientPid, cameraId.string());
1147 }
1148
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001149 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1150 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001151 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001152 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001153
Ruben Brunk6267b532015-04-30 17:44:07 -07001154 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001155
Ruben Brunka8ca9152015-04-07 14:23:40 -07001156 // Only allow clients who are being used by the current foreground device user, unless calling
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001157 // from our own process OR the caller is using the cameraserver's HIDL interface.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001158 if (getCurrentServingCall() != BinderCallType::HWBINDER && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001159 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001160 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1161 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
1162 toString(mAllowedUsers).string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001163 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1164 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
1165 clientUserId, cameraId.string());
Ruben Brunk36597b22015-03-20 22:15:57 -07001166 }
1167
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001168 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001169}
1170
1171status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
1172 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001173 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001174 if (cameraState == nullptr) {
1175 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1176 cameraId.string());
1177 return -ENODEV;
1178 }
1179
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001180 StatusInternal currentStatus = cameraState->getStatus();
1181 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001182 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
1183 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001184 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001185 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001186 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
1187 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001188 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001189 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001190
Ruben Brunkcc776712015-02-17 20:18:47 -08001191 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001192}
1193
Ruben Brunkcc776712015-02-17 20:18:47 -08001194void CameraService::finishConnectLocked(const sp<BasicClient>& client,
1195 const CameraService::DescriptorPtr& desc) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001196
Ruben Brunkcc776712015-02-17 20:18:47 -08001197 // Make a descriptor for the incoming client
1198 auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
1199 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1200
1201 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
1202 String8(client->getPackageName()));
1203
1204 if (evicted.size() > 0) {
1205 // This should never happen - clients should already have been removed in disconnect
1206 for (auto& i : evicted) {
1207 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
1208 __FUNCTION__, i->getKey().string());
1209 }
1210
1211 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1212 __FUNCTION__);
1213 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001214
1215 // And register a death notification for the client callback. Do
1216 // this last to avoid Binder policy where a nested Binder
1217 // transaction might be pre-empted to service the client death
1218 // notification if the client process dies before linkToDeath is
1219 // invoked.
1220 sp<IBinder> remoteCallback = client->getRemote();
1221 if (remoteCallback != nullptr) {
1222 remoteCallback->linkToDeath(this);
1223 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001224}
1225
1226status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
1227 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
1228 /*out*/
1229 sp<BasicClient>* client,
1230 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001231 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001232 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001233 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001234 DescriptorPtr clientDescriptor;
1235 {
1236 if (effectiveApiLevel == API_1) {
1237 // If we are using API1, any existing client for this camera ID with the same remote
1238 // should be returned rather than evicted to allow MediaRecorder to work properly.
1239
1240 auto current = mActiveClientManager.get(cameraId);
1241 if (current != nullptr) {
1242 auto clientSp = current->getValue();
1243 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001244 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
1245 ALOGW("CameraService connect called from same client, but with a different"
1246 " API level, evicting prior client...");
1247 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001248 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001249 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001250 *client = clientSp;
1251 return NO_ERROR;
1252 }
1253 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001254 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001255 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001256
Ruben Brunkcc776712015-02-17 20:18:47 -08001257 // Get current active client PIDs
1258 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1259 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001260
Emilian Peev8131a262017-02-01 12:33:43 +00001261 std::vector<int> priorityScores(ownerPids.size());
1262 std::vector<int> states(ownerPids.size());
Igor Murashkine6800ce2013-03-04 17:25:57 -08001263
Emilian Peev8131a262017-02-01 12:33:43 +00001264 // Get priority scores of all active PIDs
1265 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1266 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1267 /*out*/&priorityScores[0]);
1268 if (err != OK) {
1269 ALOGE("%s: Priority score query failed: %d",
1270 __FUNCTION__, err);
1271 return err;
1272 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001273
Ruben Brunkcc776712015-02-17 20:18:47 -08001274 // Update all active clients' priorities
Emilian Peev8131a262017-02-01 12:33:43 +00001275 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
Ruben Brunkcc776712015-02-17 20:18:47 -08001276 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
Emilian Peev8131a262017-02-01 12:33:43 +00001277 pidToPriorityMap.emplace(ownerPids[i],
Jayant Chowdharyc578a502019-05-08 10:57:54 -07001278 resource_policy::ClientPriority(priorityScores[i], states[i],
1279 /* isVendorClient won't get copied over*/ false));
Ruben Brunkcc776712015-02-17 20:18:47 -08001280 }
1281 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001282
Ruben Brunkcc776712015-02-17 20:18:47 -08001283 // Get state for the given cameraId
1284 auto state = getCameraState(cameraId);
1285 if (state == nullptr) {
1286 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1287 clientPid, cameraId.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001288 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001289 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001290 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001291
1292 // Make descriptor for incoming client
Shuzhen Wang2db86ff2018-04-25 01:11:17 +00001293 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001294 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1295 state->getConflicting(),
Emilian Peev8131a262017-02-01 12:33:43 +00001296 priorityScores[priorityScores.size() - 1],
1297 clientPid,
1298 states[states.size() - 1]);
Ruben Brunkcc776712015-02-17 20:18:47 -08001299
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001300 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1301
Ruben Brunkcc776712015-02-17 20:18:47 -08001302 // Find clients that would be evicted
1303 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1304
1305 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1306 // background, so we cannot do evictions
1307 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1308 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1309 " priority).", clientPid);
1310
1311 sp<BasicClient> clientSp = clientDescriptor->getValue();
1312 String8 curTime = getFormattedCurrentTime();
1313 auto incompatibleClients =
1314 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1315
1316 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Emilian Peev8131a262017-02-01 12:33:43 +00001317 "(PID %d, score %d state %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001318 cameraId.string(), packageName.string(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001319 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001320
1321 for (auto& i : incompatibleClients) {
1322 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001323 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
1324 i->getKey().string(),
1325 String8{i->getValue()->getPackageName()}.string(),
1326 i->getOwnerId(), i->getPriority().getScore(),
1327 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001328 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00001329 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(),
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001330 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001331 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001332 }
1333
1334 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001335 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001336 mEventLog.add(msg);
1337
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001338 auto current = mActiveClientManager.get(cameraId);
1339 if (current != nullptr) {
1340 return -EBUSY; // CAMERA_IN_USE
1341 } else {
1342 return -EUSERS; // MAX_CAMERAS_IN_USE
1343 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001344 }
1345
1346 for (auto& i : evicted) {
1347 sp<BasicClient> clientSp = i->getValue();
1348 if (clientSp.get() == nullptr) {
1349 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1350
1351 // TODO: Remove this
1352 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1353 __FUNCTION__);
1354 mActiveClientManager.remove(i);
1355 continue;
1356 }
1357
1358 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1359 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001360 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001361
Ruben Brunkcc776712015-02-17 20:18:47 -08001362 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001363 logEvent(String8::format("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00001364 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1365 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001366 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
Emilian Peev8131a262017-02-01 12:33:43 +00001367 i->getOwnerId(), i->getPriority().getScore(),
1368 i->getPriority().getState(), cameraId.string(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001369 packageName.string(), clientPid, clientPriority.getScore(),
1370 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08001371
1372 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001373 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001374 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001375 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001376 }
1377
Ruben Brunkcc776712015-02-17 20:18:47 -08001378 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1379 // other clients from connecting in mServiceLockWrapper if held
1380 mServiceLock.unlock();
1381
1382 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07001383 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001384
1385 // Destroy evicted clients
1386 for (auto& i : evictedClients) {
1387 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001388 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001389 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001390
Jayant Chowdhary12361932018-08-27 14:46:13 -07001391 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08001392
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001393 for (const auto& i : evictedClients) {
1394 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1395 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1396 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1397 if (ret == TIMED_OUT) {
1398 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1399 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1400 mActiveClientManager.toString().string());
1401 return -EBUSY;
1402 }
1403 if (ret != NO_ERROR) {
1404 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1405 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1406 ret, mActiveClientManager.toString().string());
1407 return ret;
1408 }
1409 }
1410
1411 evictedClients.clear();
1412
Ruben Brunkcc776712015-02-17 20:18:47 -08001413 // Once clients have been disconnected, relock
1414 mServiceLock.lock();
1415
1416 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1417 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1418 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001419 }
1420
Ruben Brunkcc776712015-02-17 20:18:47 -08001421 *partial = clientDescriptor;
1422 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001423}
1424
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001425Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001426 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001427 int api1CameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001428 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001429 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001430 int clientPid,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001431 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001432 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001433
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001434 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001435 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001436
1437 String8 id = cameraIdIntToStr(api1CameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001438 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001439 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001440 clientPackageName, {}, clientUid, clientPid, API_1,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001441 /*shimUpdateOnly*/ false, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001442
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001443 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001444 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001445 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001446 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001447 }
1448
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001449 *device = client;
1450 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001451}
1452
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001453bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
1454 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001455 // If the client is not a vendor client, don't add listener if
1456 // a) the camera is a publicly hidden secure camera OR
1457 // b) the camera is a system only camera and the client doesn't
1458 // have android.permission.SYSTEM_CAMERA permissions.
1459 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
1460 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1461 !hasPermissionsForSystemCamera(clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001462 return true;
1463 }
1464 return false;
1465}
1466
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001467bool CameraService::shouldRejectSystemCameraConnection(const String8& cameraId) const {
1468 // Rules for rejection:
1469 // 1) If cameraserver tries to access this camera device, accept the
1470 // connection.
1471 // 2) The camera device is a publicly hidden secure camera device AND some
1472 // component is trying to access it on a non-hwbinder thread (generally a non HAL client),
1473 // reject it.
1474 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
1475 // and the serving thread is a non hwbinder thread, the client must have
1476 // android.permission.SYSTEM_CAMERA permissions to connect.
1477
1478 int cPid = CameraThreadState::getCallingPid();
1479 int cUid = CameraThreadState::getCallingUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001480 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
1481 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001482 // This isn't a known camera ID, so it's not a system camera
1483 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
1484 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001485 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001486
1487 // (1) Cameraserver trying to connect, accept.
1488 if (CameraThreadState::getCallingPid() == getpid()) {
1489 return false;
1490 }
1491 // (2)
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001492 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001493 systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
1494 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
1495 return true;
1496 }
1497 // (3) Here we only check for permissions if it is a system only camera device. This is since
1498 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
1499 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
1500 // same behavior for system camera devices.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001501 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001502 systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1503 !hasPermissionsForSystemCamera(cPid, cUid)) {
1504 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
1505 cameraId.c_str());
1506 return true;
1507 }
1508
1509 return false;
1510}
1511
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001512Status CameraService::connectDevice(
1513 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001514 const String16& cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001515 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001516 const std::optional<String16>& clientFeatureId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001517 int clientUid,
1518 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001519 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001520
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001521 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001522 Status ret = Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001523 String8 id = String8(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001524 sp<CameraDeviceClient> client = nullptr;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001525 String16 clientPackageNameAdj = clientPackageName;
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001526
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001527 if (getCurrentServingCall() == BinderCallType::HWBINDER) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001528 std::string vendorClient =
1529 StringPrintf("vendor.client.pid<%d>", CameraThreadState::getCallingPid());
1530 clientPackageNameAdj = String16(vendorClient.c_str());
1531 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001532 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001533 /*api1CameraId*/-1, clientPackageNameAdj, clientFeatureId,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001534 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08001535
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001536 if(!ret.isOk()) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001537 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageNameAdj),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001538 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001539 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001540 }
1541
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001542 *device = client;
1543 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001544}
1545
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001546template<class CALLBACK, class CLIENT>
1547Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001548 int api1CameraId, const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001549 const std::optional<String16>& clientFeatureId, int clientUid, int clientPid,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001550 apiLevel effectiveApiLevel, bool shimUpdateOnly,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001551 /*out*/sp<CLIENT>& device) {
1552 binder::Status ret = binder::Status::ok();
1553
1554 String8 clientName8(clientPackageName);
1555
1556 int originalClientPid = 0;
1557
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001558 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001559 "Camera API version %d", clientPid, clientName8.string(), cameraId.string(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001560 static_cast<int>(effectiveApiLevel));
1561
Shuzhen Wang316781a2020-08-18 18:11:01 -07001562 nsecs_t openTimeNs = systemTime();
1563
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001564 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001565 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07001566 int orientation = 0;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001567 bool isNdk = (clientPackageName.size() == 0);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001568 {
1569 // Acquire mServiceLock and prevent other clients from connecting
1570 std::unique_ptr<AutoConditionLock> lock =
1571 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1572
1573 if (lock == nullptr) {
1574 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
1575 , clientPid);
1576 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1577 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
1578 cameraId.string(), clientName8.string(), clientPid);
1579 }
1580
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07001581 // Enforce client permissions and do basic validity checks
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001582 if(!(ret = validateConnectLocked(cameraId, clientName8,
1583 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
1584 return ret;
1585 }
1586
1587 // Check the shim parameters after acquiring lock, if they have already been updated and
1588 // we were doing a shim update, return immediately
1589 if (shimUpdateOnly) {
1590 auto cameraState = getCameraState(cameraId);
1591 if (cameraState != nullptr) {
1592 if (!cameraState->getShimParams().isEmpty()) return ret;
1593 }
1594 }
1595
1596 status_t err;
1597
1598 sp<BasicClient> clientTmp = nullptr;
1599 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
1600 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
1601 IInterface::asBinder(cameraCb), clientName8, /*out*/&clientTmp,
1602 /*out*/&partial)) != NO_ERROR) {
1603 switch (err) {
1604 case -ENODEV:
1605 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1606 "No camera device with ID \"%s\" currently available",
1607 cameraId.string());
1608 case -EBUSY:
1609 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1610 "Higher-priority client using camera, ID \"%s\" currently unavailable",
1611 cameraId.string());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001612 case -EUSERS:
1613 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1614 "Too many cameras already open, cannot open camera \"%s\"",
1615 cameraId.string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001616 default:
1617 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1618 "Unexpected error %s (%d) opening camera \"%s\"",
1619 strerror(-err), err, cameraId.string());
1620 }
1621 }
1622
1623 if (clientTmp.get() != nullptr) {
1624 // Handle special case for API1 MediaRecorder where the existing client is returned
1625 device = static_cast<CLIENT*>(clientTmp.get());
1626 return ret;
1627 }
1628
1629 // give flashlight a chance to close devices if necessary.
1630 mFlashlight->prepareDeviceOpen(cameraId);
1631
Emilian Peevb91f1802021-03-23 14:50:28 -07001632 int deviceVersion = getDeviceVersion(cameraId, /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08001633 if (facing == -1) {
1634 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.string());
1635 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1636 "Unable to get camera device \"%s\" facing", cameraId.string());
1637 }
1638
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001639 sp<BasicClient> tmp = nullptr;
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001640 if(!(ret = makeClient(this, cameraCb, clientPackageName, clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001641 cameraId, api1CameraId, facing,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001642 clientPid, clientUid, getpid(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001643 deviceVersion, effectiveApiLevel,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001644 /*out*/&tmp)).isOk()) {
1645 return ret;
1646 }
1647 client = static_cast<CLIENT*>(tmp.get());
1648
1649 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
1650 __FUNCTION__);
1651
Emilian Peevbd8c5032018-02-14 23:05:40 +00001652 err = client->initialize(mCameraProviderManager, mMonitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001653 if (err != OK) {
1654 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001655 // Errors could be from the HAL module open call or from AppOpsManager
1656 switch(err) {
1657 case BAD_VALUE:
1658 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1659 "Illegal argument to HAL module for camera \"%s\"", cameraId.string());
1660 case -EBUSY:
1661 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1662 "Camera \"%s\" is already open", cameraId.string());
1663 case -EUSERS:
1664 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1665 "Too many cameras already open, cannot open camera \"%s\"",
1666 cameraId.string());
1667 case PERMISSION_DENIED:
1668 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1669 "No permission to open camera \"%s\"", cameraId.string());
1670 case -EACCES:
1671 return STATUS_ERROR_FMT(ERROR_DISABLED,
1672 "Camera \"%s\" disabled by policy", cameraId.string());
1673 case -ENODEV:
1674 default:
1675 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1676 "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
1677 strerror(-err), err);
1678 }
1679 }
1680
1681 // Update shim paremeters for legacy clients
1682 if (effectiveApiLevel == API_1) {
1683 // Assume we have always received a Client subclass for API1
1684 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
1685 String8 rawParams = shimClient->getParameters();
1686 CameraParameters params(rawParams);
1687
1688 auto cameraState = getCameraState(cameraId);
1689 if (cameraState != nullptr) {
1690 cameraState->setShimParams(params);
1691 } else {
1692 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
1693 __FUNCTION__, cameraId.string());
1694 }
1695 }
1696
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001697 // Set rotate-and-crop override behavior
1698 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
1699 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
Emilian Peevb91f1802021-03-23 14:50:28 -07001700 } else if (CameraServiceProxyWrapper::isRotateAndCropOverrideNeeded(clientPackageName,
1701 orientation, facing)) {
1702 client->setRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_90);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001703 }
1704
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08001705 // Set camera muting behavior
1706 if (client->supportsCameraMute()) {
Evan Severson190ad252021-01-07 20:37:15 -08001707 client->setCameraMute(mOverrideCameraMuteMode ||
1708 isUserSensorPrivacyEnabledForUid(clientUid));
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08001709 }
1710
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001711 if (shimUpdateOnly) {
1712 // If only updating legacy shim parameters, immediately disconnect client
1713 mServiceLock.unlock();
1714 client->disconnect();
1715 mServiceLock.lock();
1716 } else {
1717 // Otherwise, add client to active clients list
1718 finishConnectLocked(client, partial);
1719 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001720
1721 client->setImageDumpMask(mImageDumpMask);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001722 } // lock is destroyed, allow further connect calls
1723
1724 // Important: release the mutex here so the client can call back into the service from its
1725 // destructor (can be at the end of the call)
1726 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001727
1728 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
1729 CameraServiceProxyWrapper::logOpen(cameraId, facing, clientPackageName,
1730 effectiveApiLevel, isNdk, openLatencyMs);
1731
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001732 return ret;
1733}
1734
Emilian Peevb2bc5a42019-11-20 16:02:14 -08001735status_t CameraService::addOfflineClient(String8 cameraId, sp<BasicClient> offlineClient) {
1736 if (offlineClient.get() == nullptr) {
1737 return BAD_VALUE;
1738 }
1739
1740 {
1741 // Acquire mServiceLock and prevent other clients from connecting
1742 std::unique_ptr<AutoConditionLock> lock =
1743 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1744
1745 if (lock == nullptr) {
1746 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
1747 , __FUNCTION__, offlineClient->getClientPid());
1748 return TIMED_OUT;
1749 }
1750
1751 auto onlineClientDesc = mActiveClientManager.get(cameraId);
1752 if (onlineClientDesc.get() == nullptr) {
1753 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
1754 cameraId.c_str());
1755 return BAD_VALUE;
1756 }
1757
1758 // Offline clients do not evict or conflict with other online devices. Resource sharing
1759 // conflicts are handled by the camera provider which will either succeed or fail before
1760 // reaching this method.
1761 const auto& onlinePriority = onlineClientDesc->getPriority();
1762 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
1763 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
1764 /*conflictingKeys*/ std::set<String8>(), onlinePriority.getScore(),
1765 onlineClientDesc->getOwnerId(), onlinePriority.getState());
1766
1767 // Allow only one offline device per camera
1768 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
1769 if (!incompatibleClients.empty()) {
1770 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
1771 return BAD_VALUE;
1772 }
1773
1774 auto err = offlineClient->initialize(mCameraProviderManager, mMonitorTags);
1775 if (err != OK) {
1776 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
1777 return err;
1778 }
1779
1780 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
1781 if (evicted.size() > 0) {
1782 for (auto& i : evicted) {
1783 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
1784 __FUNCTION__, i->getKey().string());
1785 }
1786
1787 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
1788 "properly", __FUNCTION__);
1789
1790 return BAD_VALUE;
1791 }
1792
1793 logConnectedOffline(offlineClientDesc->getKey(),
1794 static_cast<int>(offlineClientDesc->getOwnerId()),
1795 String8(offlineClient->getPackageName()));
1796
1797 sp<IBinder> remoteCallback = offlineClient->getRemote();
1798 if (remoteCallback != nullptr) {
1799 remoteCallback->linkToDeath(this);
1800 }
1801 } // lock is destroyed, allow further connect calls
1802
1803 return OK;
1804}
1805
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001806Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001807 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001808 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001809
1810 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07001811 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001812 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001813 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1814 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001815 }
1816
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001817 String8 id = String8(cameraId.string());
Jayant Chowdhary12361932018-08-27 14:46:13 -07001818 int uid = CameraThreadState::getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001819
1820 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08001821 auto state = getCameraState(id);
1822 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001823 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001824 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1825 "Camera ID \"%s\" is a not valid camera ID", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001826 }
1827
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001828 StatusInternal cameraStatus = state->getStatus();
1829 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001830 cameraStatus != StatusInternal::NOT_AVAILABLE) {
1831 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001832 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1833 "Camera ID \"%s\" is a not valid camera ID", id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001834 }
1835
1836 {
1837 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001838 TorchModeStatus status;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001839 status_t err = getTorchStatusLocked(id, &status);
1840 if (err != OK) {
1841 if (err == NAME_NOT_FOUND) {
1842 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1843 "Camera \"%s\" does not have a flash unit", id.string());
1844 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001845 ALOGE("%s: getting current torch status failed for camera %s",
1846 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001847 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1848 "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
1849 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001850 }
1851
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001852 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001853 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001854 ALOGE("%s: torch mode of camera %s is not available because "
1855 "camera is in use", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001856 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1857 "Torch for camera \"%s\" is not available due to an existing camera user",
1858 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001859 } else {
1860 ALOGE("%s: torch mode of camera %s is not available due to "
1861 "insufficient resources", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001862 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1863 "Torch for camera \"%s\" is not available due to insufficient resources",
1864 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001865 }
1866 }
1867 }
1868
Ruben Brunk99e69712015-05-26 17:25:07 -07001869 {
1870 // Update UID map - this is used in the torch status changed callbacks, so must be done
1871 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07001872 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -07001873 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
1874 mTorchUidMap[id].first = uid;
1875 mTorchUidMap[id].second = uid;
1876 } else {
1877 // Set the pending UID
1878 mTorchUidMap[id].first = uid;
1879 }
1880 }
1881
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001882 status_t err = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07001883
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001884 if (err != OK) {
1885 int32_t errorCode;
1886 String8 msg;
1887 switch (err) {
1888 case -ENOSYS:
1889 msg = String8::format("Camera \"%s\" has no flashlight",
1890 id.string());
1891 errorCode = ERROR_ILLEGAL_ARGUMENT;
1892 break;
1893 default:
1894 msg = String8::format(
1895 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
1896 id.string(), enabled, strerror(-err), err);
1897 errorCode = ERROR_INVALID_OPERATION;
1898 }
1899 ALOGE("%s: %s", __FUNCTION__, msg.string());
1900 return STATUS_ERROR(errorCode, msg.string());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001901 }
1902
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001903 {
1904 // update the link to client's death
1905 Mutex::Autolock al(mTorchClientMapMutex);
1906 ssize_t index = mTorchClientMap.indexOfKey(id);
1907 if (enabled) {
1908 if (index == NAME_NOT_FOUND) {
1909 mTorchClientMap.add(id, clientBinder);
1910 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07001911 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001912 mTorchClientMap.replaceValueAt(index, clientBinder);
1913 }
1914 clientBinder->linkToDeath(this);
1915 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07001916 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001917 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001918 }
1919
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07001920 int clientPid = CameraThreadState::getCallingPid();
1921 const char *id_cstr = id.c_str();
1922 const char *torchState = enabled ? "on" : "off";
1923 ALOGI("Torch for camera id %s turned %s for client PID %d", id_cstr, torchState, clientPid);
1924 logTorchEvent(id_cstr, torchState , clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001925 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001926}
1927
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001928Status CameraService::notifySystemEvent(int32_t eventId,
1929 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001930 const int pid = CameraThreadState::getCallingPid();
1931 const int selfPid = getpid();
1932
1933 // Permission checks
1934 if (pid != selfPid) {
1935 // Ensure we're being called by system_server, or similar process with
1936 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001937 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001938 const int uid = CameraThreadState::getCallingUid();
1939 ALOGE("Permission Denial: cannot send updates to camera service about system"
1940 " events from pid=%d, uid=%d", pid, uid);
1941 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09001942 "No permission to send updates to camera service about system events"
1943 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001944 }
1945 }
1946
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001947 ATRACE_CALL();
1948
Ruben Brunk36597b22015-03-20 22:15:57 -07001949 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001950 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001951 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07001952 // from a system server crash
1953 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08001954 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001955 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07001956 break;
1957 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001958 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07001959 default: {
1960 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
1961 eventId);
1962 break;
1963 }
1964 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001965 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07001966}
1967
Emilian Peev53722fa2019-02-22 17:47:20 -08001968void CameraService::notifyMonitoredUids() {
1969 Mutex::Autolock lock(mStatusListenerLock);
1970
1971 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001972 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Emilian Peev53722fa2019-02-22 17:47:20 -08001973 if (!ret.isOk()) {
1974 ALOGE("%s: Failed to trigger permission callback: %d", __FUNCTION__,
1975 ret.exceptionCode());
1976 }
1977 }
1978}
1979
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08001980Status CameraService::notifyDeviceStateChange(int64_t newState) {
1981 const int pid = CameraThreadState::getCallingPid();
1982 const int selfPid = getpid();
1983
1984 // Permission checks
1985 if (pid != selfPid) {
1986 // Ensure we're being called by system_server, or similar process with
1987 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001988 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08001989 const int uid = CameraThreadState::getCallingUid();
1990 ALOGE("Permission Denial: cannot send updates to camera service about device"
1991 " state changes from pid=%d, uid=%d", pid, uid);
1992 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1993 "No permission to send updates to camera service about device state"
1994 " changes from pid=%d, uid=%d", pid, uid);
1995 }
1996 }
1997
1998 ATRACE_CALL();
1999
2000 using hardware::camera::provider::V2_5::DeviceState;
2001 hardware::hidl_bitfield<DeviceState> newDeviceState{};
2002 if (newState & ICameraService::DEVICE_STATE_BACK_COVERED) {
2003 newDeviceState |= DeviceState::BACK_COVERED;
2004 }
2005 if (newState & ICameraService::DEVICE_STATE_FRONT_COVERED) {
2006 newDeviceState |= DeviceState::FRONT_COVERED;
2007 }
2008 if (newState & ICameraService::DEVICE_STATE_FOLDED) {
2009 newDeviceState |= DeviceState::FOLDED;
2010 }
2011 // Only map vendor bits directly
2012 uint64_t vendorBits = static_cast<uint64_t>(newState) & 0xFFFFFFFF00000000l;
2013 newDeviceState |= vendorBits;
2014
2015 ALOGV("%s: New device state 0x%" PRIx64, __FUNCTION__, newDeviceState);
2016 Mutex::Autolock l(mServiceLock);
2017 mCameraProviderManager->notifyDeviceStateChange(newDeviceState);
2018
2019 return Status::ok();
2020}
2021
Jayant Chowdharycad23c22020-03-10 15:04:59 -07002022 Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002023 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
2024 ATRACE_CALL();
2025 if (!concurrentCameraIds) {
2026 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
2027 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
2028 }
2029
2030 if (!mInitialized) {
2031 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2032 return STATUS_ERROR(ERROR_DISCONNECTED,
2033 "Camera subsystem is not available");
2034 }
2035 // First call into the provider and get the set of concurrent camera
2036 // combinations
2037 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07002038 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002039 for (auto &combination : concurrentCameraCombinations) {
2040 std::vector<std::string> validCombination;
2041 for (auto &cameraId : combination) {
2042 // if the camera state is not present, skip
2043 String8 cameraIdStr(cameraId.c_str());
2044 auto state = getCameraState(cameraIdStr);
2045 if (state == nullptr) {
2046 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
2047 continue;
2048 }
2049 StatusInternal status = state->getStatus();
2050 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
2051 continue;
2052 }
2053 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
2054 continue;
2055 }
2056 validCombination.push_back(cameraId);
2057 }
2058 if (validCombination.size() != 0) {
2059 concurrentCameraIds->push_back(std::move(validCombination));
2060 }
2061 }
2062 return Status::ok();
2063}
2064
2065Status CameraService::isConcurrentSessionConfigurationSupported(
2066 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
2067 /*out*/bool* isSupported) {
2068 if (!isSupported) {
2069 ALOGE("%s: isSupported is NULL", __FUNCTION__);
2070 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
2071 }
2072
2073 if (!mInitialized) {
2074 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2075 return STATUS_ERROR(ERROR_DISCONNECTED,
2076 "Camera subsystem is not available");
2077 }
2078
2079 // Check for camera permissions
2080 int callingPid = CameraThreadState::getCallingPid();
2081 int callingUid = CameraThreadState::getCallingUid();
2082 if ((callingPid != getpid()) && !checkPermission(sCameraPermission, callingPid, callingUid)) {
2083 ALOGE("%s: pid %d doesn't have camera permissions", __FUNCTION__, callingPid);
2084 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2085 "android.permission.CAMERA needed to call"
2086 "isConcurrentSessionConfigurationSupported");
2087 }
2088
2089 status_t res =
2090 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
2091 cameraIdsAndSessionConfigurations, isSupported);
2092 if (res != OK) {
2093 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
2094 "support %s (%d)", strerror(-res), res);
2095 }
2096 return Status::ok();
2097}
2098
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002099Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
2100 /*out*/
2101 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002102 return addListenerHelper(listener, cameraStatuses);
2103}
2104
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002105binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
2106 std::vector<hardware::CameraStatus>* cameraStatuses) {
2107 return addListenerHelper(listener, cameraStatuses, false, true);
2108}
2109
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002110Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
2111 /*out*/
2112 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002113 bool isVendorListener, bool isProcessLocalTest) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002114
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002115 ATRACE_CALL();
2116
Igor Murashkinbfc99152013-02-27 12:55:20 -08002117 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08002118
Ruben Brunk3450ba72015-06-16 11:00:37 -07002119 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002120 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002121 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002122 }
2123
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002124 auto clientUid = CameraThreadState::getCallingUid();
2125 auto clientPid = CameraThreadState::getCallingPid();
Shuzhen Wang695044d2020-03-06 09:02:23 -08002126 bool openCloseCallbackAllowed = checkPermission(sCameraOpenCloseListenerPermission,
2127 clientPid, clientUid);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002128
Igor Murashkinbfc99152013-02-27 12:55:20 -08002129 Mutex::Autolock lock(mServiceLock);
2130
Ruben Brunkcc776712015-02-17 20:18:47 -08002131 {
2132 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08002133 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002134 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002135 ALOGW("%s: Tried to add listener %p which was already subscribed",
2136 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002137 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08002138 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002139 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002140
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002141 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08002142 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
2143 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002144 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08002145 if (ret != NO_ERROR) {
2146 String8 msg = String8::format("Failed to initialize service listener: %s (%d)",
2147 strerror(-ret), ret);
2148 ALOGE("%s: %s", __FUNCTION__, msg.string());
2149 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
2150 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002151 // The listener still needs to be added to the list of listeners, regardless of what
2152 // permissions the listener process has / whether it is a vendor listener. Since it might be
2153 // eligible to listen to other camera ids.
2154 mListenerList.emplace_back(serviceListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08002155 mUidPolicy->registerMonitorUid(clientUid);
Igor Murashkinbfc99152013-02-27 12:55:20 -08002156 }
2157
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002158 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07002159 {
Ruben Brunkcc776712015-02-17 20:18:47 -08002160 Mutex::Autolock lock(mCameraStatesLock);
2161 for (auto& i : mCameraStates) {
Shuzhen Wang43858162020-01-10 13:42:15 -08002162 cameraStatuses->emplace_back(i.first,
2163 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds());
Igor Murashkincba2c162013-03-20 15:56:31 -07002164 }
2165 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002166 // Remove the camera statuses that should be hidden from the client, we do
2167 // this after collecting the states in order to avoid holding
2168 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
2169 // the same time.
2170 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
2171 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
2172 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
2173 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
2174 ALOGE("%s: Invalid camera id %s, skipping status update",
2175 __FUNCTION__, s.cameraId.c_str());
2176 return true;
2177 }
2178 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
2179 clientUid);}), cameraStatuses->end());
2180
Igor Murashkincba2c162013-03-20 15:56:31 -07002181
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002182 /*
2183 * Immediately signal current torch status to this listener only
2184 * This may be a subset of all the devices, so don't include it in the response directly
2185 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002186 {
2187 Mutex::Autolock al(mTorchStatusMutex);
2188 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002189 String16 id = String16(mTorchStatusMap.keyAt(i).string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002190 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002191 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002192 }
2193
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002194 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08002195}
Ruben Brunkcc776712015-02-17 20:18:47 -08002196
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002197Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002198 ATRACE_CALL();
2199
Igor Murashkinbfc99152013-02-27 12:55:20 -08002200 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
2201
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002202 if (listener == 0) {
2203 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002204 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002205 }
2206
Igor Murashkinbfc99152013-02-27 12:55:20 -08002207 Mutex::Autolock lock(mServiceLock);
2208
Ruben Brunkcc776712015-02-17 20:18:47 -08002209 {
2210 Mutex::Autolock lock(mStatusListenerLock);
2211 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002212 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
2213 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid());
2214 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08002215 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002216 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002217 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002218 }
2219 }
2220
2221 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
2222 __FUNCTION__, listener.get());
2223
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002224 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08002225}
2226
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002227Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002228
2229 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002230 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
2231
2232 if (parameters == NULL) {
2233 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002234 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07002235 }
2236
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002237 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002238
2239 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002240 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07002241 // Error logged by caller
2242 return ret;
2243 }
2244
2245 String8 shimParamsString8 = shimParams.flatten();
2246 String16 shimParamsString16 = String16(shimParamsString8);
2247
2248 *parameters = shimParamsString16;
2249
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002250 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07002251}
2252
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002253Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
2254 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002255 ATRACE_CALL();
2256
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002257 const String8 id = String8(cameraId);
2258
2259 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002260
2261 switch (apiVersion) {
2262 case API_VERSION_1:
2263 case API_VERSION_2:
2264 break;
2265 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002266 String8 msg = String8::format("Unknown API version %d", apiVersion);
2267 ALOGE("%s: %s", __FUNCTION__, msg.string());
2268 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002269 }
2270
Emilian Peev28ad2ea2017-02-07 16:14:32 +00002271 int deviceVersion = getDeviceVersion(id);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002272 switch (deviceVersion) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002273 case CAMERA_DEVICE_API_VERSION_1_0:
2274 case CAMERA_DEVICE_API_VERSION_3_0:
2275 case CAMERA_DEVICE_API_VERSION_3_1:
2276 if (apiVersion == API_VERSION_2) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002277 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without shim",
2278 __FUNCTION__, id.string(), deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002279 *isSupported = false;
2280 } else { // if (apiVersion == API_VERSION_1) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002281 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always supported",
2282 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002283 *isSupported = true;
2284 }
2285 break;
2286 case CAMERA_DEVICE_API_VERSION_3_2:
2287 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -07002288 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002289 case CAMERA_DEVICE_API_VERSION_3_5:
Yin-Chia Yeh56d98ba2020-01-16 16:57:14 -08002290 case CAMERA_DEVICE_API_VERSION_3_6:
Shuzhen Wang83bff122020-11-20 15:51:39 -08002291 case CAMERA_DEVICE_API_VERSION_3_7:
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002292 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
2293 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002294 *isSupported = true;
2295 break;
2296 case -1: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002297 String8 msg = String8::format("Unknown camera ID %s", id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002298 ALOGE("%s: %s", __FUNCTION__, msg.string());
2299 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002300 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002301 default: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002302 String8 msg = String8::format("Unknown device version %x for device %s",
2303 deviceVersion, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002304 ALOGE("%s: %s", __FUNCTION__, msg.string());
2305 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
2306 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07002307 }
2308
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002309 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002310}
2311
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002312Status CameraService::isHiddenPhysicalCamera(const String16& cameraId,
2313 /*out*/ bool *isSupported) {
2314 ATRACE_CALL();
2315
2316 const String8 id = String8(cameraId);
2317
2318 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
2319 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(id.string());
2320
2321 return Status::ok();
2322}
2323
Ruben Brunkcc776712015-02-17 20:18:47 -08002324void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002325 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002326 for (auto& i : mActiveClientManager.getAll()) {
2327 auto clientSp = i->getValue();
2328 if (clientSp.get() == client) {
2329 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08002330 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07002331 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002332 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08002333}
2334
Ruben Brunkcc776712015-02-17 20:18:47 -08002335bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002336 bool ret = false;
2337 {
2338 // Acquire mServiceLock and prevent other clients from connecting
2339 std::unique_ptr<AutoConditionLock> lock =
2340 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08002341
Igor Murashkin634a5152013-02-20 17:15:11 -08002342
Ruben Brunkcc776712015-02-17 20:18:47 -08002343 std::vector<sp<BasicClient>> evicted;
2344 for (auto& i : mActiveClientManager.getAll()) {
2345 auto clientSp = i->getValue();
2346 if (clientSp.get() == nullptr) {
2347 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2348 mActiveClientManager.remove(i);
2349 continue;
2350 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08002351 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002352 mActiveClientManager.remove(i);
2353 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08002354
Ruben Brunkcc776712015-02-17 20:18:47 -08002355 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002356 clientSp->notifyError(
2357 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002358 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08002359 }
2360 }
2361
Ruben Brunkcc776712015-02-17 20:18:47 -08002362 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2363 // other clients from connecting in mServiceLockWrapper if held
2364 mServiceLock.unlock();
2365
Ruben Brunk36597b22015-03-20 22:15:57 -07002366 // Do not clear caller identity, remote caller should be client proccess
2367
Ruben Brunkcc776712015-02-17 20:18:47 -08002368 for (auto& i : evicted) {
2369 if (i.get() != nullptr) {
2370 i->disconnect();
2371 ret = true;
2372 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002373 }
2374
Ruben Brunkcc776712015-02-17 20:18:47 -08002375 // Reacquire mServiceLock
2376 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08002377
Ruben Brunkcc776712015-02-17 20:18:47 -08002378 } // lock is destroyed, allow further connect calls
2379
2380 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07002381}
2382
Ruben Brunkcc776712015-02-17 20:18:47 -08002383std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
2384 const String8& cameraId) const {
2385 std::shared_ptr<CameraState> state;
2386 {
2387 Mutex::Autolock lock(mCameraStatesLock);
2388 auto iter = mCameraStates.find(cameraId);
2389 if (iter != mCameraStates.end()) {
2390 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002391 }
2392 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002393 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002394}
2395
Ruben Brunkcc776712015-02-17 20:18:47 -08002396sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
2397 // Remove from active clients list
2398 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
2399 if (clientDescriptorPtr == nullptr) {
2400 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
2401 cameraId.string());
2402 return sp<BasicClient>{nullptr};
2403 }
2404
2405 return clientDescriptorPtr->getValue();
Keun young Parkd8973a72012-03-28 14:13:09 -07002406}
2407
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002408void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07002409 // Acquire mServiceLock and prevent other clients from connecting
2410 std::unique_ptr<AutoConditionLock> lock =
2411 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
2412
Ruben Brunk6267b532015-04-30 17:44:07 -07002413 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002414 for (size_t i = 0; i < newUserIds.size(); i++) {
2415 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07002416 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002417 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07002418 return;
2419 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002420 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07002421 }
2422
Ruben Brunka8ca9152015-04-07 14:23:40 -07002423
Ruben Brunk6267b532015-04-30 17:44:07 -07002424 if (newAllowedUsers == mAllowedUsers) {
2425 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
2426 return;
2427 }
2428
2429 logUserSwitch(mAllowedUsers, newAllowedUsers);
2430
2431 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07002432
2433 // Current user has switched, evict all current clients.
2434 std::vector<sp<BasicClient>> evicted;
2435 for (auto& i : mActiveClientManager.getAll()) {
2436 auto clientSp = i->getValue();
2437
2438 if (clientSp.get() == nullptr) {
2439 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2440 continue;
2441 }
2442
Ruben Brunk6267b532015-04-30 17:44:07 -07002443 // Don't evict clients that are still allowed.
2444 uid_t clientUid = clientSp->getClientUid();
2445 userid_t clientUserId = multiuser_get_user_id(clientUid);
2446 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
2447 continue;
2448 }
2449
Ruben Brunk36597b22015-03-20 22:15:57 -07002450 evicted.push_back(clientSp);
2451
2452 String8 curTime = getFormattedCurrentTime();
2453
2454 ALOGE("Evicting conflicting client for camera ID %s due to user change",
2455 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07002456
Ruben Brunk36597b22015-03-20 22:15:57 -07002457 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002458 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00002459 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
2460 " to user switch.", i->getKey().string(),
2461 String8{clientSp->getPackageName()}.string(),
2462 i->getOwnerId(), i->getPriority().getScore(),
2463 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07002464
2465 }
2466
2467 // Do not hold mServiceLock while disconnecting clients, but retain the condition
2468 // blocking other clients from connecting in mServiceLockWrapper if held.
2469 mServiceLock.unlock();
2470
2471 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07002472 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07002473
2474 for (auto& i : evicted) {
2475 i->disconnect();
2476 }
2477
Jayant Chowdhary12361932018-08-27 14:46:13 -07002478 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07002479
2480 // Reacquire mServiceLock
2481 mServiceLock.lock();
2482}
Ruben Brunkcc776712015-02-17 20:18:47 -08002483
Ruben Brunka8ca9152015-04-07 14:23:40 -07002484void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002485 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07002486 Mutex::Autolock l(mLogLock);
2487 mEventLog.add(String8::format("%s : %s", curTime.string(), event));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002488}
2489
Ruben Brunka8ca9152015-04-07 14:23:40 -07002490void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002491 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002492 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002493 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002494 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002495}
2496
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002497void CameraService::logDisconnectedOffline(const char* cameraId, int clientPid,
2498 const char* clientPackage) {
2499 // Log the clients evicted
2500 logEvent(String8::format("DISCONNECT offline device %s client for package %s (PID %d)",
2501 cameraId, clientPackage, clientPid));
2502}
2503
Ruben Brunka8ca9152015-04-07 14:23:40 -07002504void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002505 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002506 // Log the clients evicted
2507 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002508 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002509}
2510
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002511void CameraService::logConnectedOffline(const char* cameraId, int clientPid,
2512 const char* clientPackage) {
2513 // Log the clients evicted
2514 logEvent(String8::format("CONNECT offline device %s client for package %s (PID %d)", cameraId,
2515 clientPackage, clientPid));
2516}
2517
Ruben Brunka8ca9152015-04-07 14:23:40 -07002518void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002519 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002520 // Log the client rejected
2521 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002522 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002523}
2524
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002525void CameraService::logTorchEvent(const char* cameraId, const char *torchState, int clientPid) {
2526 // Log torch event
2527 logEvent(String8::format("Torch for camera id %s turned %s for client PID %d", cameraId,
2528 torchState, clientPid));
2529}
2530
Ruben Brunk6267b532015-04-30 17:44:07 -07002531void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
2532 const std::set<userid_t>& newUserIds) {
2533 String8 newUsers = toString(newUserIds);
2534 String8 oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002535 if (oldUsers.size() == 0) {
2536 oldUsers = "<None>";
2537 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07002538 // Log the new and old users
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002539 logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
Ruben Brunk6267b532015-04-30 17:44:07 -07002540 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002541}
2542
2543void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
2544 // Log the device removal
2545 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
2546}
2547
2548void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
2549 // Log the device removal
2550 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
2551}
2552
2553void CameraService::logClientDied(int clientPid, const char* reason) {
2554 // Log the device removal
2555 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07002556}
2557
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002558void CameraService::logServiceError(const char* msg, int errorCode) {
2559 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002560 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002561}
2562
Ruben Brunk36597b22015-03-20 22:15:57 -07002563status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
2564 uint32_t flags) {
2565
Mathias Agopian65ab4712010-07-14 17:59:35 -07002566 // Permission checks
2567 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002568 case SHELL_COMMAND_TRANSACTION: {
2569 int in = data.readFileDescriptor();
2570 int out = data.readFileDescriptor();
2571 int err = data.readFileDescriptor();
2572 int argc = data.readInt32();
2573 Vector<String16> args;
2574 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
2575 args.add(data.readString16());
2576 }
2577 sp<IBinder> unusedCallback;
2578 sp<IResultReceiver> resultReceiver;
2579 status_t status;
2580 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
2581 return status;
2582 }
2583 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
2584 return status;
2585 }
2586 status = shellCommand(in, out, err, args);
2587 if (resultReceiver != nullptr) {
2588 resultReceiver->send(status);
2589 }
2590 return NO_ERROR;
2591 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002592 }
2593
2594 return BnCameraService::onTransact(code, data, reply, flags);
2595}
2596
Mathias Agopian65ab4712010-07-14 17:59:35 -07002597// We share the media players for shutter and recording sound for all clients.
2598// A reference count is kept to determine when we will actually release the
2599// media players.
2600
Jaekyun Seokef498052018-03-23 13:09:44 +09002601sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
2602 sp<MediaPlayer> mp = new MediaPlayer();
2603 status_t error;
2604 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08002605 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09002606 error = mp->prepare();
2607 }
2608 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00002609 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09002610 mp->disconnect();
2611 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002612 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002613 }
2614 return mp;
2615}
2616
username5755fea2018-12-27 09:48:08 +08002617void CameraService::increaseSoundRef() {
2618 Mutex::Autolock lock(mSoundLock);
2619 mSoundRef++;
2620}
2621
2622void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002623 ATRACE_CALL();
2624
username5755fea2018-12-27 09:48:08 +08002625 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
2626 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
2627 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
2628 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
2629 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
2630 }
2631 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
2632 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
2633 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
2634 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002635 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08002636 }
2637 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
2638 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
2639 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
2640 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
2641 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002642 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002643}
2644
username5755fea2018-12-27 09:48:08 +08002645void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002646 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002647 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002648 if (--mSoundRef) return;
2649
2650 for (int i = 0; i < NUM_SOUNDS; i++) {
2651 if (mSoundPlayer[i] != 0) {
2652 mSoundPlayer[i]->disconnect();
2653 mSoundPlayer[i].clear();
2654 }
2655 }
2656}
2657
2658void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002659 ATRACE_CALL();
2660
Mathias Agopian65ab4712010-07-14 17:59:35 -07002661 LOG1("playSound(%d)", kind);
2662 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002663 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002664 sp<MediaPlayer> player = mSoundPlayer[kind];
2665 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08002666 player->seekTo(0);
2667 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002668 }
2669}
2670
2671// ----------------------------------------------------------------------------
2672
2673CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07002674 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002675 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09002676 const std::optional<String16>& clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002677 const String8& cameraIdStr,
2678 int api1CameraId, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002679 int clientPid, uid_t clientUid,
2680 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002681 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08002682 IInterface::asBinder(cameraClient),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002683 clientPackageName, clientFeatureId,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002684 cameraIdStr, cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002685 clientPid, clientUid,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002686 servicePid),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002687 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08002688{
Jayant Chowdhary12361932018-08-27 14:46:13 -07002689 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002690 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002691
Igor Murashkin44cfcf02013-03-01 16:22:28 -08002692 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002693
username5755fea2018-12-27 09:48:08 +08002694 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002695
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002696 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002697}
2698
Mathias Agopian65ab4712010-07-14 17:59:35 -07002699// tear down the client
2700CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002701 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08002702 mDestructionStarted = true;
2703
username5755fea2018-12-27 09:48:08 +08002704 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002705 // unconditionally disconnect. function is idempotent
2706 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002707}
2708
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002709sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
2710
Igor Murashkin634a5152013-02-20 17:15:11 -08002711CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002712 const sp<IBinder>& remoteCallback,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09002713 const String16& clientPackageName, const std::optional<String16>& clientFeatureId,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002714 const String8& cameraIdStr, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002715 int clientPid, uid_t clientUid,
2716 int servicePid):
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002717 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing),
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09002718 mClientPackageName(clientPackageName), mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002719 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002720 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07002721 mDisconnected(false), mUidIsTrusted(false),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002722 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002723 mRemoteBinder(remoteCallback)
Igor Murashkin634a5152013-02-20 17:15:11 -08002724{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002725 if (sCameraService == nullptr) {
2726 sCameraService = cameraService;
2727 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002728 mOpsActive = false;
Igor Murashkin634a5152013-02-20 17:15:11 -08002729 mDestructionStarted = false;
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08002730
2731 // In some cases the calling code has no access to the package it runs under.
2732 // For example, NDK camera API.
2733 // In this case we will get the packages for the calling UID and pick the first one
2734 // for attributing the app op. This will work correctly for runtime permissions
2735 // as for legacy apps we will toggle the app op for all packages in the UID.
2736 // The caveat is that the operation may be attributed to the wrong package and
2737 // stats based on app ops may be slightly off.
2738 if (mClientPackageName.size() <= 0) {
2739 sp<IServiceManager> sm = defaultServiceManager();
2740 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
2741 if (binder == 0) {
2742 ALOGE("Cannot get permission service");
2743 // Leave mClientPackageName unchanged (empty) and the further interaction
2744 // with camera will fail in BasicClient::startCameraOps
2745 return;
2746 }
2747
2748 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
2749 Vector<String16> packages;
2750
2751 permCtrl->getPackagesForUid(mClientUid, packages);
2752
2753 if (packages.isEmpty()) {
2754 ALOGE("No packages for calling UID");
2755 // Leave mClientPackageName unchanged (empty) and the further interaction
2756 // with camera will fail in BasicClient::startCameraOps
2757 return;
2758 }
2759 mClientPackageName = packages[0];
2760 }
Steven Moreland89a2c5c2020-01-31 15:02:25 -08002761 if (getCurrentServingCall() != BinderCallType::HWBINDER) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002762 mAppOpsManager = std::make_unique<AppOpsManager>();
2763 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07002764
2765 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08002766}
2767
2768CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002769 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08002770 mDestructionStarted = true;
2771}
2772
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002773binder::Status CameraService::BasicClient::disconnect() {
2774 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002775 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002776 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07002777 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07002778 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002779
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002780 sCameraService->removeByClient(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002781 sCameraService->logDisconnected(mCameraIdStr, mClientPid, String8(mClientPackageName));
Peter Kalauskasa29c1352018-10-10 12:05:42 -07002782 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
2783 mCameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002784
2785 sp<IBinder> remote = getRemote();
2786 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002787 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08002788 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002789
2790 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07002791 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002792 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
2793 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
2794 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002795
Igor Murashkincba2c162013-03-20 15:56:31 -07002796 // client shouldn't be able to call into us anymore
2797 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002798
2799 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08002800}
2801
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002802status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
2803 // No dumping of clients directly over Binder,
2804 // must go through CameraService::dump
2805 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07002806 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002807 return OK;
2808}
2809
Ruben Brunkcc776712015-02-17 20:18:47 -08002810String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002811 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08002812}
2813
2814
2815int CameraService::BasicClient::getClientPid() const {
2816 return mClientPid;
2817}
2818
Ruben Brunk6267b532015-04-30 17:44:07 -07002819uid_t CameraService::BasicClient::getClientUid() const {
2820 return mClientUid;
2821}
2822
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002823bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
2824 // Defaults to API2.
2825 return level == API_2;
2826}
2827
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002828status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002829 {
2830 Mutex::Autolock l(mAudioRestrictionLock);
2831 mAudioRestriction = mode;
2832 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002833 sCameraService->updateAudioRestriction();
2834 return OK;
2835}
2836
2837int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002838 return sCameraService->updateAudioRestriction();
2839}
2840
2841int32_t CameraService::BasicClient::getAudioRestriction() const {
2842 Mutex::Autolock l(mAudioRestrictionLock);
2843 return mAudioRestriction;
2844}
2845
2846bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
2847 switch (mode) {
2848 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
2849 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
2850 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
2851 return true;
2852 default:
2853 return false;
2854 }
2855}
2856
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002857status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002858 ATRACE_CALL();
2859
Igor Murashkine6800ce2013-03-04 17:25:57 -08002860 {
2861 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002862 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08002863 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002864 if (mAppOpsManager != nullptr) {
2865 // Notify app ops that the camera is not available
2866 mOpsCallback = new OpsCallback(this);
2867 int32_t res;
2868 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
2869 mClientPackageName, mOpsCallback);
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002870 res = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
2871 mClientPackageName, /*startIfModeDefault*/ false, mClientFeatureId,
2872 String16("start camera ") + String16(mCameraIdStr));
Igor Murashkine6800ce2013-03-04 17:25:57 -08002873
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002874 if (res == AppOpsManager::MODE_ERRORED) {
2875 ALOGI("Camera %s: Access for \"%s\" has been revoked",
2876 mCameraIdStr.string(), String8(mClientPackageName).string());
2877 return PERMISSION_DENIED;
2878 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002879
Shuzhen Wang2c656792020-04-13 17:36:49 -07002880 // If the calling Uid is trusted (a native service), the AppOpsManager could
2881 // return MODE_IGNORED. Do not treat such case as error.
2882 if (!mUidIsTrusted && res == AppOpsManager::MODE_IGNORED) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002883 ALOGI("Camera %s: Access for \"%s\" has been restricted",
2884 mCameraIdStr.string(), String8(mClientPackageName).string());
2885 // Return the same error as for device policy manager rejection
2886 return -EACCES;
2887 }
Svetoslav28e8ef72015-05-11 19:21:31 -07002888 }
2889
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002890 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002891
2892 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002893 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002894
Emilian Peev53722fa2019-02-22 17:47:20 -08002895 sCameraService->mUidPolicy->registerMonitorUid(mClientUid);
2896
Shuzhen Wang695044d2020-03-06 09:02:23 -08002897 // Notify listeners of camera open/close status
2898 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
2899
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002900 return OK;
2901}
2902
2903status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002904 ATRACE_CALL();
2905
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002906 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002907 if (mOpsActive) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002908 // Notify app ops that the camera is available again
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002909 if (mAppOpsManager != nullptr) {
2910 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002911 mClientPackageName, mClientFeatureId);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002912 mOpsActive = false;
2913 }
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002914 // This function is called when a client disconnects. This should
2915 // release the camera, but actually only if it was in a proper
2916 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002917 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002918 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002919
Ruben Brunkcc776712015-02-17 20:18:47 -08002920 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002921 sCameraService->updateStatus(StatusInternal::PRESENT,
2922 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002923 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002924 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002925 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
2926 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002927 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002928 mOpsCallback.clear();
2929
Emilian Peev53722fa2019-02-22 17:47:20 -08002930 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid);
2931
Shuzhen Wang695044d2020-03-06 09:02:23 -08002932 // Notify listeners of camera open/close status
2933 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
2934
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002935 return OK;
2936}
2937
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002938void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002939 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002940 if (mAppOpsManager == nullptr) {
2941 return;
2942 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002943 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002944 if (op != AppOpsManager::OP_CAMERA) {
2945 ALOGW("Unexpected app ops notification received: %d", op);
2946 return;
2947 }
2948
2949 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002950 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002951 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002952 ALOGV("checkOp returns: %d, %s ", res,
2953 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
2954 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
2955 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
2956 "UNKNOWN");
2957
Shuzhen Wang64900852021-02-05 09:03:29 -08002958 if (res == AppOpsManager::MODE_ERRORED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002959 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002960 String8(mClientPackageName).string());
Svet Ganova453d0d2018-01-11 15:37:58 -08002961 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08002962 } else if (res == AppOpsManager::MODE_IGNORED) {
2963 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
2964 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d",
2965 mCameraIdStr.string(), String8(mClientPackageName).string(),
2966 mUidIsTrusted, isUidActive);
2967 // If the calling Uid is trusted (a native service), or the client Uid is active (WAR for
2968 // b/175320666), the AppOpsManager could return MODE_IGNORED. Do not treat such cases as
2969 // error.
2970 if (!mUidIsTrusted && !isUidActive) {
2971 block();
2972 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002973 }
2974}
2975
Svet Ganova453d0d2018-01-11 15:37:58 -08002976void CameraService::BasicClient::block() {
2977 ATRACE_CALL();
2978
2979 // Reset the client PID to allow server-initiated disconnect,
2980 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07002981 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08002982 CaptureResultExtras resultExtras; // a dummy result (invalid)
2983 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
2984 disconnect();
2985}
2986
Mathias Agopian65ab4712010-07-14 17:59:35 -07002987// ----------------------------------------------------------------------------
2988
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002989void CameraService::Client::notifyError(int32_t errorCode,
Jianing Weicb0652e2014-03-12 18:29:36 -07002990 const CaptureResultExtras& resultExtras) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002991 (void) resultExtras;
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07002992 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07002993 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
2994 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
2995 api1ErrorCode = CAMERA_ERROR_DISABLED;
2996 }
2997 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07002998 } else {
2999 ALOGE("mRemoteCallback is NULL!!");
3000 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003001}
3002
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003003// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003004binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003005 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003006 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08003007}
3008
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003009bool CameraService::Client::canCastToApiClient(apiLevel level) const {
3010 return level == API_1;
3011}
3012
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003013CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
3014 mClient(client) {
3015}
3016
3017void CameraService::Client::OpsCallback::opChanged(int32_t op,
3018 const String16& packageName) {
3019 sp<BasicClient> client = mClient.promote();
3020 if (client != NULL) {
3021 client->opChanged(op, packageName);
3022 }
3023}
3024
Mathias Agopian65ab4712010-07-14 17:59:35 -07003025// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08003026// UidPolicy
3027// ----------------------------------------------------------------------------
3028
3029void CameraService::UidPolicy::registerSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003030 Mutex::Autolock _l(mUidLock);
3031
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003032 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07003033 status_t res = mAm.linkToDeath(this);
3034 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08003035 | ActivityManager::UID_OBSERVER_IDLE
Emilian Peev53722fa2019-02-22 17:47:20 -08003036 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganova453d0d2018-01-11 15:37:58 -08003037 ActivityManager::PROCESS_STATE_UNKNOWN,
3038 String16("cameraserver"));
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003039 if (res == OK) {
3040 mRegistered = true;
3041 ALOGV("UidPolicy: Registered with ActivityManager");
3042 }
Svet Ganova453d0d2018-01-11 15:37:58 -08003043}
3044
3045void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003046 Mutex::Autolock _l(mUidLock);
3047
Steven Moreland2f348142019-07-02 15:59:07 -07003048 mAm.unregisterUidObserver(this);
3049 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003050 mRegistered = false;
3051 mActiveUids.clear();
3052 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08003053}
3054
3055void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
3056 onUidIdle(uid, disabled);
3057}
3058
3059void CameraService::UidPolicy::onUidActive(uid_t uid) {
3060 Mutex::Autolock _l(mUidLock);
3061 mActiveUids.insert(uid);
3062}
3063
3064void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
3065 bool deleted = false;
3066 {
3067 Mutex::Autolock _l(mUidLock);
3068 if (mActiveUids.erase(uid) > 0) {
3069 deleted = true;
3070 }
3071 }
3072 if (deleted) {
3073 sp<CameraService> service = mService.promote();
3074 if (service != nullptr) {
3075 service->blockClientsForUid(uid);
3076 }
3077 }
3078}
3079
Emilian Peev53722fa2019-02-22 17:47:20 -08003080void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07003081 int64_t procStateSeq __unused, int32_t capability __unused) {
Emilian Peev53722fa2019-02-22 17:47:20 -08003082 bool procStateChange = false;
3083 {
3084 Mutex::Autolock _l(mUidLock);
3085 if ((mMonitoredUids.find(uid) != mMonitoredUids.end()) &&
3086 (mMonitoredUids[uid].first != procState)) {
3087 mMonitoredUids[uid].first = procState;
3088 procStateChange = true;
3089 }
3090 }
3091
3092 if (procStateChange) {
3093 sp<CameraService> service = mService.promote();
3094 if (service != nullptr) {
3095 service->notifyMonitoredUids();
3096 }
3097 }
3098}
3099
3100void CameraService::UidPolicy::registerMonitorUid(uid_t uid) {
3101 Mutex::Autolock _l(mUidLock);
3102 auto it = mMonitoredUids.find(uid);
3103 if (it != mMonitoredUids.end()) {
3104 it->second.second++;
3105 } else {
3106 mMonitoredUids.emplace(
3107 std::pair<uid_t, std::pair<int32_t, size_t>> (uid,
3108 std::pair<int32_t, size_t> (ActivityManager::PROCESS_STATE_NONEXISTENT, 1)));
3109 }
3110}
3111
3112void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid) {
3113 Mutex::Autolock _l(mUidLock);
3114 auto it = mMonitoredUids.find(uid);
3115 if (it != mMonitoredUids.end()) {
3116 it->second.second--;
3117 if (it->second.second == 0) {
3118 mMonitoredUids.erase(it);
3119 }
3120 } else {
3121 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
3122 }
3123}
3124
Svet Ganov7b4ab782018-03-25 12:48:10 -07003125bool CameraService::UidPolicy::isUidActive(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003126 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003127 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003128}
3129
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003130static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
3131static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003132
Svet Ganov7b4ab782018-03-25 12:48:10 -07003133bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003134 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003135 // If activity manager is unreachable, assume everything is active
3136 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003137 return true;
3138 }
3139 auto it = mOverrideUids.find(uid);
3140 if (it != mOverrideUids.end()) {
3141 return it->second;
3142 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003143 bool active = mActiveUids.find(uid) != mActiveUids.end();
3144 if (!active) {
3145 // We want active UIDs to always access camera with their first attempt since
3146 // there is no guarantee the app is robustly written and would retry getting
3147 // the camera on failure. The inverse case is not a problem as we would take
3148 // camera away soon once we get the callback that the uid is no longer active.
3149 ActivityManager am;
3150 // Okay to access with a lock held as UID changes are dispatched without
3151 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07003152 int64_t startTimeMillis = 0;
3153 do {
3154 // TODO: Fix this b/109950150!
3155 // Okay this is a hack. There is a race between the UID turning active and
3156 // activity being resumed. The proper fix is very risky, so we temporary add
3157 // some polling which should happen pretty rarely anyway as the race is hard
3158 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003159 active = mActiveUids.find(uid) != mActiveUids.end();
Hui Yu12c7ec72020-05-04 17:40:52 +00003160 if (!active) active = am.isUidActive(uid, callingPackage);
Svet Ganov94ec46f2018-06-08 15:03:46 -07003161 if (active) {
3162 break;
3163 }
3164 if (startTimeMillis <= 0) {
3165 startTimeMillis = uptimeMillis();
3166 }
3167 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003168 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003169 if (remainingTimeMillis <= 0) {
3170 break;
3171 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003172 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
3173
3174 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003175 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003176 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003177 } while (true);
3178
Svet Ganov7b4ab782018-03-25 12:48:10 -07003179 if (active) {
3180 // Now that we found out the UID is actually active, cache that
3181 mActiveUids.insert(uid);
3182 }
3183 }
3184 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08003185}
3186
Varun Shahb42f1eb2019-04-16 14:45:13 -07003187int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
3188 Mutex::Autolock _l(mUidLock);
3189 return getProcStateLocked(uid);
3190}
3191
3192int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
3193 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
3194 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
3195 procState = mMonitoredUids[uid].first;
3196 }
3197 return procState;
3198}
3199
Svet Ganov7b4ab782018-03-25 12:48:10 -07003200void CameraService::UidPolicy::UidPolicy::addOverrideUid(uid_t uid,
3201 String16 callingPackage, bool active) {
3202 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08003203}
3204
Svet Ganov7b4ab782018-03-25 12:48:10 -07003205void CameraService::UidPolicy::removeOverrideUid(uid_t uid, String16 callingPackage) {
3206 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08003207}
3208
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003209void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
3210 Mutex::Autolock _l(mUidLock);
3211 ALOGV("UidPolicy: ActivityManager has died");
3212 mRegistered = false;
3213 mActiveUids.clear();
3214}
3215
Svet Ganov7b4ab782018-03-25 12:48:10 -07003216void CameraService::UidPolicy::updateOverrideUid(uid_t uid, String16 callingPackage,
3217 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003218 bool wasActive = false;
3219 bool isActive = false;
3220 {
3221 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003222 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003223 mOverrideUids.erase(uid);
3224 if (insert) {
3225 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
3226 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003227 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003228 }
3229 if (wasActive != isActive && !isActive) {
3230 sp<CameraService> service = mService.promote();
3231 if (service != nullptr) {
3232 service->blockClientsForUid(uid);
3233 }
3234 }
3235}
3236
3237// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08003238// SensorPrivacyPolicy
3239// ----------------------------------------------------------------------------
3240void CameraService::SensorPrivacyPolicy::registerSelf() {
3241 Mutex::Autolock _l(mSensorPrivacyLock);
3242 if (mRegistered) {
3243 return;
3244 }
Steven Moreland3cf67172020-01-29 11:44:22 -08003245 mSpm.addSensorPrivacyListener(this);
3246 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
3247 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003248 if (res == OK) {
3249 mRegistered = true;
3250 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
3251 }
3252}
3253
Evan Severson190ad252021-01-07 20:37:15 -08003254status_t CameraService::SensorPrivacyPolicy::registerSelfForIndividual(int userId) {
3255 Mutex::Autolock _l(mSensorPrivacyLock);
3256 if (mRegistered) {
3257 return OK;
3258 }
3259
3260 status_t res = mSpm.addIndividualSensorPrivacyListener(userId,
3261 SensorPrivacyManager::INDIVIDUAL_SENSOR_CAMERA, this);
3262 if (res != OK) {
3263 ALOGE("Unable to register camera privacy listener: %s (%d)", strerror(-res), res);
3264 return res;
3265 }
3266
3267 res = mSpm.isIndividualSensorPrivacyEnabled(userId,
3268 SensorPrivacyManager::INDIVIDUAL_SENSOR_CAMERA, mSensorPrivacyEnabled);
3269 if (res != OK) {
3270 ALOGE("Unable to check camera privacy: %s (%d)", strerror(-res), res);
3271 return res;
3272 }
3273
3274 res = mSpm.linkToDeath(this);
3275 if (res != OK) {
3276 ALOGE("Register link to death failed for sensor privacy: %s (%d)", strerror(-res), res);
3277 return res;
3278 }
3279
3280 mRegistered = true;
Evan Seversondd51a012021-02-03 09:15:21 -08003281 mIsIndividual = true;
3282 mUserId = userId;
Evan Severson190ad252021-01-07 20:37:15 -08003283 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
3284 return OK;
3285}
3286
Michael Grooverd1d435a2018-12-18 17:39:42 -08003287void CameraService::SensorPrivacyPolicy::unregisterSelf() {
3288 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08003289 mSpm.removeSensorPrivacyListener(this);
3290 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003291 mRegistered = false;
3292 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
3293}
3294
3295bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
3296 Mutex::Autolock _l(mSensorPrivacyLock);
3297 return mSensorPrivacyEnabled;
3298}
3299
3300binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
3301 {
3302 Mutex::Autolock _l(mSensorPrivacyLock);
3303 mSensorPrivacyEnabled = enabled;
3304 }
3305 // if sensor privacy is enabled then block all clients from accessing the camera
Evan Severson190ad252021-01-07 20:37:15 -08003306 sp<CameraService> service = mService.promote();
3307 if (service != nullptr) {
Evan Seversondd51a012021-02-03 09:15:21 -08003308 if (mIsIndividual) {
3309 service->setMuteForAllClients(mUserId, enabled);
Evan Severson190ad252021-01-07 20:37:15 -08003310 } else {
3311 if (enabled) {
3312 service->blockAllClients();
3313 }
Michael Grooverd1d435a2018-12-18 17:39:42 -08003314 }
3315 }
3316 return binder::Status::ok();
3317}
3318
3319void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
3320 Mutex::Autolock _l(mSensorPrivacyLock);
3321 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
3322 mRegistered = false;
3323}
3324
3325// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003326// CameraState
3327// ----------------------------------------------------------------------------
3328
3329CameraService::CameraState::CameraState(const String8& id, int cost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003330 const std::set<String8>& conflicting, SystemCameraKind systemCameraKind) : mId(id),
3331 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
3332 mSystemCameraKind(systemCameraKind) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08003333
3334CameraService::CameraState::~CameraState() {}
3335
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003336CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003337 Mutex::Autolock lock(mStatusLock);
3338 return mStatus;
3339}
3340
Shuzhen Wang43858162020-01-10 13:42:15 -08003341std::vector<String8> CameraService::CameraState::getUnavailablePhysicalIds() const {
3342 Mutex::Autolock lock(mStatusLock);
3343 std::vector<String8> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
3344 return res;
3345}
3346
Ruben Brunkcc776712015-02-17 20:18:47 -08003347CameraParameters CameraService::CameraState::getShimParams() const {
3348 return mShimParams;
3349}
3350
3351void CameraService::CameraState::setShimParams(const CameraParameters& params) {
3352 mShimParams = params;
3353}
3354
3355int CameraService::CameraState::getCost() const {
3356 return mCost;
3357}
3358
3359std::set<String8> CameraService::CameraState::getConflicting() const {
3360 return mConflicting;
3361}
3362
3363String8 CameraService::CameraState::getId() const {
3364 return mId;
3365}
3366
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003367SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
3368 return mSystemCameraKind;
3369}
3370
Shuzhen Wang43858162020-01-10 13:42:15 -08003371bool CameraService::CameraState::addUnavailablePhysicalId(const String8& physicalId) {
3372 Mutex::Autolock lock(mStatusLock);
3373 auto result = mUnavailablePhysicalIds.insert(physicalId);
3374 return result.second;
3375}
3376
3377bool CameraService::CameraState::removeUnavailablePhysicalId(const String8& physicalId) {
3378 Mutex::Autolock lock(mStatusLock);
3379 auto count = mUnavailablePhysicalIds.erase(physicalId);
3380 return count > 0;
3381}
3382
Ruben Brunkcc776712015-02-17 20:18:47 -08003383// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07003384// ClientEventListener
3385// ----------------------------------------------------------------------------
3386
3387void CameraService::ClientEventListener::onClientAdded(
3388 const resource_policy::ClientDescriptor<String8,
3389 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003390 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003391 if (basicClient.get() != nullptr) {
3392 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3393 notifier.noteStartCamera(descriptor.getKey(),
3394 static_cast<int>(basicClient->getClientUid()));
3395 }
3396}
3397
3398void CameraService::ClientEventListener::onClientRemoved(
3399 const resource_policy::ClientDescriptor<String8,
3400 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003401 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003402 if (basicClient.get() != nullptr) {
3403 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3404 notifier.noteStopCamera(descriptor.getKey(),
3405 static_cast<int>(basicClient->getClientUid()));
3406 }
3407}
3408
3409
3410// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003411// CameraClientManager
3412// ----------------------------------------------------------------------------
3413
Ruben Brunk99e69712015-05-26 17:25:07 -07003414CameraService::CameraClientManager::CameraClientManager() {
3415 setListener(std::make_shared<ClientEventListener>());
3416}
3417
Ruben Brunkcc776712015-02-17 20:18:47 -08003418CameraService::CameraClientManager::~CameraClientManager() {}
3419
3420sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
3421 const String8& id) const {
3422 auto descriptor = get(id);
3423 if (descriptor == nullptr) {
3424 return sp<BasicClient>{nullptr};
3425 }
3426 return descriptor->getValue();
3427}
3428
3429String8 CameraService::CameraClientManager::toString() const {
3430 auto all = getAll();
3431 String8 ret("[");
3432 bool hasAny = false;
3433 for (auto& i : all) {
3434 hasAny = true;
3435 String8 key = i->getKey();
3436 int32_t cost = i->getCost();
3437 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00003438 int32_t score = i->getPriority().getScore();
3439 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08003440 auto conflicting = i->getConflicting();
3441 auto clientSp = i->getValue();
3442 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07003443 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08003444 if (clientSp.get() != nullptr) {
3445 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07003446 uid_t clientUid = clientSp->getClientUid();
3447 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003448 }
Emilian Peev8131a262017-02-01 12:33:43 +00003449 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
3450 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08003451
Ruben Brunk6267b532015-04-30 17:44:07 -07003452 if (clientSp.get() != nullptr) {
3453 ret.appendFormat("User Id: %d, ", clientUserId);
3454 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003455 if (packageName.size() != 0) {
3456 ret.appendFormat("Client Package Name: %s", packageName.string());
3457 }
3458
3459 ret.append(", Conflicting Client Devices: {");
3460 for (auto& j : conflicting) {
3461 ret.appendFormat("%s, ", j.string());
3462 }
3463 ret.append("})");
3464 }
3465 if (hasAny) ret.append("\n");
3466 ret.append("]\n");
3467 return ret;
3468}
3469
3470CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3471 const String8& key, const sp<BasicClient>& value, int32_t cost,
Emilian Peev8131a262017-02-01 12:33:43 +00003472 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
3473 int32_t state) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003474
Steven Moreland89a2c5c2020-01-31 15:02:25 -08003475 bool isVendorClient = getCurrentServingCall() == BinderCallType::HWBINDER;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003476 int32_t score_adj = isVendorClient ? kVendorClientScore : score;
3477 int32_t state_adj = isVendorClient ? kVendorClientState: state;
3478
Ruben Brunkcc776712015-02-17 20:18:47 -08003479 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003480 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj, isVendorClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08003481}
3482
3483CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3484 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
3485 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00003486 partial->getConflicting(), partial->getPriority().getScore(),
3487 partial->getOwnerId(), partial->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08003488}
3489
3490// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07003491
3492static const int kDumpLockRetries = 50;
3493static const int kDumpLockSleep = 60000;
3494
3495static bool tryLock(Mutex& mutex)
3496{
3497 bool locked = false;
3498 for (int i = 0; i < kDumpLockRetries; ++i) {
3499 if (mutex.tryLock() == NO_ERROR) {
3500 locked = true;
3501 break;
3502 }
3503 usleep(kDumpLockSleep);
3504 }
3505 return locked;
3506}
3507
3508status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003509 ATRACE_CALL();
3510
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003511 if (checkCallingPermission(sDumpPermission) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003512 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07003513 CameraThreadState::getCallingPid(),
3514 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003515 return NO_ERROR;
3516 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003517 bool locked = tryLock(mServiceLock);
3518 // failed to lock - CameraService is probably deadlocked
3519 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003520 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003521 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003522
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003523 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003524 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07003525
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003526 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003527 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08003528
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003529 if (locked) mServiceLock.unlock();
3530 return NO_ERROR;
3531 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003532 dprintf(fd, "\n== Service global info: ==\n\n");
3533 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003534 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07003535 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
3536 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003537 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
3538 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
3539 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003540 String8 activeClientString = mActiveClientManager.toString();
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003541 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
3542 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003543
3544 dumpEventLog(fd);
3545
3546 bool stateLocked = tryLock(mCameraStatesLock);
3547 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003548 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003549 }
3550
Emilian Peevbd8c5032018-02-14 23:05:40 +00003551 int argSize = args.size();
3552 for (int i = 0; i < argSize; i++) {
3553 if (args[i] == TagMonitor::kMonitorOption) {
3554 if (i + 1 < argSize) {
3555 mMonitorTags = String8(args[i + 1]);
3556 }
3557 break;
3558 }
3559 }
3560
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003561 for (auto& state : mCameraStates) {
3562 String8 cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003563
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003564 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003565
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003566 CameraParameters p = state.second->getShimParams();
3567 if (!p.isEmpty()) {
3568 dprintf(fd, " Camera1 API shim is using parameters:\n ");
3569 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003570 }
3571
3572 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08003573 if (clientDescriptor != nullptr) {
3574 dprintf(fd, " Device %s is open. Client instance dump:\n",
3575 cameraId.string());
3576 dprintf(fd, " Client priority score: %d state: %d\n",
3577 clientDescriptor->getPriority().getScore(),
3578 clientDescriptor->getPriority().getState());
3579 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
3580
3581 auto client = clientDescriptor->getValue();
3582 dprintf(fd, " Client package: %s\n",
3583 String8(client->getPackageName()).string());
3584
3585 client->dumpClient(fd, args);
3586 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003587 dprintf(fd, " Device %s is closed, no client instance\n",
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003588 cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003589 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003590
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003591 }
3592
3593 if (stateLocked) mCameraStatesLock.unlock();
3594
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003595 if (locked) mServiceLock.unlock();
3596
Emilian Peevf53f66e2017-04-11 14:29:43 +01003597 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003598
3599 dprintf(fd, "\n== Vendor tags: ==\n\n");
3600
3601 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
3602 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00003603 sp<VendorTagDescriptorCache> cache =
3604 VendorTagDescriptorCache::getGlobalVendorTagCache();
3605 if (cache == NULL) {
3606 dprintf(fd, "No vendor tags.\n");
3607 } else {
3608 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
3609 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003610 } else {
3611 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
3612 }
3613
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003614 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003615 dprintf(fd, "\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003616 camera3::CameraTraces::dump(fd, args);
3617
3618 // Process dump arguments, if any
3619 int n = args.size();
3620 String16 verboseOption("-v");
3621 String16 unreachableOption("--unreachable");
3622 for (int i = 0; i < n; i++) {
3623 if (args[i] == verboseOption) {
3624 // change logging level
3625 if (i + 1 >= n) continue;
3626 String8 levelStr(args[i+1]);
3627 int level = atoi(levelStr.string());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003628 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003629 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003630 } else if (args[i] == unreachableOption) {
3631 // Dump memory analysis
3632 // TODO - should limit be an argument parameter?
3633 UnreachableMemoryInfo info;
3634 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
3635 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003636 dprintf(fd, "\n== Unable to dump unreachable memory. "
3637 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003638 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003639 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003640 std::string s = info.ToString(/*log_contents*/ true);
3641 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003642 }
3643 }
3644 }
3645 return NO_ERROR;
3646}
3647
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003648void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003649 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003650
3651 Mutex::Autolock l(mLogLock);
3652 for (const auto& msg : mEventLog) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003653 dprintf(fd, " %s\n", msg.string());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003654 }
3655
3656 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003657 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003658 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003659 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003660 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003661 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003662}
3663
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003664void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003665 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003666 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
3667 if (mTorchClientMap[i] == who) {
3668 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003669 String8 cameraId = mTorchClientMap.keyAt(i);
3670 status_t res = mFlashlight->setTorchMode(cameraId, false);
3671 if (res) {
3672 ALOGE("%s: torch client died but couldn't turn off torch: "
3673 "%s (%d)", __FUNCTION__, strerror(-res), res);
3674 return;
3675 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003676 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003677 break;
3678 }
3679 }
3680}
3681
Ruben Brunkcc776712015-02-17 20:18:47 -08003682/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003683
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003684 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07003685 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
3686 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003687 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003688 // PID here is approximate and can be wrong.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003689 logClientDied(CameraThreadState::getCallingPid(), String8("Binder died unexpectedly"));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003690
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003691 // check torch client
3692 handleTorchClientBinderDied(who);
3693
3694 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08003695 if(!evictClientIdByRemote(who)) {
3696 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003697 return;
3698 }
3699
Ruben Brunkcc776712015-02-17 20:18:47 -08003700 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
3701 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003702}
3703
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003704void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003705 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08003706}
3707
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003708void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
3709 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003710 // Do not lock mServiceLock here or can get into a deadlock from
3711 // connect() -> disconnect -> updateStatus
3712
3713 auto state = getCameraState(cameraId);
3714
3715 if (state == nullptr) {
3716 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
3717 cameraId.string());
3718 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07003719 }
3720
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003721 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
3722 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3723 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3724 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
3725 return;
3726 }
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003727 bool supportsHAL3 = false;
3728 // supportsCameraApi also holds mInterfaceMutex, we can't call it in the
3729 // HIDL onStatusChanged wrapper call (we'll hold mStatusListenerLock and
3730 // mInterfaceMutex together, which can lead to deadlocks)
3731 binder::Status sRet =
3732 supportsCameraApi(String16(cameraId), hardware::ICameraService::API_VERSION_2,
3733 &supportsHAL3);
3734 if (!sRet.isOk()) {
3735 ALOGW("%s: Failed to determine if device supports HAL3 %s, supportsCameraApi call failed",
3736 __FUNCTION__, cameraId.string());
3737 return;
3738 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003739
3740 // Collect the logical cameras without holding mStatusLock in updateStatus
3741 // as that can lead to a deadlock(b/162192331).
3742 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08003743 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08003744 // of the listeners with both the mStatusLock and mStatusListenerLock held
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003745 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind, &supportsHAL3,
3746 &logicalCameraIds]
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003747 (const String8& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003748
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003749 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003750 // Update torch status if it has a flash unit.
3751 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003752 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003753 if (getTorchStatusLocked(cameraId, &torchStatus) !=
3754 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003755 TorchModeStatus newTorchStatus =
3756 status == StatusInternal::PRESENT ?
3757 TorchModeStatus::AVAILABLE_OFF :
3758 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003759 if (torchStatus != newTorchStatus) {
3760 onTorchStatusChangedLocked(cameraId, newTorchStatus);
3761 }
3762 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003763 }
3764
3765 Mutex::Autolock lock(mStatusListenerLock);
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003766 notifyPhysicalCameraStatusLocked(mapToInterface(status), String16(cameraId),
3767 logicalCameraIds, deviceKind);
Shuzhen Wang43858162020-01-10 13:42:15 -08003768
Ruben Brunkcc776712015-02-17 20:18:47 -08003769 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003770 bool isVendorListener = listener->isVendorListener();
3771 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
3772 listener->getListenerPid(), listener->getListenerUid()) ||
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07003773 (isVendorListener && !supportsHAL3)) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003774 ALOGV("Skipping discovery callback for system-only camera/HAL1 device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003775 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003776 continue;
3777 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003778 listener->getListener()->onStatusChanged(mapToInterface(status),
Emilian Peev53722fa2019-02-22 17:47:20 -08003779 String16(cameraId));
Ruben Brunkcc776712015-02-17 20:18:47 -08003780 }
3781 });
Igor Murashkincba2c162013-03-20 15:56:31 -07003782}
3783
Shuzhen Wang695044d2020-03-06 09:02:23 -08003784void CameraService::updateOpenCloseStatus(const String8& cameraId, bool open,
3785 const String16& clientPackageName) {
3786 Mutex::Autolock lock(mStatusListenerLock);
3787
3788 for (const auto& it : mListenerList) {
3789 if (!it->isOpenCloseCallbackAllowed()) {
3790 continue;
3791 }
3792
3793 binder::Status ret;
3794 String16 cameraId64(cameraId);
3795 if (open) {
3796 ret = it->getListener()->onCameraOpened(cameraId64, clientPackageName);
3797 } else {
3798 ret = it->getListener()->onCameraClosed(cameraId64);
3799 }
3800 if (!ret.isOk()) {
3801 ALOGE("%s: Failed to trigger onCameraOpened/onCameraClosed callback: %d", __FUNCTION__,
3802 ret.exceptionCode());
3803 }
3804 }
3805}
3806
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003807template<class Func>
3808void CameraService::CameraState::updateStatus(StatusInternal status,
3809 const String8& cameraId,
3810 std::initializer_list<StatusInternal> rejectSourceStates,
3811 Func onStatusUpdatedLocked) {
3812 Mutex::Autolock lock(mStatusLock);
3813 StatusInternal oldStatus = mStatus;
3814 mStatus = status;
3815
3816 if (oldStatus == status) {
3817 return;
3818 }
3819
3820 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
3821 cameraId.string(), oldStatus, status);
3822
3823 if (oldStatus == StatusInternal::NOT_PRESENT &&
3824 (status != StatusInternal::PRESENT &&
3825 status != StatusInternal::ENUMERATING)) {
3826
3827 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
3828 __FUNCTION__);
3829 mStatus = oldStatus;
3830 return;
3831 }
3832
3833 /**
3834 * Sometimes we want to conditionally do a transition.
3835 * For example if a client disconnects, we want to go to PRESENT
3836 * only if we weren't already in NOT_PRESENT or ENUMERATING.
3837 */
3838 for (auto& rejectStatus : rejectSourceStates) {
3839 if (oldStatus == rejectStatus) {
3840 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
3841 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
3842 mStatus = oldStatus;
3843 return;
3844 }
3845 }
3846
3847 onStatusUpdatedLocked(cameraId, status);
3848}
3849
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003850status_t CameraService::getTorchStatusLocked(
3851 const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003852 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003853 if (!status) {
3854 return BAD_VALUE;
3855 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003856 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3857 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003858 // invalid camera ID or the camera doesn't have a flash unit
3859 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003860 }
3861
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003862 *status = mTorchStatusMap.valueAt(index);
3863 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003864}
3865
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003866status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003867 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003868 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3869 if (index == NAME_NOT_FOUND) {
3870 return BAD_VALUE;
3871 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003872 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003873
3874 return OK;
3875}
3876
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003877std::list<String16> CameraService::getLogicalCameras(
3878 const String8& physicalCameraId) {
3879 std::list<String16> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08003880 Mutex::Autolock lock(mCameraStatesLock);
3881 for (const auto& state : mCameraStates) {
3882 std::vector<std::string> physicalCameraIds;
3883 if (!mCameraProviderManager->isLogicalCamera(state.first.c_str(), &physicalCameraIds)) {
3884 // This is not a logical multi-camera.
3885 continue;
3886 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003887 if (std::find(physicalCameraIds.begin(), physicalCameraIds.end(), physicalCameraId.c_str())
Shuzhen Wang43858162020-01-10 13:42:15 -08003888 == physicalCameraIds.end()) {
3889 // cameraId is not a physical camera of this logical multi-camera.
3890 continue;
3891 }
3892
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003893 retList.emplace_back(String16(state.first));
3894 }
3895 return retList;
3896}
3897
3898void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
3899 const String16& physicalCameraId, const std::list<String16>& logicalCameraIds,
3900 SystemCameraKind deviceKind) {
3901 // mStatusListenerLock is expected to be locked
3902 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08003903 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003904 // Note: we check only the deviceKind of the physical camera id
3905 // since, logical camera ids and their physical camera ids are
3906 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07003907 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
3908 listener->getListenerPid(), listener->getListenerUid())) {
3909 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003910 String8(physicalCameraId).c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07003911 continue;
3912 }
Shuzhen Wang43858162020-01-10 13:42:15 -08003913 listener->getListener()->onPhysicalCameraStatusChanged(status,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003914 logicalCameraId, physicalCameraId);
Shuzhen Wang43858162020-01-10 13:42:15 -08003915 }
3916 }
3917}
3918
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003919
Svet Ganova453d0d2018-01-11 15:37:58 -08003920void CameraService::blockClientsForUid(uid_t uid) {
3921 const auto clients = mActiveClientManager.getAll();
3922 for (auto& current : clients) {
3923 if (current != nullptr) {
3924 const auto basicClient = current->getValue();
3925 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
3926 basicClient->block();
3927 }
3928 }
3929 }
3930}
3931
Michael Grooverd1d435a2018-12-18 17:39:42 -08003932void CameraService::blockAllClients() {
3933 const auto clients = mActiveClientManager.getAll();
3934 for (auto& current : clients) {
3935 if (current != nullptr) {
3936 const auto basicClient = current->getValue();
3937 if (basicClient.get() != nullptr) {
3938 basicClient->block();
3939 }
3940 }
3941 }
3942}
3943
Evan Severson190ad252021-01-07 20:37:15 -08003944void CameraService::setMuteForAllClients(userid_t userId, bool enabled) {
3945 const auto clients = mActiveClientManager.getAll();
3946 for (auto& current : clients) {
3947 if (current != nullptr) {
3948 const auto basicClient = current->getValue();
3949 if (basicClient.get() != nullptr
3950 && multiuser_get_user_id(basicClient->getClientUid()) == userId) {
3951 basicClient->setCameraMute(enabled);
3952 }
3953 }
3954 }
3955}
3956
Svet Ganova453d0d2018-01-11 15:37:58 -08003957// NOTE: This is a remote API - make sure all args are validated
3958status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
3959 if (!checkCallingPermission(sManageCameraPermission, nullptr, nullptr)) {
3960 return PERMISSION_DENIED;
3961 }
3962 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
3963 return BAD_VALUE;
3964 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003965 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003966 return handleSetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07003967 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003968 return handleResetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07003969 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003970 return handleGetUidState(args, out, err);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003971 } else if (args.size() >= 2 && args[0] == String16("set-rotate-and-crop")) {
3972 return handleSetRotateAndCrop(args);
3973 } else if (args.size() >= 1 && args[0] == String16("get-rotate-and-crop")) {
3974 return handleGetRotateAndCrop(out);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08003975 } else if (args.size() >= 2 && args[0] == String16("set-image-dump-mask")) {
3976 return handleSetImageDumpMask(args);
3977 } else if (args.size() >= 1 && args[0] == String16("get-image-dump-mask")) {
3978 return handleGetImageDumpMask(out);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003979 } else if (args.size() >= 2 && args[0] == String16("set-camera-mute")) {
3980 return handleSetCameraMute(args);
Svet Ganova453d0d2018-01-11 15:37:58 -08003981 } else if (args.size() == 1 && args[0] == String16("help")) {
3982 printHelp(out);
3983 return NO_ERROR;
3984 }
3985 printHelp(err);
3986 return BAD_VALUE;
3987}
3988
3989status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07003990 String16 packageName = args[1];
3991
Svet Ganova453d0d2018-01-11 15:37:58 -08003992 bool active = false;
3993 if (args[2] == String16("active")) {
3994 active = true;
3995 } else if ((args[2] != String16("idle"))) {
3996 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
3997 return BAD_VALUE;
3998 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003999
4000 int userId = 0;
4001 if (args.size() >= 5 && args[3] == String16("--user")) {
4002 userId = atoi(String8(args[4]));
4003 }
4004
4005 uid_t uid;
4006 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
4007 return BAD_VALUE;
4008 }
4009
4010 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08004011 return NO_ERROR;
4012}
4013
4014status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004015 String16 packageName = args[1];
4016
4017 int userId = 0;
4018 if (args.size() >= 4 && args[2] == String16("--user")) {
4019 userId = atoi(String8(args[3]));
4020 }
4021
4022 uid_t uid;
4023 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004024 return BAD_VALUE;
4025 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004026
4027 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08004028 return NO_ERROR;
4029}
4030
4031status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004032 String16 packageName = args[1];
4033
4034 int userId = 0;
4035 if (args.size() >= 4 && args[2] == String16("--user")) {
4036 userId = atoi(String8(args[3]));
4037 }
4038
4039 uid_t uid;
4040 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004041 return BAD_VALUE;
4042 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004043
4044 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004045 return dprintf(out, "active\n");
4046 } else {
4047 return dprintf(out, "idle\n");
4048 }
4049}
4050
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004051status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
4052 int rotateValue = atoi(String8(args[1]));
4053 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
4054 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
4055 Mutex::Autolock lock(mServiceLock);
4056
4057 mOverrideRotateAndCropMode = rotateValue;
4058
4059 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
4060
4061 const auto clients = mActiveClientManager.getAll();
4062 for (auto& current : clients) {
4063 if (current != nullptr) {
4064 const auto basicClient = current->getValue();
4065 if (basicClient.get() != nullptr) {
4066 basicClient->setRotateAndCropOverride(rotateValue);
4067 }
4068 }
4069 }
4070
4071 return OK;
4072}
4073
4074status_t CameraService::handleGetRotateAndCrop(int out) {
4075 Mutex::Autolock lock(mServiceLock);
4076
4077 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
4078}
4079
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004080status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
4081 char *endPtr;
4082 errno = 0;
4083 String8 maskString8 = String8(args[1]);
4084 long maskValue = strtol(maskString8.c_str(), &endPtr, 10);
4085
4086 if (errno != 0) return BAD_VALUE;
4087 if (endPtr != maskString8.c_str() + maskString8.size()) return BAD_VALUE;
4088 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
4089
4090 Mutex::Autolock lock(mServiceLock);
4091
4092 mImageDumpMask = maskValue;
4093
4094 return OK;
4095}
4096
4097status_t CameraService::handleGetImageDumpMask(int out) {
4098 Mutex::Autolock lock(mServiceLock);
4099
4100 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
4101}
4102
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004103status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
4104 int muteValue = strtol(String8(args[1]), nullptr, 10);
4105 if (errno != 0) return BAD_VALUE;
4106
4107 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
4108 Mutex::Autolock lock(mServiceLock);
4109
4110 mOverrideCameraMuteMode = (muteValue == 1);
4111
4112 const auto clients = mActiveClientManager.getAll();
4113 for (auto& current : clients) {
4114 if (current != nullptr) {
4115 const auto basicClient = current->getValue();
4116 if (basicClient.get() != nullptr) {
4117 if (basicClient->supportsCameraMute()) {
4118 basicClient->setCameraMute(mOverrideCameraMuteMode);
4119 }
4120 }
4121 }
4122 }
4123
4124 return OK;
4125}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004126
Svet Ganova453d0d2018-01-11 15:37:58 -08004127status_t CameraService::printHelp(int out) {
4128 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07004129 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
4130 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
4131 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004132 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
4133 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
4134 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004135 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
4136 " Valid values 0=OFF, 1=ON for JPEG\n"
4137 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004138 " set-camera-mute <0/1> enable or disable camera muting\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08004139 " help print this message\n");
4140}
4141
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004142int32_t CameraService::updateAudioRestriction() {
4143 Mutex::Autolock lock(mServiceLock);
4144 return updateAudioRestrictionLocked();
4145}
4146
4147int32_t CameraService::updateAudioRestrictionLocked() {
4148 int32_t mode = 0;
4149 // iterate through all active client
4150 for (const auto& i : mActiveClientManager.getAll()) {
4151 const auto clientSp = i->getValue();
4152 mode |= clientSp->getAudioRestriction();
4153 }
4154
4155 bool modeChanged = (mAudioRestriction != mode);
4156 mAudioRestriction = mode;
4157 if (modeChanged) {
4158 mAppOps.setCameraAudioRestriction(mode);
4159 }
4160 return mode;
4161}
4162
Evan Severson190ad252021-01-07 20:37:15 -08004163bool CameraService::isUserSensorPrivacyEnabledForUid(uid_t uid) {
4164 userid_t userId = multiuser_get_user_id(uid);
4165 if (mCameraSensorPrivacyPolicies.find(userId) == mCameraSensorPrivacyPolicies.end()) {
4166 sp<SensorPrivacyPolicy> userPolicy = new SensorPrivacyPolicy(this);
4167 if (userPolicy->registerSelfForIndividual(userId) != OK) {
4168 return false;
4169 }
4170 mCameraSensorPrivacyPolicies[userId] = userPolicy;
4171 }
4172 return mCameraSensorPrivacyPolicies[userId]->isSensorPrivacyEnabled();
4173}
4174
Mathias Agopian65ab4712010-07-14 17:59:35 -07004175}; // namespace android