blob: 88a1ab66b467f5b55d4a46ecc34250fd4d36ffa0 [file] [log] [blame]
Mathias Agopian65ab4712010-07-14 17:59:35 -07001/*
Ruben Brunkd1176ef2014-02-21 10:51:38 -08002 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Mathias Agopian65ab4712010-07-14 17:59:35 -070016
17#define LOG_TAG "CameraService"
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -070018#define ATRACE_TAG ATRACE_TAG_CAMERA
Iliyan Malchev8951a972011-04-14 16:55:59 -070019//#define LOG_NDEBUG 0
Mathias Agopian65ab4712010-07-14 17:59:35 -070020
Ruben Brunkcc776712015-02-17 20:18:47 -080021#include <algorithm>
22#include <climits>
Mathias Agopian65ab4712010-07-14 17:59:35 -070023#include <stdio.h>
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -080024#include <cstdlib>
Ruben Brunkcc776712015-02-17 20:18:47 -080025#include <cstring>
26#include <ctime>
27#include <string>
Mathias Agopian65ab4712010-07-14 17:59:35 -070028#include <sys/types.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080029#include <inttypes.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070030#include <pthread.h>
31
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080032#include <android/hardware/ICamera.h>
33#include <android/hardware/ICameraClient.h>
34
Alex Deymo9c2a2c22016-08-25 11:59:14 -070035#include <android-base/macros.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080036#include <android-base/parseint.h>
Jayant Chowdharyb61526c2019-05-13 19:37:42 -070037#include <android-base/stringprintf.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080038#include <binder/ActivityManager.h>
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -080039#include <binder/AppOpsManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070040#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070041#include <binder/MemoryBase.h>
42#include <binder/MemoryHeapBase.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080043#include <binder/PermissionController.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080044#include <binder/IResultReceiver.h>
Steven Moreland89a2c5c2020-01-31 15:02:25 -080045#include <binderthreadstate/CallerUtils.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070046#include <cutils/atomic.h>
Nipun Kwatrab5ca4612010-09-11 19:31:10 -070047#include <cutils/properties.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080048#include <cutils/misc.h>
Mathias Agopiandf712ea2012-02-25 18:48:35 -080049#include <gui/Surface.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070050#include <hardware/hardware.h>
Jayant Chowdharybe543d42018-08-15 13:16:14 -070051#include "hidl/HidlCameraService.h"
52#include <hidl/HidlTransportSupport.h>
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -080053#include <hwbinder/IPCThreadState.h>
Eino-Ville Talvalad89821e2016-04-20 11:23:50 -070054#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070055#include <media/AudioSystem.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080056#include <media/IMediaHTTPService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070057#include <media/mediaplayer.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070058#include <mediautils/BatteryNotifier.h>
Steven Moreland886d7322021-04-02 04:19:45 +000059#include <processinfo/ProcessInfoService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070060#include <utils/Errors.h>
61#include <utils/Log.h>
62#include <utils/String16.h>
Svet Ganov94ec46f2018-06-08 15:03:46 -070063#include <utils/SystemClock.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080064#include <utils/Trace.h>
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080065#include <utils/CallStack.h>
Chien-Yu Chen98a668f2015-12-18 14:10:33 -080066#include <private/android_filesystem_config.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080067#include <system/camera_vendor_tags.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070068#include <system/camera_metadata.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080069
Ruben Brunkb2119af2014-05-09 19:57:56 -070070#include <system/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070071
72#include "CameraService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070073#include "api1/Camera2Client.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070074#include "api2/CameraDeviceClient.h"
Igor Murashkinff3e31d2013-10-23 16:40:06 -070075#include "utils/CameraTraces.h"
Emilian Peevbd8c5032018-02-14 23:05:40 +000076#include "utils/TagMonitor.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070077#include "utils/CameraThreadState.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070078#include "utils/CameraServiceProxyWrapper.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070079
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080080namespace {
81 const char* kPermissionServiceName = "permission";
82}; // namespace anonymous
83
Mathias Agopian65ab4712010-07-14 17:59:35 -070084namespace android {
85
Jayant Chowdharyb61526c2019-05-13 19:37:42 -070086using base::StringPrintf;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080087using binder::Status;
Jayant Chowdharybe543d42018-08-15 13:16:14 -070088using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -080089using hardware::ICamera;
90using hardware::ICameraClient;
91using hardware::ICameraServiceListener;
92using hardware::camera::common::V1_0::CameraDeviceStatus;
93using hardware::camera::common::V1_0::TorchModeStatus;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080094using hardware::camera2::utils::CameraIdAndSessionConfiguration;
95using hardware::camera2::utils::ConcurrentCameraIdCombination;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080096
Mathias Agopian65ab4712010-07-14 17:59:35 -070097// ----------------------------------------------------------------------------
98// Logging support -- this is for debugging only
99// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700100volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700101
Steve Blockb8a80522011-12-20 16:23:08 +0000102#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
103#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700104
105static void setLogLevel(int level) {
106 android_atomic_write(level, &gLogLevel);
107}
108
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800109// Convenience methods for constructing binder::Status objects for error returns
110
111#define STATUS_ERROR(errorCode, errorString) \
112 binder::Status::fromServiceSpecificError(errorCode, \
113 String8::format("%s:%d: %s", __FUNCTION__, __LINE__, errorString))
114
115#define STATUS_ERROR_FMT(errorCode, errorString, ...) \
116 binder::Status::fromServiceSpecificError(errorCode, \
117 String8::format("%s:%d: " errorString, __FUNCTION__, __LINE__, \
118 __VA_ARGS__))
119
Mathias Agopian65ab4712010-07-14 17:59:35 -0700120// ----------------------------------------------------------------------------
121
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700122static const String16 sDumpPermission("android.permission.DUMP");
Svet Ganova453d0d2018-01-11 15:37:58 -0800123static const String16 sManageCameraPermission("android.permission.MANAGE_CAMERA");
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700124static const String16 sCameraPermission("android.permission.CAMERA");
125static const String16 sSystemCameraPermission("android.permission.SYSTEM_CAMERA");
126static const String16
127 sCameraSendSystemEventsPermission("android.permission.CAMERA_SEND_SYSTEM_EVENTS");
Shuzhen Wang695044d2020-03-06 09:02:23 -0800128static const String16 sCameraOpenCloseListenerPermission(
129 "android.permission.CAMERA_OPEN_CLOSE_LISTENER");
Svet Ganova453d0d2018-01-11 15:37:58 -0800130
Eino-Ville Talvala7c602c32021-03-20 17:00:18 -0700131static constexpr int32_t kVendorClientScore = resource_policy::PERCEPTIBLE_APP_ADJ;
132static constexpr int32_t kVendorClientState = ActivityManager::PROCESS_STATE_PERSISTENT_UI;
133
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800134const String8 CameraService::kOfflineDevice("offline-");
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700135
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800136CameraService::CameraService() :
137 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800138 mNumberOfCameras(0),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700139 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700140 mSoundRef(0), mInitialized(false),
141 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000142 ALOGI("CameraService started (pid=%d)", getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800143 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700144}
145
Iliyan Malchev8951a972011-04-14 16:55:59 -0700146void CameraService::onFirstRef()
147{
Ruben Brunkcc776712015-02-17 20:18:47 -0800148 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800149
Iliyan Malchev8951a972011-04-14 16:55:59 -0700150 BnCameraService::onFirstRef();
151
Ruben Brunk99e69712015-05-26 17:25:07 -0700152 // Update battery life tracking if service is restarting
153 BatteryNotifier& notifier(BatteryNotifier::getInstance());
154 notifier.noteResetCamera();
155 notifier.noteResetFlashlight();
156
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800157 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800158
Emilian Peevf53f66e2017-04-11 14:29:43 +0100159 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800160 if (res == OK) {
161 mInitialized = true;
162 }
163
Svet Ganova453d0d2018-01-11 15:37:58 -0800164 mUidPolicy = new UidPolicy(this);
165 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800166 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
167 mSensorPrivacyPolicy->registerSelf();
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700168 mAppOps.setCameraAudioRestriction(mAudioRestriction);
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700169 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
170 if (hcs->registerAsService() != android::OK) {
171 ALOGE("%s: Failed to register default android.frameworks.cameraservice.service@1.0",
172 __FUNCTION__);
173 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700174
175 // This needs to be last call in this function, so that it's as close to
176 // ServiceManager::addService() as possible.
Shuzhen Wang316781a2020-08-18 18:11:01 -0700177 CameraServiceProxyWrapper::pingCameraServiceProxy();
Shuzhen Wang24b44152019-09-20 10:38:11 -0700178 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800179}
180
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800181status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800182 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100183
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800184 std::vector<std::string> deviceIds;
185 {
186 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800187
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800188 if (nullptr == mCameraProviderManager.get()) {
189 mCameraProviderManager = new CameraProviderManager();
190 res = mCameraProviderManager->initialize(this);
191 if (res != OK) {
192 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
193 __FUNCTION__, strerror(-res), res);
194 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100195 }
196 }
197
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800198
199 // Setup vendor tags before we call get_camera_info the first time
200 // because HAL might need to setup static vendor keys in get_camera_info
201 // TODO: maybe put this into CameraProviderManager::initialize()?
202 mCameraProviderManager->setUpVendorTags();
203
204 if (nullptr == mFlashlight.get()) {
205 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700206 }
207
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800208 res = mFlashlight->findFlashUnits();
209 if (res != OK) {
210 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
211 }
212
213 deviceIds = mCameraProviderManager->getCameraDeviceIds();
214 }
215
216
217 for (auto& cameraId : deviceIds) {
218 String8 id8 = String8(cameraId.c_str());
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800219 if (getCameraState(id8) == nullptr) {
220 onDeviceStatusChanged(id8, CameraDeviceStatus::PRESENT);
221 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800222 }
223
224 return OK;
225}
226
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700227void CameraService::broadcastTorchModeStatus(const String8& cameraId, TorchModeStatus status,
228 SystemCameraKind systemCameraKind) {
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800229 Mutex::Autolock lock(mStatusListenerLock);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800230 for (auto& i : mListenerList) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700231 if (shouldSkipStatusUpdates(systemCameraKind, i->isVendorListener(), i->getListenerPid(),
232 i->getListenerUid())) {
233 ALOGV("Skipping torch callback for system-only camera device %s",
234 cameraId.c_str());
235 continue;
236 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700237 i->getListener()->onTorchStatusChanged(mapToInterface(status), String16{cameraId});
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800238 }
239}
240
Mathias Agopian65ab4712010-07-14 17:59:35 -0700241CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800242 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800243 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800244 mSensorPrivacyPolicy->unregisterSelf();
Evan Severson190ad252021-01-07 20:37:15 -0800245
246 for (auto const& [_, policy] : mCameraSensorPrivacyPolicies) {
247 policy->unregisterSelf();
248 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700249}
250
Emilian Peevaee727d2017-05-04 16:35:48 +0100251void CameraService::onNewProviderRegistered() {
252 enumerateProviders();
253}
254
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700255void CameraService::filterAPI1SystemCameraLocked(
256 const std::vector<std::string> &normalDeviceIds) {
257 mNormalDeviceIdsWithoutSystemCamera.clear();
258 for (auto &deviceId : normalDeviceIds) {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700259 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
260 if (getSystemCameraKind(String8(deviceId.c_str()), &deviceKind) != OK) {
261 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, deviceId.c_str());
262 continue;
263 }
264 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700265 // All system camera ids will necessarily come after public camera
266 // device ids as per the HAL interface contract.
267 break;
268 }
269 mNormalDeviceIdsWithoutSystemCamera.push_back(deviceId);
270 }
271 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
272 mNormalDeviceIdsWithoutSystemCamera.size());
273}
274
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700275status_t CameraService::getSystemCameraKind(const String8& cameraId, SystemCameraKind *kind) const {
276 auto state = getCameraState(cameraId);
277 if (state != nullptr) {
278 *kind = state->getSystemCameraKind();
279 return OK;
280 }
281 // Hidden physical camera ids won't have CameraState
282 return mCameraProviderManager->getSystemCameraKind(cameraId.c_str(), kind);
283}
284
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800285void CameraService::updateCameraNumAndIds() {
286 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700287 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
288 // Excludes hidden secure cameras
289 mNumberOfCameras =
290 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
291 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800292 mNormalDeviceIds =
293 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700294 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800295}
296
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100297void CameraService::addStates(const String8 id) {
298 std::string cameraId(id.c_str());
299 hardware::camera::common::V1_0::CameraResourceCost cost;
300 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700301 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100302 if (res != OK) {
303 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
304 return;
305 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700306 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
307 if (res != OK) {
308 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
309 return;
310 }
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100311 std::set<String8> conflicting;
312 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
313 conflicting.emplace(String8(cost.conflictingDevices[i].c_str()));
314 }
315
316 {
317 Mutex::Autolock lock(mCameraStatesLock);
318 mCameraStates.emplace(id, std::make_shared<CameraState>(id, cost.resourceCost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700319 conflicting, deviceKind));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100320 }
321
322 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100323 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100324 mTorchStatusMap.add(id, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800325
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700326 broadcastTorchModeStatus(id, TorchModeStatus::AVAILABLE_OFF, deviceKind);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100327 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800328
329 updateCameraNumAndIds();
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100330 logDeviceAdded(id, "Device added");
331}
332
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100333void CameraService::removeStates(const String8 id) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800334 updateCameraNumAndIds();
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100335 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100336 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100337 mTorchStatusMap.removeItem(id);
338 }
339
340 {
341 Mutex::Autolock lock(mCameraStatesLock);
342 mCameraStates.erase(id);
343 }
344}
345
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800346void CameraService::onDeviceStatusChanged(const String8& id,
347 CameraDeviceStatus newHalStatus) {
348 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
349 id.string(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700350
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800351 StatusInternal newStatus = mapToInternal(newHalStatus);
352
Ruben Brunkcc776712015-02-17 20:18:47 -0800353 std::shared_ptr<CameraState> state = getCameraState(id);
354
355 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700356 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100357 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700358 __FUNCTION__, id.string());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100359
360 // First add as absent to make sure clients are notified below
361 addStates(id);
362
363 updateStatus(newStatus, id);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700364 } else {
365 ALOGE("%s: Bad camera ID %s", __FUNCTION__, id.string());
366 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700367 return;
368 }
369
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800370 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800371
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800372 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800373 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700374 return;
375 }
376
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800377 if (newStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700378 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
379 newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800380
381 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
382 // to this device until the status changes
383 updateStatus(StatusInternal::NOT_PRESENT, id);
384
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800385 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700386 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800387 // Don't do this in updateStatus to avoid deadlock over mServiceLock
388 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700389
Ruben Brunkcc776712015-02-17 20:18:47 -0800390 // Remove cached shim parameters
391 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700392
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800393 // Remove online as well as offline client from the list of active clients,
394 // if they are present
395 clientToDisconnectOnline = removeClientLocked(id);
396 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + id);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700397 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800398
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800399 disconnectClient(id, clientToDisconnectOnline);
400 disconnectClient(kOfflineDevice + id, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700401
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100402 removeStates(id);
Ruben Brunkcc776712015-02-17 20:18:47 -0800403 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800404 if (oldStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700405 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
406 newStatus));
407 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800408 updateStatus(newStatus, id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700409 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800410}
Igor Murashkincba2c162013-03-20 15:56:31 -0700411
Shuzhen Wang43858162020-01-10 13:42:15 -0800412void CameraService::onDeviceStatusChanged(const String8& id,
413 const String8& physicalId,
414 CameraDeviceStatus newHalStatus) {
415 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
416 __FUNCTION__, id.string(), physicalId.string(), newHalStatus);
417
418 StatusInternal newStatus = mapToInternal(newHalStatus);
419
420 std::shared_ptr<CameraState> state = getCameraState(id);
421
422 if (state == nullptr) {
423 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
424 __FUNCTION__, id.string(), physicalId.string());
425 return;
426 }
427
428 StatusInternal logicalCameraStatus = state->getStatus();
429 if (logicalCameraStatus != StatusInternal::PRESENT &&
430 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
431 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
432 __FUNCTION__, physicalId.string(), newHalStatus, logicalCameraStatus);
433 return;
434 }
435
436 bool updated = false;
437 if (newStatus == StatusInternal::PRESENT) {
438 updated = state->removeUnavailablePhysicalId(physicalId);
439 } else {
440 updated = state->addUnavailablePhysicalId(physicalId);
441 }
442
443 if (updated) {
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800444 String8 idCombo = id + " : " + physicalId;
445 if (newStatus == StatusInternal::PRESENT) {
446 logDeviceAdded(idCombo,
447 String8::format("Device status changed to %d", newStatus));
448 } else {
449 logDeviceRemoved(idCombo,
450 String8::format("Device status changed to %d", newStatus));
451 }
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700452 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
453 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
454 if (getSystemCameraKind(id, &deviceKind) != OK) {
455 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.string());
456 return;
457 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800458 String16 id16(id), physicalId16(physicalId);
459 Mutex::Autolock lock(mStatusListenerLock);
460 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700461 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
462 listener->getListenerPid(), listener->getListenerUid())) {
463 ALOGV("Skipping discovery callback for system-only camera device %s",
464 id.c_str());
465 continue;
466 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800467 listener->getListener()->onPhysicalCameraStatusChanged(mapToInterface(newStatus),
468 id16, physicalId16);
469 }
470 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700471}
472
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800473void CameraService::disconnectClient(const String8& id, sp<BasicClient> clientToDisconnect) {
474 if (clientToDisconnect.get() != nullptr) {
475 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
476 __FUNCTION__, id.string());
477 // Notify the client of disconnection
478 clientToDisconnect->notifyError(
479 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
480 CaptureResultExtras{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800481 clientToDisconnect->disconnect();
482 }
483}
484
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800485void CameraService::onTorchStatusChanged(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800486 TorchModeStatus newStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700487 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
488 status_t res = getSystemCameraKind(cameraId, &systemCameraKind);
489 if (res != OK) {
490 ALOGE("%s: Could not get system camera kind for camera id %s", __FUNCTION__,
491 cameraId.string());
492 return;
493 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800494 Mutex::Autolock al(mTorchStatusMutex);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700495 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800496}
497
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800498void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700499 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800500 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
501 __FUNCTION__, cameraId.string(), newStatus);
502
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800503 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800504 status_t res = getTorchStatusLocked(cameraId, &status);
505 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700506 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
507 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800508 return;
509 }
510 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800511 return;
512 }
513
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800514 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800515 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800516 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
517 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800518 return;
519 }
520
Ruben Brunkcc776712015-02-17 20:18:47 -0800521 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700522 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700523 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700524 auto iter = mTorchUidMap.find(cameraId);
525 if (iter != mTorchUidMap.end()) {
526 int oldUid = iter->second.second;
527 int newUid = iter->second.first;
528 BatteryNotifier& notifier(BatteryNotifier::getInstance());
529 if (oldUid != newUid) {
530 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800531 if (status == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700532 notifier.noteFlashlightOff(cameraId, oldUid);
533 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800534 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700535 notifier.noteFlashlightOn(cameraId, newUid);
536 }
537 iter->second.second = newUid;
538 } else {
539 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800540 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700541 notifier.noteFlashlightOn(cameraId, oldUid);
542 } else {
543 notifier.noteFlashlightOff(cameraId, oldUid);
544 }
545 }
546 }
547 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700548 broadcastTorchModeStatus(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800549}
550
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700551static bool hasPermissionsForSystemCamera(int callingPid, int callingUid) {
552 return checkPermission(sSystemCameraPermission, callingPid, callingUid) &&
553 checkPermission(sCameraPermission, callingPid, callingUid);
554}
555
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800556Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700557 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100558 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700559 bool hasSystemCameraPermissions =
560 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
561 CameraThreadState::getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700562 switch (type) {
563 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700564 if (hasSystemCameraPermissions) {
565 *numCameras = static_cast<int>(mNormalDeviceIds.size());
566 } else {
567 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
568 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800569 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700570 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700571 if (hasSystemCameraPermissions) {
572 *numCameras = mNumberOfCameras;
573 } else {
574 *numCameras = mNumberOfCamerasWithoutSystemCamera;
575 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800576 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700577 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800578 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700579 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800580 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
581 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700582 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800583 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700584}
585
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800586Status CameraService::getCameraInfo(int cameraId,
587 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700588 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100589 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700590 std::string cameraIdStr = cameraIdIntToStrLocked(cameraId);
591 if (shouldRejectSystemCameraConnection(String8(cameraIdStr.c_str()))) {
592 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
593 "characteristics for system only device %s: ", cameraIdStr.c_str());
594 }
Emilian Peevaee727d2017-05-04 16:35:48 +0100595
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800596 if (!mInitialized) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800597 return STATUS_ERROR(ERROR_DISCONNECTED,
598 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -0700599 }
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700600 bool hasSystemCameraPermissions =
601 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
602 CameraThreadState::getCallingUid());
603 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
604 if (hasSystemCameraPermissions) {
605 cameraIdBound = mNumberOfCameras;
606 }
607 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800608 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
609 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700610 }
611
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800612 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800613 status_t err = mCameraProviderManager->getCameraInfo(
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700614 cameraIdStr.c_str(), cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100615 if (err != OK) {
616 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
617 "Error retrieving camera info from device %d: %s (%d)", cameraId,
618 strerror(-err), err);
Ruben Brunkcc776712015-02-17 20:18:47 -0800619 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100620
Ruben Brunkcc776712015-02-17 20:18:47 -0800621 return ret;
622}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700623
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800624std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700625 const std::vector<std::string> *deviceIds = &mNormalDeviceIdsWithoutSystemCamera;
626 auto callingPid = CameraThreadState::getCallingPid();
627 auto callingUid = CameraThreadState::getCallingUid();
628 if (checkPermission(sSystemCameraPermission, callingPid, callingUid) ||
629 getpid() == callingPid) {
630 deviceIds = &mNormalDeviceIds;
631 }
632 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(deviceIds->size())) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800633 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700634 __FUNCTION__, cameraIdInt, deviceIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800635 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800636 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800637
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700638 return (*deviceIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800639}
640
641String8 CameraService::cameraIdIntToStr(int cameraIdInt) {
642 Mutex::Autolock lock(mServiceLock);
643 return String8(cameraIdIntToStrLocked(cameraIdInt).c_str());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800644}
645
646Status CameraService::getCameraCharacteristics(const String16& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800647 CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700648 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700649 if (!cameraInfo) {
650 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800651 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -0700652 }
653
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800654 if (!mInitialized) {
655 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800656 return STATUS_ERROR(ERROR_DISCONNECTED,
657 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -0700658 }
659
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700660 if (shouldRejectSystemCameraConnection(String8(cameraId))) {
661 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
662 "characteristics for system only device %s: ", String8(cameraId).string());
663 }
664
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800665 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800666
Emilian Peevf53f66e2017-04-11 14:29:43 +0100667 status_t res = mCameraProviderManager->getCameraCharacteristics(
668 String8(cameraId).string(), cameraInfo);
669 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700670 if (res == NAME_NOT_FOUND) {
671 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
672 "characteristics for unknown device %s: %s (%d)", String8(cameraId).string(),
673 strerror(-res), res);
674 } else {
675 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
676 "characteristics for device %s: %s (%d)", String8(cameraId).string(),
677 strerror(-res), res);
678 }
Ruben Brunkb2119af2014-05-09 19:57:56 -0700679 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700680 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
681 if (getSystemCameraKind(String8(cameraId), &deviceKind) != OK) {
682 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, String8(cameraId).string());
683 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera kind "
684 "for device %s", String8(cameraId).string());
685 }
Jayant Chowdhary12361932018-08-27 14:46:13 -0700686 int callingPid = CameraThreadState::getCallingPid();
687 int callingUid = CameraThreadState::getCallingUid();
Emilian Peeve20c6372018-08-14 18:45:53 +0100688 std::vector<int32_t> tagsRemoved;
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700689 // If it's not calling from cameraserver, check the permission only if
690 // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
691 // it would've already been checked in shouldRejectSystemCameraConnection.
Emilian Peeve20c6372018-08-14 18:45:53 +0100692 if ((callingPid != getpid()) &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700693 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700694 !checkPermission(sCameraPermission, callingPid, callingUid)) {
Emilian Peeve20c6372018-08-14 18:45:53 +0100695 res = cameraInfo->removePermissionEntries(
696 mCameraProviderManager->getProviderTagIdLocked(String8(cameraId).string()),
697 &tagsRemoved);
698 if (res != OK) {
699 cameraInfo->clear();
700 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
701 " characteristics needing camera permission for device %s: %s (%d)",
702 String8(cameraId).string(), strerror(-res), res);
703 }
704 }
705
706 if (!tagsRemoved.empty()) {
707 res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
708 tagsRemoved.data(), tagsRemoved.size());
709 if (res != OK) {
710 cameraInfo->clear();
711 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
712 "keys needing permission for device %s: %s (%d)", String8(cameraId).string(),
713 strerror(-res), res);
714 }
715 }
716
Zhijun He2b59be82013-09-25 10:14:30 -0700717 return ret;
718}
719
Ruben Brunkcc776712015-02-17 20:18:47 -0800720String8 CameraService::getFormattedCurrentTime() {
721 time_t now = time(nullptr);
722 char formattedTime[64];
723 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
724 return String8(formattedTime);
725}
726
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800727Status CameraService::getCameraVendorTagDescriptor(
728 /*out*/
729 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700730 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800731 if (!mInitialized) {
732 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800733 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800734 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -0800735 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
736 if (globalDescriptor != nullptr) {
737 *desc = *(globalDescriptor.get());
738 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800739 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800740}
741
Emilian Peev71c73a22017-03-21 16:35:51 +0000742Status CameraService::getCameraVendorTagCache(
743 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
744 ATRACE_CALL();
745 if (!mInitialized) {
746 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
747 return STATUS_ERROR(ERROR_DISCONNECTED,
748 "Camera subsystem not available");
749 }
750 sp<VendorTagDescriptorCache> globalCache =
751 VendorTagDescriptorCache::getGlobalVendorTagCache();
752 if (globalCache != nullptr) {
753 *cache = *(globalCache.get());
754 }
755 return Status::ok();
756}
757
Emilian Peevb91f1802021-03-23 14:50:28 -0700758int CameraService::getDeviceVersion(const String8& cameraId, int* facing, int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700759 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800760
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800761 int deviceVersion = 0;
762
Emilian Peevf53f66e2017-04-11 14:29:43 +0100763 status_t res;
764 hardware::hidl_version maxVersion{0,0};
765 res = mCameraProviderManager->getHighestSupportedVersion(cameraId.string(),
766 &maxVersion);
767 if (res != OK) return -1;
768 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800769
Emilian Peevf53f66e2017-04-11 14:29:43 +0100770 hardware::CameraInfo info;
771 if (facing) {
772 res = mCameraProviderManager->getCameraInfo(cameraId.string(), &info);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -0800773 if (res != OK) return -1;
Emilian Peevf53f66e2017-04-11 14:29:43 +0100774 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -0700775 if (orientation) {
776 *orientation = info.orientation;
777 }
Igor Murashkin634a5152013-02-20 17:15:11 -0800778 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100779
Igor Murashkin634a5152013-02-20 17:15:11 -0800780 return deviceVersion;
781}
782
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800783Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700784 switch(err) {
785 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800786 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800787 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800788 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
789 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800790 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800791 return STATUS_ERROR(ERROR_DISCONNECTED,
792 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700793 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800794 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
795 "Camera HAL encountered error %d: %s",
796 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700797 }
Igor Murashkinbfc99152013-02-27 12:55:20 -0800798}
799
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800800Status CameraService::makeClient(const sp<CameraService>& cameraService,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800801 const sp<IInterface>& cameraCb, const String16& packageName,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700802 const std::optional<String16>& featureId, const String8& cameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -0700803 int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
804 int servicePid, int deviceVersion, apiLevel effectiveApiLevel,
Ruben Brunkcc776712015-02-17 20:18:47 -0800805 /*out*/sp<BasicClient>* client) {
806
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700807 // Create CameraClient based on device version reported by the HAL.
808 switch(deviceVersion) {
809 case CAMERA_DEVICE_API_VERSION_1_0:
810 ALOGE("Camera using old HAL version: %d", deviceVersion);
811 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
812 "Camera device \"%s\" HAL version %d no longer supported",
813 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800814 break;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700815 case CAMERA_DEVICE_API_VERSION_3_0:
816 case CAMERA_DEVICE_API_VERSION_3_1:
817 case CAMERA_DEVICE_API_VERSION_3_2:
818 case CAMERA_DEVICE_API_VERSION_3_3:
819 case CAMERA_DEVICE_API_VERSION_3_4:
820 case CAMERA_DEVICE_API_VERSION_3_5:
821 case CAMERA_DEVICE_API_VERSION_3_6:
Shuzhen Wang83bff122020-11-20 15:51:39 -0800822 case CAMERA_DEVICE_API_VERSION_3_7:
Ruben Brunkcc776712015-02-17 20:18:47 -0800823 if (effectiveApiLevel == API_1) { // Camera1 API route
824 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800825 *client = new Camera2Client(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800826 cameraId, api1CameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -0700827 facing, sensorOrientation, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700828 servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800829 } else { // Camera2 API route
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800830 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
831 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800832 *client = new CameraDeviceClient(cameraService, tmp, packageName, featureId,
Emilian Peev8b64f282021-03-25 16:49:57 -0700833 cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800834 }
835 break;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700836 default:
Ruben Brunkcc776712015-02-17 20:18:47 -0800837 // Should not be reachable
838 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800839 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800840 "Camera device \"%s\" has unknown HAL version %d",
841 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800842 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800843 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800844}
845
Ruben Brunk6267b532015-04-30 17:44:07 -0700846String8 CameraService::toString(std::set<userid_t> intSet) {
847 String8 s("");
848 bool first = true;
849 for (userid_t i : intSet) {
850 if (first) {
851 s.appendFormat("%d", i);
852 first = false;
853 } else {
854 s.appendFormat(", %d", i);
855 }
856 }
857 return s;
858}
859
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800860int32_t CameraService::mapToInterface(TorchModeStatus status) {
861 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
862 switch (status) {
863 case TorchModeStatus::NOT_AVAILABLE:
864 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
865 break;
866 case TorchModeStatus::AVAILABLE_OFF:
867 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
868 break;
869 case TorchModeStatus::AVAILABLE_ON:
870 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
871 break;
872 default:
873 ALOGW("Unknown new flash status: %d", status);
874 }
875 return serviceStatus;
876}
877
878CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
879 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
880 switch (status) {
881 case CameraDeviceStatus::NOT_PRESENT:
882 serviceStatus = StatusInternal::NOT_PRESENT;
883 break;
884 case CameraDeviceStatus::PRESENT:
885 serviceStatus = StatusInternal::PRESENT;
886 break;
887 case CameraDeviceStatus::ENUMERATING:
888 serviceStatus = StatusInternal::ENUMERATING;
889 break;
890 default:
891 ALOGW("Unknown new HAL device status: %d", status);
892 }
893 return serviceStatus;
894}
895
896int32_t CameraService::mapToInterface(StatusInternal status) {
897 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
898 switch (status) {
899 case StatusInternal::NOT_PRESENT:
900 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
901 break;
902 case StatusInternal::PRESENT:
903 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
904 break;
905 case StatusInternal::ENUMERATING:
906 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
907 break;
908 case StatusInternal::NOT_AVAILABLE:
909 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
910 break;
911 case StatusInternal::UNKNOWN:
912 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
913 break;
914 default:
915 ALOGW("Unknown new internal device status: %d", status);
916 }
917 return serviceStatus;
918}
919
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800920Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -0700921 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700922
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800923 String16 internalPackageName("cameraserver");
Ruben Brunkcc776712015-02-17 20:18:47 -0800924 String8 id = String8::format("%d", cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800925 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800926 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800927 if (!(ret = connectHelper<ICameraClient,Client>(
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800928 sp<ICameraClient>{nullptr}, id, cameraId,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +0900929 internalPackageName, {}, uid, USE_CALLING_PID,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700930 API_1, /*shimUpdateOnly*/ true, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800931 ).isOk()) {
932 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
Ruben Brunkb2119af2014-05-09 19:57:56 -0700933 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800934 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700935}
936
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800937Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -0700938 /*out*/
939 CameraParameters* parameters) {
940
941 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
942
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800943 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -0700944
945 if (parameters == NULL) {
946 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800947 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -0700948 }
949
Ruben Brunkcc776712015-02-17 20:18:47 -0800950 String8 id = String8::format("%d", cameraId);
951
952 // Check if we already have parameters
953 {
954 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -0700955 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -0800956 auto cameraState = getCameraState(id);
957 if (cameraState == nullptr) {
958 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800959 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
960 "Invalid camera ID: %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -0800961 }
962 CameraParameters p = cameraState->getShimParams();
963 if (!p.isEmpty()) {
964 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800965 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700966 }
967 }
968
Jayant Chowdhary12361932018-08-27 14:46:13 -0700969 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -0800970 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -0700971 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800972 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800973 // Error already logged by callee
974 return ret;
975 }
976
977 // Check for parameters again
978 {
979 // Scope for service lock
980 Mutex::Autolock lock(mServiceLock);
981 auto cameraState = getCameraState(id);
982 if (cameraState == nullptr) {
983 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800984 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
985 "Invalid camera ID: %s", id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -0700986 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800987 CameraParameters p = cameraState->getShimParams();
988 if (!p.isEmpty()) {
989 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800990 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700991 }
992 }
993
Ruben Brunkcc776712015-02-17 20:18:47 -0800994 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
995 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800996 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -0700997}
998
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800999// Can camera service trust the caller based on the calling UID?
1000static bool isTrustedCallingUid(uid_t uid) {
1001 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001002 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001003 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001004 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001005 return true;
1006 default:
1007 return false;
1008 }
1009}
1010
Nicholas Sauera3620332019-04-03 14:05:17 -07001011static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1012 PermissionController pc;
1013 uid = pc.getPackageUid(packageName, 0);
1014 if (uid <= 0) {
1015 ALOGE("Unknown package: '%s'", String8(packageName).string());
1016 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
1017 return BAD_VALUE;
1018 }
1019
1020 if (userId < 0) {
1021 ALOGE("Invalid user: %d", userId);
1022 dprintf(err, "Invalid user: %d\n", userId);
1023 return BAD_VALUE;
1024 }
1025
1026 uid = multiuser_get_uid(userId, uid);
1027 return NO_ERROR;
1028}
1029
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001030Status CameraService::validateConnectLocked(const String8& cameraId,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001031 const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
1032 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001033
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001034#ifdef __BRILLO__
1035 UNUSED(clientName8);
1036 UNUSED(clientUid);
1037 UNUSED(clientPid);
1038 UNUSED(originalClientPid);
1039#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001040 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1041 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001042 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001043 return allowed;
1044 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001045#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001046
Jayant Chowdhary12361932018-08-27 14:46:13 -07001047 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001048
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001049 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001050 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1051 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001052 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1053 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001054 }
1055
Ruben Brunkcc776712015-02-17 20:18:47 -08001056 if (getCameraState(cameraId) == nullptr) {
1057 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1058 cameraId.string());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001059 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1060 "No camera device with ID \"%s\" available", cameraId.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001061 }
1062
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001063 status_t err = checkIfDeviceIsUsable(cameraId);
1064 if (err != NO_ERROR) {
1065 switch(err) {
1066 case -ENODEV:
1067 case -EBUSY:
1068 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1069 "No camera device with ID \"%s\" currently available", cameraId.string());
1070 default:
1071 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1072 "Unknown error connecting to ID \"%s\"", cameraId.string());
1073 }
1074 }
1075 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001076}
1077
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001078Status CameraService::validateClientPermissionsLocked(const String8& cameraId,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001079 const String8& clientName8, int& clientUid, int& clientPid,
1080 /*out*/int& originalClientPid) const {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001081 int callingPid = CameraThreadState::getCallingPid();
1082 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001083
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001084 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001085 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001086 clientUid = callingUid;
1087 } else if (!isTrustedCallingUid(callingUid)) {
1088 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1089 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001090 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1091 "Untrusted caller (calling PID %d, UID %d) trying to "
1092 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1093 callingPid, callingUid, cameraId.string(),
1094 clientName8.string(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001095 }
1096
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001097 // Check if we can trust clientPid
1098 if (clientPid == USE_CALLING_PID) {
1099 clientPid = callingPid;
1100 } else if (!isTrustedCallingUid(callingUid)) {
1101 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1102 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001103 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1104 "Untrusted caller (calling PID %d, UID %d) trying to "
1105 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1106 callingPid, callingUid, cameraId.string(),
1107 clientName8.string(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001108 }
1109
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001110 if (shouldRejectSystemCameraConnection(cameraId)) {
1111 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1112 cameraId.c_str());
1113 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
1114 "available", cameraId.string());
1115 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001116 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1117 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1118 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
1119 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
1120 "found while trying to query device kind", cameraId.string());
1121
1122 }
1123
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001124 // If it's not calling from cameraserver, check the permission if the
1125 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1126 // android.permission.SYSTEM_CAMERA for system only camera devices).
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001127 if (callingPid != getpid() &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001128 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001129 !checkPermission(sCameraPermission, clientPid, clientUid)) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001130 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001131 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1132 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
1133 clientName8.string(), clientUid, clientPid, cameraId.string());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001134 }
1135
Svet Ganova453d0d2018-01-11 15:37:58 -08001136 // Make sure the UID is in an active state to use the camera
Svet Ganov7b4ab782018-03-25 12:48:10 -07001137 if (!mUidPolicy->isUidActive(callingUid, String16(clientName8))) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001138 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001139 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1140 clientPid, clientUid);
1141 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001142 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1143 "calling UID %d proc state %" PRId32 ")",
1144 clientName8.string(), clientUid, clientPid, cameraId.string(),
1145 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001146 }
1147
Michael Grooverd1d435a2018-12-18 17:39:42 -08001148 // If sensor privacy is enabled then prevent access to the camera
1149 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1150 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1151 return STATUS_ERROR_FMT(ERROR_DISABLED,
1152 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
1153 "is enabled", clientName8.string(), clientUid, clientPid, cameraId.string());
1154 }
1155
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001156 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1157 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001158 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001159 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001160
Ruben Brunk6267b532015-04-30 17:44:07 -07001161 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001162
Ruben Brunka8ca9152015-04-07 14:23:40 -07001163 // Only allow clients who are being used by the current foreground device user, unless calling
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001164 // from our own process OR the caller is using the cameraserver's HIDL interface.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001165 if (getCurrentServingCall() != BinderCallType::HWBINDER && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001166 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001167 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1168 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
1169 toString(mAllowedUsers).string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001170 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1171 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
1172 clientUserId, cameraId.string());
Ruben Brunk36597b22015-03-20 22:15:57 -07001173 }
1174
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001175 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001176}
1177
1178status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
1179 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001180 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001181 if (cameraState == nullptr) {
1182 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1183 cameraId.string());
1184 return -ENODEV;
1185 }
1186
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001187 StatusInternal currentStatus = cameraState->getStatus();
1188 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001189 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
1190 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001191 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001192 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001193 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
1194 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001195 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001196 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001197
Ruben Brunkcc776712015-02-17 20:18:47 -08001198 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001199}
1200
Ruben Brunkcc776712015-02-17 20:18:47 -08001201void CameraService::finishConnectLocked(const sp<BasicClient>& client,
1202 const CameraService::DescriptorPtr& desc) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001203
Ruben Brunkcc776712015-02-17 20:18:47 -08001204 // Make a descriptor for the incoming client
1205 auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
1206 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1207
1208 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
1209 String8(client->getPackageName()));
1210
1211 if (evicted.size() > 0) {
1212 // This should never happen - clients should already have been removed in disconnect
1213 for (auto& i : evicted) {
1214 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
1215 __FUNCTION__, i->getKey().string());
1216 }
1217
1218 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1219 __FUNCTION__);
1220 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001221
1222 // And register a death notification for the client callback. Do
1223 // this last to avoid Binder policy where a nested Binder
1224 // transaction might be pre-empted to service the client death
1225 // notification if the client process dies before linkToDeath is
1226 // invoked.
1227 sp<IBinder> remoteCallback = client->getRemote();
1228 if (remoteCallback != nullptr) {
1229 remoteCallback->linkToDeath(this);
1230 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001231}
1232
1233status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
1234 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
1235 /*out*/
1236 sp<BasicClient>* client,
1237 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001238 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001239 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001240 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001241 DescriptorPtr clientDescriptor;
1242 {
1243 if (effectiveApiLevel == API_1) {
1244 // If we are using API1, any existing client for this camera ID with the same remote
1245 // should be returned rather than evicted to allow MediaRecorder to work properly.
1246
1247 auto current = mActiveClientManager.get(cameraId);
1248 if (current != nullptr) {
1249 auto clientSp = current->getValue();
1250 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001251 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
1252 ALOGW("CameraService connect called from same client, but with a different"
1253 " API level, evicting prior client...");
1254 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001255 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001256 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001257 *client = clientSp;
1258 return NO_ERROR;
1259 }
1260 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001261 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001262 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001263
Ruben Brunkcc776712015-02-17 20:18:47 -08001264 // Get current active client PIDs
1265 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1266 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001267
Emilian Peev8131a262017-02-01 12:33:43 +00001268 std::vector<int> priorityScores(ownerPids.size());
1269 std::vector<int> states(ownerPids.size());
Igor Murashkine6800ce2013-03-04 17:25:57 -08001270
Emilian Peev8131a262017-02-01 12:33:43 +00001271 // Get priority scores of all active PIDs
1272 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1273 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1274 /*out*/&priorityScores[0]);
1275 if (err != OK) {
1276 ALOGE("%s: Priority score query failed: %d",
1277 __FUNCTION__, err);
1278 return err;
1279 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001280
Ruben Brunkcc776712015-02-17 20:18:47 -08001281 // Update all active clients' priorities
Emilian Peev8131a262017-02-01 12:33:43 +00001282 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
Ruben Brunkcc776712015-02-17 20:18:47 -08001283 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
Emilian Peev8131a262017-02-01 12:33:43 +00001284 pidToPriorityMap.emplace(ownerPids[i],
Jayant Chowdharyc578a502019-05-08 10:57:54 -07001285 resource_policy::ClientPriority(priorityScores[i], states[i],
1286 /* isVendorClient won't get copied over*/ false));
Ruben Brunkcc776712015-02-17 20:18:47 -08001287 }
1288 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001289
Ruben Brunkcc776712015-02-17 20:18:47 -08001290 // Get state for the given cameraId
1291 auto state = getCameraState(cameraId);
1292 if (state == nullptr) {
1293 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1294 clientPid, cameraId.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001295 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001296 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001297 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001298
1299 // Make descriptor for incoming client
Shuzhen Wang2db86ff2018-04-25 01:11:17 +00001300 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001301 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1302 state->getConflicting(),
Emilian Peev8131a262017-02-01 12:33:43 +00001303 priorityScores[priorityScores.size() - 1],
1304 clientPid,
1305 states[states.size() - 1]);
Ruben Brunkcc776712015-02-17 20:18:47 -08001306
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001307 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1308
Ruben Brunkcc776712015-02-17 20:18:47 -08001309 // Find clients that would be evicted
1310 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1311
1312 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1313 // background, so we cannot do evictions
1314 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1315 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1316 " priority).", clientPid);
1317
1318 sp<BasicClient> clientSp = clientDescriptor->getValue();
1319 String8 curTime = getFormattedCurrentTime();
1320 auto incompatibleClients =
1321 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1322
1323 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Emilian Peev8131a262017-02-01 12:33:43 +00001324 "(PID %d, score %d state %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001325 cameraId.string(), packageName.string(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001326 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001327
1328 for (auto& i : incompatibleClients) {
1329 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001330 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
1331 i->getKey().string(),
1332 String8{i->getValue()->getPackageName()}.string(),
1333 i->getOwnerId(), i->getPriority().getScore(),
1334 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001335 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00001336 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(),
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001337 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001338 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001339 }
1340
1341 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001342 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001343 mEventLog.add(msg);
1344
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001345 auto current = mActiveClientManager.get(cameraId);
1346 if (current != nullptr) {
1347 return -EBUSY; // CAMERA_IN_USE
1348 } else {
1349 return -EUSERS; // MAX_CAMERAS_IN_USE
1350 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001351 }
1352
1353 for (auto& i : evicted) {
1354 sp<BasicClient> clientSp = i->getValue();
1355 if (clientSp.get() == nullptr) {
1356 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1357
1358 // TODO: Remove this
1359 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1360 __FUNCTION__);
1361 mActiveClientManager.remove(i);
1362 continue;
1363 }
1364
1365 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1366 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001367 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001368
Ruben Brunkcc776712015-02-17 20:18:47 -08001369 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001370 logEvent(String8::format("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00001371 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1372 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001373 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
Emilian Peev8131a262017-02-01 12:33:43 +00001374 i->getOwnerId(), i->getPriority().getScore(),
1375 i->getPriority().getState(), cameraId.string(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001376 packageName.string(), clientPid, clientPriority.getScore(),
1377 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08001378
1379 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001380 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001381 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001382 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001383 }
1384
Ruben Brunkcc776712015-02-17 20:18:47 -08001385 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1386 // other clients from connecting in mServiceLockWrapper if held
1387 mServiceLock.unlock();
1388
1389 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07001390 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001391
1392 // Destroy evicted clients
1393 for (auto& i : evictedClients) {
1394 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001395 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001396 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001397
Jayant Chowdhary12361932018-08-27 14:46:13 -07001398 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08001399
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001400 for (const auto& i : evictedClients) {
1401 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1402 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1403 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1404 if (ret == TIMED_OUT) {
1405 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1406 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1407 mActiveClientManager.toString().string());
1408 return -EBUSY;
1409 }
1410 if (ret != NO_ERROR) {
1411 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1412 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1413 ret, mActiveClientManager.toString().string());
1414 return ret;
1415 }
1416 }
1417
1418 evictedClients.clear();
1419
Ruben Brunkcc776712015-02-17 20:18:47 -08001420 // Once clients have been disconnected, relock
1421 mServiceLock.lock();
1422
1423 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1424 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1425 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001426 }
1427
Ruben Brunkcc776712015-02-17 20:18:47 -08001428 *partial = clientDescriptor;
1429 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001430}
1431
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001432Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001433 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001434 int api1CameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001435 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001436 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001437 int clientPid,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001438 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001439 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001440
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001441 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001442 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001443
1444 String8 id = cameraIdIntToStr(api1CameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001445 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001446 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001447 clientPackageName, {}, clientUid, clientPid, API_1,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001448 /*shimUpdateOnly*/ false, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001449
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001450 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001451 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001452 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001453 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001454 }
1455
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001456 *device = client;
1457 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001458}
1459
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001460bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
1461 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001462 // If the client is not a vendor client, don't add listener if
1463 // a) the camera is a publicly hidden secure camera OR
1464 // b) the camera is a system only camera and the client doesn't
1465 // have android.permission.SYSTEM_CAMERA permissions.
1466 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
1467 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1468 !hasPermissionsForSystemCamera(clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001469 return true;
1470 }
1471 return false;
1472}
1473
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001474bool CameraService::shouldRejectSystemCameraConnection(const String8& cameraId) const {
1475 // Rules for rejection:
1476 // 1) If cameraserver tries to access this camera device, accept the
1477 // connection.
1478 // 2) The camera device is a publicly hidden secure camera device AND some
1479 // component is trying to access it on a non-hwbinder thread (generally a non HAL client),
1480 // reject it.
1481 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
1482 // and the serving thread is a non hwbinder thread, the client must have
1483 // android.permission.SYSTEM_CAMERA permissions to connect.
1484
1485 int cPid = CameraThreadState::getCallingPid();
1486 int cUid = CameraThreadState::getCallingUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001487 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
1488 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001489 // This isn't a known camera ID, so it's not a system camera
1490 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
1491 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001492 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001493
1494 // (1) Cameraserver trying to connect, accept.
1495 if (CameraThreadState::getCallingPid() == getpid()) {
1496 return false;
1497 }
1498 // (2)
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001499 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001500 systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
1501 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
1502 return true;
1503 }
1504 // (3) Here we only check for permissions if it is a system only camera device. This is since
1505 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
1506 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
1507 // same behavior for system camera devices.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001508 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001509 systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1510 !hasPermissionsForSystemCamera(cPid, cUid)) {
1511 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
1512 cameraId.c_str());
1513 return true;
1514 }
1515
1516 return false;
1517}
1518
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001519Status CameraService::connectDevice(
1520 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001521 const String16& cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001522 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001523 const std::optional<String16>& clientFeatureId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001524 int clientUid,
1525 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001526 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001527
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001528 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001529 Status ret = Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001530 String8 id = String8(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001531 sp<CameraDeviceClient> client = nullptr;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001532 String16 clientPackageNameAdj = clientPackageName;
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001533
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001534 if (getCurrentServingCall() == BinderCallType::HWBINDER) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001535 std::string vendorClient =
1536 StringPrintf("vendor.client.pid<%d>", CameraThreadState::getCallingPid());
1537 clientPackageNameAdj = String16(vendorClient.c_str());
1538 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001539 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001540 /*api1CameraId*/-1, clientPackageNameAdj, clientFeatureId,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001541 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08001542
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001543 if(!ret.isOk()) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001544 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageNameAdj),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001545 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001546 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001547 }
1548
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001549 *device = client;
1550 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001551}
1552
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001553template<class CALLBACK, class CLIENT>
1554Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001555 int api1CameraId, const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001556 const std::optional<String16>& clientFeatureId, int clientUid, int clientPid,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001557 apiLevel effectiveApiLevel, bool shimUpdateOnly,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001558 /*out*/sp<CLIENT>& device) {
1559 binder::Status ret = binder::Status::ok();
1560
1561 String8 clientName8(clientPackageName);
1562
1563 int originalClientPid = 0;
1564
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001565 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001566 "Camera API version %d", clientPid, clientName8.string(), cameraId.string(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001567 static_cast<int>(effectiveApiLevel));
1568
Shuzhen Wang316781a2020-08-18 18:11:01 -07001569 nsecs_t openTimeNs = systemTime();
1570
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001571 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001572 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07001573 int orientation = 0;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001574 bool isNdk = (clientPackageName.size() == 0);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001575 {
1576 // Acquire mServiceLock and prevent other clients from connecting
1577 std::unique_ptr<AutoConditionLock> lock =
1578 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1579
1580 if (lock == nullptr) {
1581 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
1582 , clientPid);
1583 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1584 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
1585 cameraId.string(), clientName8.string(), clientPid);
1586 }
1587
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07001588 // Enforce client permissions and do basic validity checks
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001589 if(!(ret = validateConnectLocked(cameraId, clientName8,
1590 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
1591 return ret;
1592 }
1593
1594 // Check the shim parameters after acquiring lock, if they have already been updated and
1595 // we were doing a shim update, return immediately
1596 if (shimUpdateOnly) {
1597 auto cameraState = getCameraState(cameraId);
1598 if (cameraState != nullptr) {
1599 if (!cameraState->getShimParams().isEmpty()) return ret;
1600 }
1601 }
1602
1603 status_t err;
1604
1605 sp<BasicClient> clientTmp = nullptr;
1606 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
1607 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
1608 IInterface::asBinder(cameraCb), clientName8, /*out*/&clientTmp,
1609 /*out*/&partial)) != NO_ERROR) {
1610 switch (err) {
1611 case -ENODEV:
1612 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1613 "No camera device with ID \"%s\" currently available",
1614 cameraId.string());
1615 case -EBUSY:
1616 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1617 "Higher-priority client using camera, ID \"%s\" currently unavailable",
1618 cameraId.string());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001619 case -EUSERS:
1620 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1621 "Too many cameras already open, cannot open camera \"%s\"",
1622 cameraId.string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001623 default:
1624 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1625 "Unexpected error %s (%d) opening camera \"%s\"",
1626 strerror(-err), err, cameraId.string());
1627 }
1628 }
1629
1630 if (clientTmp.get() != nullptr) {
1631 // Handle special case for API1 MediaRecorder where the existing client is returned
1632 device = static_cast<CLIENT*>(clientTmp.get());
1633 return ret;
1634 }
1635
1636 // give flashlight a chance to close devices if necessary.
1637 mFlashlight->prepareDeviceOpen(cameraId);
1638
Emilian Peevb91f1802021-03-23 14:50:28 -07001639 int deviceVersion = getDeviceVersion(cameraId, /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08001640 if (facing == -1) {
1641 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.string());
1642 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1643 "Unable to get camera device \"%s\" facing", cameraId.string());
1644 }
1645
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001646 sp<BasicClient> tmp = nullptr;
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001647 if(!(ret = makeClient(this, cameraCb, clientPackageName, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07001648 cameraId, api1CameraId, facing, orientation,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001649 clientPid, clientUid, getpid(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001650 deviceVersion, effectiveApiLevel,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001651 /*out*/&tmp)).isOk()) {
1652 return ret;
1653 }
1654 client = static_cast<CLIENT*>(tmp.get());
1655
1656 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
1657 __FUNCTION__);
1658
Emilian Peevbd8c5032018-02-14 23:05:40 +00001659 err = client->initialize(mCameraProviderManager, mMonitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001660 if (err != OK) {
1661 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001662 // Errors could be from the HAL module open call or from AppOpsManager
1663 switch(err) {
1664 case BAD_VALUE:
1665 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1666 "Illegal argument to HAL module for camera \"%s\"", cameraId.string());
1667 case -EBUSY:
1668 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1669 "Camera \"%s\" is already open", cameraId.string());
1670 case -EUSERS:
1671 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1672 "Too many cameras already open, cannot open camera \"%s\"",
1673 cameraId.string());
1674 case PERMISSION_DENIED:
1675 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1676 "No permission to open camera \"%s\"", cameraId.string());
1677 case -EACCES:
1678 return STATUS_ERROR_FMT(ERROR_DISABLED,
1679 "Camera \"%s\" disabled by policy", cameraId.string());
1680 case -ENODEV:
1681 default:
1682 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1683 "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
1684 strerror(-err), err);
1685 }
1686 }
1687
1688 // Update shim paremeters for legacy clients
1689 if (effectiveApiLevel == API_1) {
1690 // Assume we have always received a Client subclass for API1
1691 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
1692 String8 rawParams = shimClient->getParameters();
1693 CameraParameters params(rawParams);
1694
1695 auto cameraState = getCameraState(cameraId);
1696 if (cameraState != nullptr) {
1697 cameraState->setShimParams(params);
1698 } else {
1699 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
1700 __FUNCTION__, cameraId.string());
1701 }
1702 }
1703
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001704 // Set rotate-and-crop override behavior
1705 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
1706 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
Emilian Peevb91f1802021-03-23 14:50:28 -07001707 } else if (CameraServiceProxyWrapper::isRotateAndCropOverrideNeeded(clientPackageName,
1708 orientation, facing)) {
1709 client->setRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_90);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001710 }
1711
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08001712 // Set camera muting behavior
1713 if (client->supportsCameraMute()) {
Evan Severson190ad252021-01-07 20:37:15 -08001714 client->setCameraMute(mOverrideCameraMuteMode ||
1715 isUserSensorPrivacyEnabledForUid(clientUid));
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08001716 }
1717
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001718 if (shimUpdateOnly) {
1719 // If only updating legacy shim parameters, immediately disconnect client
1720 mServiceLock.unlock();
1721 client->disconnect();
1722 mServiceLock.lock();
1723 } else {
1724 // Otherwise, add client to active clients list
1725 finishConnectLocked(client, partial);
1726 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001727
1728 client->setImageDumpMask(mImageDumpMask);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001729 } // lock is destroyed, allow further connect calls
1730
1731 // Important: release the mutex here so the client can call back into the service from its
1732 // destructor (can be at the end of the call)
1733 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001734
1735 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
1736 CameraServiceProxyWrapper::logOpen(cameraId, facing, clientPackageName,
1737 effectiveApiLevel, isNdk, openLatencyMs);
1738
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001739 return ret;
1740}
1741
Emilian Peevb2bc5a42019-11-20 16:02:14 -08001742status_t CameraService::addOfflineClient(String8 cameraId, sp<BasicClient> offlineClient) {
1743 if (offlineClient.get() == nullptr) {
1744 return BAD_VALUE;
1745 }
1746
1747 {
1748 // Acquire mServiceLock and prevent other clients from connecting
1749 std::unique_ptr<AutoConditionLock> lock =
1750 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1751
1752 if (lock == nullptr) {
1753 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
1754 , __FUNCTION__, offlineClient->getClientPid());
1755 return TIMED_OUT;
1756 }
1757
1758 auto onlineClientDesc = mActiveClientManager.get(cameraId);
1759 if (onlineClientDesc.get() == nullptr) {
1760 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
1761 cameraId.c_str());
1762 return BAD_VALUE;
1763 }
1764
1765 // Offline clients do not evict or conflict with other online devices. Resource sharing
1766 // conflicts are handled by the camera provider which will either succeed or fail before
1767 // reaching this method.
1768 const auto& onlinePriority = onlineClientDesc->getPriority();
1769 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
1770 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
1771 /*conflictingKeys*/ std::set<String8>(), onlinePriority.getScore(),
1772 onlineClientDesc->getOwnerId(), onlinePriority.getState());
1773
1774 // Allow only one offline device per camera
1775 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
1776 if (!incompatibleClients.empty()) {
1777 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
1778 return BAD_VALUE;
1779 }
1780
1781 auto err = offlineClient->initialize(mCameraProviderManager, mMonitorTags);
1782 if (err != OK) {
1783 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
1784 return err;
1785 }
1786
1787 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
1788 if (evicted.size() > 0) {
1789 for (auto& i : evicted) {
1790 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
1791 __FUNCTION__, i->getKey().string());
1792 }
1793
1794 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
1795 "properly", __FUNCTION__);
1796
1797 return BAD_VALUE;
1798 }
1799
1800 logConnectedOffline(offlineClientDesc->getKey(),
1801 static_cast<int>(offlineClientDesc->getOwnerId()),
1802 String8(offlineClient->getPackageName()));
1803
1804 sp<IBinder> remoteCallback = offlineClient->getRemote();
1805 if (remoteCallback != nullptr) {
1806 remoteCallback->linkToDeath(this);
1807 }
1808 } // lock is destroyed, allow further connect calls
1809
1810 return OK;
1811}
1812
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001813Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001814 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001815 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001816
1817 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07001818 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001819 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001820 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1821 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001822 }
1823
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001824 String8 id = String8(cameraId.string());
Jayant Chowdhary12361932018-08-27 14:46:13 -07001825 int uid = CameraThreadState::getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001826
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07001827 if (shouldRejectSystemCameraConnection(id)) {
1828 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
1829 " for system only device %s: ", id.string());
1830 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001831 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08001832 auto state = getCameraState(id);
1833 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001834 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001835 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1836 "Camera ID \"%s\" is a not valid camera ID", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001837 }
1838
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001839 StatusInternal cameraStatus = state->getStatus();
1840 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001841 cameraStatus != StatusInternal::NOT_AVAILABLE) {
1842 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001843 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1844 "Camera ID \"%s\" is a not valid camera ID", id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001845 }
1846
1847 {
1848 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001849 TorchModeStatus status;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001850 status_t err = getTorchStatusLocked(id, &status);
1851 if (err != OK) {
1852 if (err == NAME_NOT_FOUND) {
1853 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1854 "Camera \"%s\" does not have a flash unit", id.string());
1855 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001856 ALOGE("%s: getting current torch status failed for camera %s",
1857 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001858 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1859 "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
1860 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001861 }
1862
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001863 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001864 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001865 ALOGE("%s: torch mode of camera %s is not available because "
1866 "camera is in use", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001867 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1868 "Torch for camera \"%s\" is not available due to an existing camera user",
1869 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001870 } else {
1871 ALOGE("%s: torch mode of camera %s is not available due to "
1872 "insufficient resources", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001873 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1874 "Torch for camera \"%s\" is not available due to insufficient resources",
1875 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001876 }
1877 }
1878 }
1879
Ruben Brunk99e69712015-05-26 17:25:07 -07001880 {
1881 // Update UID map - this is used in the torch status changed callbacks, so must be done
1882 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07001883 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -07001884 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
1885 mTorchUidMap[id].first = uid;
1886 mTorchUidMap[id].second = uid;
1887 } else {
1888 // Set the pending UID
1889 mTorchUidMap[id].first = uid;
1890 }
1891 }
1892
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001893 status_t err = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07001894
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001895 if (err != OK) {
1896 int32_t errorCode;
1897 String8 msg;
1898 switch (err) {
1899 case -ENOSYS:
1900 msg = String8::format("Camera \"%s\" has no flashlight",
1901 id.string());
1902 errorCode = ERROR_ILLEGAL_ARGUMENT;
1903 break;
1904 default:
1905 msg = String8::format(
1906 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
1907 id.string(), enabled, strerror(-err), err);
1908 errorCode = ERROR_INVALID_OPERATION;
1909 }
1910 ALOGE("%s: %s", __FUNCTION__, msg.string());
1911 return STATUS_ERROR(errorCode, msg.string());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001912 }
1913
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001914 {
1915 // update the link to client's death
1916 Mutex::Autolock al(mTorchClientMapMutex);
1917 ssize_t index = mTorchClientMap.indexOfKey(id);
1918 if (enabled) {
1919 if (index == NAME_NOT_FOUND) {
1920 mTorchClientMap.add(id, clientBinder);
1921 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07001922 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001923 mTorchClientMap.replaceValueAt(index, clientBinder);
1924 }
1925 clientBinder->linkToDeath(this);
1926 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07001927 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001928 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001929 }
1930
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07001931 int clientPid = CameraThreadState::getCallingPid();
1932 const char *id_cstr = id.c_str();
1933 const char *torchState = enabled ? "on" : "off";
1934 ALOGI("Torch for camera id %s turned %s for client PID %d", id_cstr, torchState, clientPid);
1935 logTorchEvent(id_cstr, torchState , clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001936 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001937}
1938
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001939Status CameraService::notifySystemEvent(int32_t eventId,
1940 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001941 const int pid = CameraThreadState::getCallingPid();
1942 const int selfPid = getpid();
1943
1944 // Permission checks
1945 if (pid != selfPid) {
1946 // Ensure we're being called by system_server, or similar process with
1947 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001948 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001949 const int uid = CameraThreadState::getCallingUid();
1950 ALOGE("Permission Denial: cannot send updates to camera service about system"
1951 " events from pid=%d, uid=%d", pid, uid);
1952 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09001953 "No permission to send updates to camera service about system events"
1954 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001955 }
1956 }
1957
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001958 ATRACE_CALL();
1959
Ruben Brunk36597b22015-03-20 22:15:57 -07001960 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001961 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001962 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07001963 // from a system server crash
1964 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08001965 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001966 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07001967 break;
1968 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001969 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07001970 default: {
1971 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
1972 eventId);
1973 break;
1974 }
1975 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001976 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07001977}
1978
Emilian Peev53722fa2019-02-22 17:47:20 -08001979void CameraService::notifyMonitoredUids() {
1980 Mutex::Autolock lock(mStatusListenerLock);
1981
1982 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001983 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Emilian Peev53722fa2019-02-22 17:47:20 -08001984 if (!ret.isOk()) {
1985 ALOGE("%s: Failed to trigger permission callback: %d", __FUNCTION__,
1986 ret.exceptionCode());
1987 }
1988 }
1989}
1990
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08001991Status CameraService::notifyDeviceStateChange(int64_t newState) {
1992 const int pid = CameraThreadState::getCallingPid();
1993 const int selfPid = getpid();
1994
1995 // Permission checks
1996 if (pid != selfPid) {
1997 // Ensure we're being called by system_server, or similar process with
1998 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001999 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002000 const int uid = CameraThreadState::getCallingUid();
2001 ALOGE("Permission Denial: cannot send updates to camera service about device"
2002 " state changes from pid=%d, uid=%d", pid, uid);
2003 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2004 "No permission to send updates to camera service about device state"
2005 " changes from pid=%d, uid=%d", pid, uid);
2006 }
2007 }
2008
2009 ATRACE_CALL();
2010
2011 using hardware::camera::provider::V2_5::DeviceState;
2012 hardware::hidl_bitfield<DeviceState> newDeviceState{};
2013 if (newState & ICameraService::DEVICE_STATE_BACK_COVERED) {
2014 newDeviceState |= DeviceState::BACK_COVERED;
2015 }
2016 if (newState & ICameraService::DEVICE_STATE_FRONT_COVERED) {
2017 newDeviceState |= DeviceState::FRONT_COVERED;
2018 }
2019 if (newState & ICameraService::DEVICE_STATE_FOLDED) {
2020 newDeviceState |= DeviceState::FOLDED;
2021 }
2022 // Only map vendor bits directly
2023 uint64_t vendorBits = static_cast<uint64_t>(newState) & 0xFFFFFFFF00000000l;
2024 newDeviceState |= vendorBits;
2025
2026 ALOGV("%s: New device state 0x%" PRIx64, __FUNCTION__, newDeviceState);
2027 Mutex::Autolock l(mServiceLock);
2028 mCameraProviderManager->notifyDeviceStateChange(newDeviceState);
2029
2030 return Status::ok();
2031}
2032
Emilian Peev8b64f282021-03-25 16:49:57 -07002033Status CameraService::notifyDisplayConfigurationChange() {
2034 ATRACE_CALL();
2035 const int callingPid = CameraThreadState::getCallingPid();
2036 const int selfPid = getpid();
2037
2038 // Permission checks
2039 if (callingPid != selfPid) {
2040 // Ensure we're being called by system_server, or similar process with
2041 // permissions to notify the camera service about system events
2042 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
2043 const int uid = CameraThreadState::getCallingUid();
2044 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
2045 " changes from pid=%d, uid=%d", callingPid, uid);
2046 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2047 "No permission to send updates to camera service about orientation"
2048 " changes from pid=%d, uid=%d", callingPid, uid);
2049 }
2050 }
2051
2052 Mutex::Autolock lock(mServiceLock);
2053
2054 // Don't do anything if rotate-and-crop override via cmd is active
2055 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
2056
2057 const auto clients = mActiveClientManager.getAll();
2058 for (auto& current : clients) {
2059 if (current != nullptr) {
2060 const auto basicClient = current->getValue();
2061 if (basicClient.get() != nullptr) {
2062 if (CameraServiceProxyWrapper::isRotateAndCropOverrideNeeded(
2063 basicClient->getPackageName(), basicClient->getCameraOrientation(),
2064 basicClient->getCameraFacing())) {
2065 basicClient->setRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_90);
2066 } else {
2067 basicClient->setRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE);
2068 }
2069 }
2070 }
2071 }
2072
2073 return Status::ok();
2074}
2075
2076Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002077 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
2078 ATRACE_CALL();
2079 if (!concurrentCameraIds) {
2080 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
2081 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
2082 }
2083
2084 if (!mInitialized) {
2085 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2086 return STATUS_ERROR(ERROR_DISCONNECTED,
2087 "Camera subsystem is not available");
2088 }
2089 // First call into the provider and get the set of concurrent camera
2090 // combinations
2091 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07002092 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002093 for (auto &combination : concurrentCameraCombinations) {
2094 std::vector<std::string> validCombination;
2095 for (auto &cameraId : combination) {
2096 // if the camera state is not present, skip
2097 String8 cameraIdStr(cameraId.c_str());
2098 auto state = getCameraState(cameraIdStr);
2099 if (state == nullptr) {
2100 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
2101 continue;
2102 }
2103 StatusInternal status = state->getStatus();
2104 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
2105 continue;
2106 }
2107 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
2108 continue;
2109 }
2110 validCombination.push_back(cameraId);
2111 }
2112 if (validCombination.size() != 0) {
2113 concurrentCameraIds->push_back(std::move(validCombination));
2114 }
2115 }
2116 return Status::ok();
2117}
2118
2119Status CameraService::isConcurrentSessionConfigurationSupported(
2120 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
2121 /*out*/bool* isSupported) {
2122 if (!isSupported) {
2123 ALOGE("%s: isSupported is NULL", __FUNCTION__);
2124 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
2125 }
2126
2127 if (!mInitialized) {
2128 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2129 return STATUS_ERROR(ERROR_DISCONNECTED,
2130 "Camera subsystem is not available");
2131 }
2132
2133 // Check for camera permissions
2134 int callingPid = CameraThreadState::getCallingPid();
2135 int callingUid = CameraThreadState::getCallingUid();
2136 if ((callingPid != getpid()) && !checkPermission(sCameraPermission, callingPid, callingUid)) {
2137 ALOGE("%s: pid %d doesn't have camera permissions", __FUNCTION__, callingPid);
2138 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2139 "android.permission.CAMERA needed to call"
2140 "isConcurrentSessionConfigurationSupported");
2141 }
2142
2143 status_t res =
2144 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
2145 cameraIdsAndSessionConfigurations, isSupported);
2146 if (res != OK) {
2147 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
2148 "support %s (%d)", strerror(-res), res);
2149 }
2150 return Status::ok();
2151}
2152
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002153Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
2154 /*out*/
2155 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002156 return addListenerHelper(listener, cameraStatuses);
2157}
2158
2159Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
2160 /*out*/
2161 std::vector<hardware::CameraStatus> *cameraStatuses,
2162 bool isVendorListener) {
2163
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002164 ATRACE_CALL();
2165
Igor Murashkinbfc99152013-02-27 12:55:20 -08002166 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08002167
Ruben Brunk3450ba72015-06-16 11:00:37 -07002168 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002169 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002170 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002171 }
2172
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002173 auto clientUid = CameraThreadState::getCallingUid();
2174 auto clientPid = CameraThreadState::getCallingPid();
Shuzhen Wang695044d2020-03-06 09:02:23 -08002175 bool openCloseCallbackAllowed = checkPermission(sCameraOpenCloseListenerPermission,
2176 clientPid, clientUid);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002177
Igor Murashkinbfc99152013-02-27 12:55:20 -08002178 Mutex::Autolock lock(mServiceLock);
2179
Ruben Brunkcc776712015-02-17 20:18:47 -08002180 {
2181 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08002182 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002183 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002184 ALOGW("%s: Tried to add listener %p which was already subscribed",
2185 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002186 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08002187 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002188 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002189
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002190 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08002191 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
2192 openCloseCallbackAllowed);
Emilian Peev53722fa2019-02-22 17:47:20 -08002193 auto ret = serviceListener->initialize();
2194 if (ret != NO_ERROR) {
2195 String8 msg = String8::format("Failed to initialize service listener: %s (%d)",
2196 strerror(-ret), ret);
2197 ALOGE("%s: %s", __FUNCTION__, msg.string());
2198 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
2199 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002200 // The listener still needs to be added to the list of listeners, regardless of what
2201 // permissions the listener process has / whether it is a vendor listener. Since it might be
2202 // eligible to listen to other camera ids.
2203 mListenerList.emplace_back(serviceListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08002204 mUidPolicy->registerMonitorUid(clientUid);
Igor Murashkinbfc99152013-02-27 12:55:20 -08002205 }
2206
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002207 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07002208 {
Ruben Brunkcc776712015-02-17 20:18:47 -08002209 Mutex::Autolock lock(mCameraStatesLock);
2210 for (auto& i : mCameraStates) {
Shuzhen Wang43858162020-01-10 13:42:15 -08002211 cameraStatuses->emplace_back(i.first,
2212 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds());
Igor Murashkincba2c162013-03-20 15:56:31 -07002213 }
2214 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002215 // Remove the camera statuses that should be hidden from the client, we do
2216 // this after collecting the states in order to avoid holding
2217 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
2218 // the same time.
2219 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
2220 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
2221 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
2222 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
2223 ALOGE("%s: Invalid camera id %s, skipping status update",
2224 __FUNCTION__, s.cameraId.c_str());
2225 return true;
2226 }
2227 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
2228 clientUid);}), cameraStatuses->end());
2229
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002230 //cameraStatuses will have non-eligible camera ids removed.
2231 std::set<String16> idsChosenForCallback;
2232 for (const auto &s : *cameraStatuses) {
2233 idsChosenForCallback.insert(String16(s.cameraId));
2234 }
Igor Murashkincba2c162013-03-20 15:56:31 -07002235
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002236 /*
2237 * Immediately signal current torch status to this listener only
2238 * This may be a subset of all the devices, so don't include it in the response directly
2239 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002240 {
2241 Mutex::Autolock al(mTorchStatusMutex);
2242 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002243 String16 id = String16(mTorchStatusMap.keyAt(i).string());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002244 // The camera id is visible to the client. Fine to send torch
2245 // callback.
2246 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
2247 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
2248 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002249 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002250 }
2251
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002252 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08002253}
Ruben Brunkcc776712015-02-17 20:18:47 -08002254
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002255Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002256 ATRACE_CALL();
2257
Igor Murashkinbfc99152013-02-27 12:55:20 -08002258 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
2259
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002260 if (listener == 0) {
2261 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002262 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002263 }
2264
Igor Murashkinbfc99152013-02-27 12:55:20 -08002265 Mutex::Autolock lock(mServiceLock);
2266
Ruben Brunkcc776712015-02-17 20:18:47 -08002267 {
2268 Mutex::Autolock lock(mStatusListenerLock);
2269 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002270 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
2271 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid());
2272 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08002273 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002274 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002275 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002276 }
2277 }
2278
2279 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
2280 __FUNCTION__, listener.get());
2281
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002282 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08002283}
2284
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002285Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002286
2287 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002288 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
2289
2290 if (parameters == NULL) {
2291 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002292 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07002293 }
2294
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002295 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002296
2297 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002298 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07002299 // Error logged by caller
2300 return ret;
2301 }
2302
2303 String8 shimParamsString8 = shimParams.flatten();
2304 String16 shimParamsString16 = String16(shimParamsString8);
2305
2306 *parameters = shimParamsString16;
2307
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002308 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07002309}
2310
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002311Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
2312 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002313 ATRACE_CALL();
2314
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002315 const String8 id = String8(cameraId);
2316
2317 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002318
2319 switch (apiVersion) {
2320 case API_VERSION_1:
2321 case API_VERSION_2:
2322 break;
2323 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002324 String8 msg = String8::format("Unknown API version %d", apiVersion);
2325 ALOGE("%s: %s", __FUNCTION__, msg.string());
2326 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002327 }
2328
Emilian Peev28ad2ea2017-02-07 16:14:32 +00002329 int deviceVersion = getDeviceVersion(id);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002330 switch (deviceVersion) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002331 case CAMERA_DEVICE_API_VERSION_1_0:
2332 case CAMERA_DEVICE_API_VERSION_3_0:
2333 case CAMERA_DEVICE_API_VERSION_3_1:
2334 if (apiVersion == API_VERSION_2) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002335 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without shim",
2336 __FUNCTION__, id.string(), deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002337 *isSupported = false;
2338 } else { // if (apiVersion == API_VERSION_1) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002339 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always supported",
2340 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002341 *isSupported = true;
2342 }
2343 break;
2344 case CAMERA_DEVICE_API_VERSION_3_2:
2345 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -07002346 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002347 case CAMERA_DEVICE_API_VERSION_3_5:
Yin-Chia Yeh56d98ba2020-01-16 16:57:14 -08002348 case CAMERA_DEVICE_API_VERSION_3_6:
Shuzhen Wang83bff122020-11-20 15:51:39 -08002349 case CAMERA_DEVICE_API_VERSION_3_7:
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002350 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
2351 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002352 *isSupported = true;
2353 break;
2354 case -1: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002355 String8 msg = String8::format("Unknown camera ID %s", id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002356 ALOGE("%s: %s", __FUNCTION__, msg.string());
2357 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002358 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002359 default: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002360 String8 msg = String8::format("Unknown device version %x for device %s",
2361 deviceVersion, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002362 ALOGE("%s: %s", __FUNCTION__, msg.string());
2363 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
2364 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07002365 }
2366
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002367 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002368}
2369
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002370Status CameraService::isHiddenPhysicalCamera(const String16& cameraId,
2371 /*out*/ bool *isSupported) {
2372 ATRACE_CALL();
2373
2374 const String8 id = String8(cameraId);
2375
2376 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
2377 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(id.string());
2378
2379 return Status::ok();
2380}
2381
Ruben Brunkcc776712015-02-17 20:18:47 -08002382void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002383 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002384 for (auto& i : mActiveClientManager.getAll()) {
2385 auto clientSp = i->getValue();
2386 if (clientSp.get() == client) {
2387 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08002388 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07002389 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002390 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08002391}
2392
Ruben Brunkcc776712015-02-17 20:18:47 -08002393bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002394 bool ret = false;
2395 {
2396 // Acquire mServiceLock and prevent other clients from connecting
2397 std::unique_ptr<AutoConditionLock> lock =
2398 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08002399
Igor Murashkin634a5152013-02-20 17:15:11 -08002400
Ruben Brunkcc776712015-02-17 20:18:47 -08002401 std::vector<sp<BasicClient>> evicted;
2402 for (auto& i : mActiveClientManager.getAll()) {
2403 auto clientSp = i->getValue();
2404 if (clientSp.get() == nullptr) {
2405 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2406 mActiveClientManager.remove(i);
2407 continue;
2408 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08002409 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002410 mActiveClientManager.remove(i);
2411 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08002412
Ruben Brunkcc776712015-02-17 20:18:47 -08002413 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002414 clientSp->notifyError(
2415 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002416 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08002417 }
2418 }
2419
Ruben Brunkcc776712015-02-17 20:18:47 -08002420 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2421 // other clients from connecting in mServiceLockWrapper if held
2422 mServiceLock.unlock();
2423
Ruben Brunk36597b22015-03-20 22:15:57 -07002424 // Do not clear caller identity, remote caller should be client proccess
2425
Ruben Brunkcc776712015-02-17 20:18:47 -08002426 for (auto& i : evicted) {
2427 if (i.get() != nullptr) {
2428 i->disconnect();
2429 ret = true;
2430 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002431 }
2432
Ruben Brunkcc776712015-02-17 20:18:47 -08002433 // Reacquire mServiceLock
2434 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08002435
Ruben Brunkcc776712015-02-17 20:18:47 -08002436 } // lock is destroyed, allow further connect calls
2437
2438 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07002439}
2440
Ruben Brunkcc776712015-02-17 20:18:47 -08002441std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
2442 const String8& cameraId) const {
2443 std::shared_ptr<CameraState> state;
2444 {
2445 Mutex::Autolock lock(mCameraStatesLock);
2446 auto iter = mCameraStates.find(cameraId);
2447 if (iter != mCameraStates.end()) {
2448 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002449 }
2450 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002451 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002452}
2453
Ruben Brunkcc776712015-02-17 20:18:47 -08002454sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
2455 // Remove from active clients list
2456 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
2457 if (clientDescriptorPtr == nullptr) {
2458 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
2459 cameraId.string());
2460 return sp<BasicClient>{nullptr};
2461 }
2462
2463 return clientDescriptorPtr->getValue();
Keun young Parkd8973a72012-03-28 14:13:09 -07002464}
2465
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002466void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07002467 // Acquire mServiceLock and prevent other clients from connecting
2468 std::unique_ptr<AutoConditionLock> lock =
2469 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
2470
Ruben Brunk6267b532015-04-30 17:44:07 -07002471 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002472 for (size_t i = 0; i < newUserIds.size(); i++) {
2473 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07002474 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002475 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07002476 return;
2477 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002478 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07002479 }
2480
Ruben Brunka8ca9152015-04-07 14:23:40 -07002481
Ruben Brunk6267b532015-04-30 17:44:07 -07002482 if (newAllowedUsers == mAllowedUsers) {
2483 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
2484 return;
2485 }
2486
2487 logUserSwitch(mAllowedUsers, newAllowedUsers);
2488
2489 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07002490
2491 // Current user has switched, evict all current clients.
2492 std::vector<sp<BasicClient>> evicted;
2493 for (auto& i : mActiveClientManager.getAll()) {
2494 auto clientSp = i->getValue();
2495
2496 if (clientSp.get() == nullptr) {
2497 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2498 continue;
2499 }
2500
Ruben Brunk6267b532015-04-30 17:44:07 -07002501 // Don't evict clients that are still allowed.
2502 uid_t clientUid = clientSp->getClientUid();
2503 userid_t clientUserId = multiuser_get_user_id(clientUid);
2504 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
2505 continue;
2506 }
2507
Ruben Brunk36597b22015-03-20 22:15:57 -07002508 evicted.push_back(clientSp);
2509
2510 String8 curTime = getFormattedCurrentTime();
2511
2512 ALOGE("Evicting conflicting client for camera ID %s due to user change",
2513 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07002514
Ruben Brunk36597b22015-03-20 22:15:57 -07002515 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002516 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00002517 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
2518 " to user switch.", i->getKey().string(),
2519 String8{clientSp->getPackageName()}.string(),
2520 i->getOwnerId(), i->getPriority().getScore(),
2521 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07002522
2523 }
2524
2525 // Do not hold mServiceLock while disconnecting clients, but retain the condition
2526 // blocking other clients from connecting in mServiceLockWrapper if held.
2527 mServiceLock.unlock();
2528
2529 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07002530 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07002531
2532 for (auto& i : evicted) {
2533 i->disconnect();
2534 }
2535
Jayant Chowdhary12361932018-08-27 14:46:13 -07002536 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07002537
2538 // Reacquire mServiceLock
2539 mServiceLock.lock();
2540}
Ruben Brunkcc776712015-02-17 20:18:47 -08002541
Ruben Brunka8ca9152015-04-07 14:23:40 -07002542void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002543 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07002544 Mutex::Autolock l(mLogLock);
2545 mEventLog.add(String8::format("%s : %s", curTime.string(), event));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002546}
2547
Ruben Brunka8ca9152015-04-07 14:23:40 -07002548void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002549 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002550 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002551 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002552 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002553}
2554
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002555void CameraService::logDisconnectedOffline(const char* cameraId, int clientPid,
2556 const char* clientPackage) {
2557 // Log the clients evicted
2558 logEvent(String8::format("DISCONNECT offline device %s client for package %s (PID %d)",
2559 cameraId, clientPackage, clientPid));
2560}
2561
Ruben Brunka8ca9152015-04-07 14:23:40 -07002562void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002563 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002564 // Log the clients evicted
2565 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002566 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002567}
2568
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002569void CameraService::logConnectedOffline(const char* cameraId, int clientPid,
2570 const char* clientPackage) {
2571 // Log the clients evicted
2572 logEvent(String8::format("CONNECT offline device %s client for package %s (PID %d)", cameraId,
2573 clientPackage, clientPid));
2574}
2575
Ruben Brunka8ca9152015-04-07 14:23:40 -07002576void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002577 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002578 // Log the client rejected
2579 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002580 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002581}
2582
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002583void CameraService::logTorchEvent(const char* cameraId, const char *torchState, int clientPid) {
2584 // Log torch event
2585 logEvent(String8::format("Torch for camera id %s turned %s for client PID %d", cameraId,
2586 torchState, clientPid));
2587}
2588
Ruben Brunk6267b532015-04-30 17:44:07 -07002589void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
2590 const std::set<userid_t>& newUserIds) {
2591 String8 newUsers = toString(newUserIds);
2592 String8 oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002593 if (oldUsers.size() == 0) {
2594 oldUsers = "<None>";
2595 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07002596 // Log the new and old users
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002597 logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
Ruben Brunk6267b532015-04-30 17:44:07 -07002598 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002599}
2600
2601void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
2602 // Log the device removal
2603 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
2604}
2605
2606void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
2607 // Log the device removal
2608 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
2609}
2610
2611void CameraService::logClientDied(int clientPid, const char* reason) {
2612 // Log the device removal
2613 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07002614}
2615
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002616void CameraService::logServiceError(const char* msg, int errorCode) {
2617 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002618 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002619}
2620
Ruben Brunk36597b22015-03-20 22:15:57 -07002621status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
2622 uint32_t flags) {
2623
Mathias Agopian65ab4712010-07-14 17:59:35 -07002624 // Permission checks
2625 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002626 case SHELL_COMMAND_TRANSACTION: {
2627 int in = data.readFileDescriptor();
2628 int out = data.readFileDescriptor();
2629 int err = data.readFileDescriptor();
2630 int argc = data.readInt32();
2631 Vector<String16> args;
2632 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
2633 args.add(data.readString16());
2634 }
2635 sp<IBinder> unusedCallback;
2636 sp<IResultReceiver> resultReceiver;
2637 status_t status;
2638 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
2639 return status;
2640 }
2641 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
2642 return status;
2643 }
2644 status = shellCommand(in, out, err, args);
2645 if (resultReceiver != nullptr) {
2646 resultReceiver->send(status);
2647 }
2648 return NO_ERROR;
2649 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002650 }
2651
2652 return BnCameraService::onTransact(code, data, reply, flags);
2653}
2654
Mathias Agopian65ab4712010-07-14 17:59:35 -07002655// We share the media players for shutter and recording sound for all clients.
2656// A reference count is kept to determine when we will actually release the
2657// media players.
2658
Jaekyun Seokef498052018-03-23 13:09:44 +09002659sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
2660 sp<MediaPlayer> mp = new MediaPlayer();
2661 status_t error;
2662 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08002663 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09002664 error = mp->prepare();
2665 }
2666 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00002667 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09002668 mp->disconnect();
2669 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002670 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002671 }
2672 return mp;
2673}
2674
username5755fea2018-12-27 09:48:08 +08002675void CameraService::increaseSoundRef() {
2676 Mutex::Autolock lock(mSoundLock);
2677 mSoundRef++;
2678}
2679
2680void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002681 ATRACE_CALL();
2682
username5755fea2018-12-27 09:48:08 +08002683 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
2684 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
2685 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
2686 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
2687 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
2688 }
2689 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
2690 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
2691 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
2692 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002693 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08002694 }
2695 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
2696 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
2697 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
2698 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
2699 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002700 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002701}
2702
username5755fea2018-12-27 09:48:08 +08002703void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002704 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002705 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002706 if (--mSoundRef) return;
2707
2708 for (int i = 0; i < NUM_SOUNDS; i++) {
2709 if (mSoundPlayer[i] != 0) {
2710 mSoundPlayer[i]->disconnect();
2711 mSoundPlayer[i].clear();
2712 }
2713 }
2714}
2715
2716void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002717 ATRACE_CALL();
2718
Mathias Agopian65ab4712010-07-14 17:59:35 -07002719 LOG1("playSound(%d)", kind);
2720 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002721 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002722 sp<MediaPlayer> player = mSoundPlayer[kind];
2723 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08002724 player->seekTo(0);
2725 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002726 }
2727}
2728
2729// ----------------------------------------------------------------------------
2730
2731CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07002732 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002733 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09002734 const std::optional<String16>& clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002735 const String8& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07002736 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002737 int clientPid, uid_t clientUid,
2738 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002739 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08002740 IInterface::asBinder(cameraClient),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002741 clientPackageName, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07002742 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002743 clientPid, clientUid,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002744 servicePid),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002745 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08002746{
Jayant Chowdhary12361932018-08-27 14:46:13 -07002747 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002748 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002749
Igor Murashkin44cfcf02013-03-01 16:22:28 -08002750 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002751
username5755fea2018-12-27 09:48:08 +08002752 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002753
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002754 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002755}
2756
Mathias Agopian65ab4712010-07-14 17:59:35 -07002757// tear down the client
2758CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002759 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08002760 mDestructionStarted = true;
2761
username5755fea2018-12-27 09:48:08 +08002762 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002763 // unconditionally disconnect. function is idempotent
2764 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002765}
2766
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002767sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
2768
Igor Murashkin634a5152013-02-20 17:15:11 -08002769CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002770 const sp<IBinder>& remoteCallback,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09002771 const String16& clientPackageName, const std::optional<String16>& clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07002772 const String8& cameraIdStr, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002773 int clientPid, uid_t clientUid,
2774 int servicePid):
Emilian Peev8b64f282021-03-25 16:49:57 -07002775 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09002776 mClientPackageName(clientPackageName), mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002777 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002778 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07002779 mDisconnected(false), mUidIsTrusted(false),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002780 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002781 mRemoteBinder(remoteCallback)
Igor Murashkin634a5152013-02-20 17:15:11 -08002782{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002783 if (sCameraService == nullptr) {
2784 sCameraService = cameraService;
2785 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002786 mOpsActive = false;
Igor Murashkin634a5152013-02-20 17:15:11 -08002787 mDestructionStarted = false;
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08002788
2789 // In some cases the calling code has no access to the package it runs under.
2790 // For example, NDK camera API.
2791 // In this case we will get the packages for the calling UID and pick the first one
2792 // for attributing the app op. This will work correctly for runtime permissions
2793 // as for legacy apps we will toggle the app op for all packages in the UID.
2794 // The caveat is that the operation may be attributed to the wrong package and
2795 // stats based on app ops may be slightly off.
2796 if (mClientPackageName.size() <= 0) {
2797 sp<IServiceManager> sm = defaultServiceManager();
2798 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
2799 if (binder == 0) {
2800 ALOGE("Cannot get permission service");
2801 // Leave mClientPackageName unchanged (empty) and the further interaction
2802 // with camera will fail in BasicClient::startCameraOps
2803 return;
2804 }
2805
2806 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
2807 Vector<String16> packages;
2808
2809 permCtrl->getPackagesForUid(mClientUid, packages);
2810
2811 if (packages.isEmpty()) {
2812 ALOGE("No packages for calling UID");
2813 // Leave mClientPackageName unchanged (empty) and the further interaction
2814 // with camera will fail in BasicClient::startCameraOps
2815 return;
2816 }
2817 mClientPackageName = packages[0];
2818 }
Steven Moreland89a2c5c2020-01-31 15:02:25 -08002819 if (getCurrentServingCall() != BinderCallType::HWBINDER) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002820 mAppOpsManager = std::make_unique<AppOpsManager>();
2821 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07002822
2823 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08002824}
2825
2826CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002827 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08002828 mDestructionStarted = true;
2829}
2830
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002831binder::Status CameraService::BasicClient::disconnect() {
2832 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002833 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002834 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07002835 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07002836 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002837
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002838 sCameraService->removeByClient(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002839 sCameraService->logDisconnected(mCameraIdStr, mClientPid, String8(mClientPackageName));
Peter Kalauskasa29c1352018-10-10 12:05:42 -07002840 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
2841 mCameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002842
2843 sp<IBinder> remote = getRemote();
2844 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002845 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08002846 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002847
2848 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07002849 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002850 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
2851 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
2852 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002853
Igor Murashkincba2c162013-03-20 15:56:31 -07002854 // client shouldn't be able to call into us anymore
2855 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002856
2857 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08002858}
2859
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002860status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
2861 // No dumping of clients directly over Binder,
2862 // must go through CameraService::dump
2863 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07002864 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002865 return OK;
2866}
2867
Ruben Brunkcc776712015-02-17 20:18:47 -08002868String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002869 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08002870}
2871
Emilian Peev8b64f282021-03-25 16:49:57 -07002872int CameraService::BasicClient::getCameraFacing() const {
2873 return mCameraFacing;
2874}
2875
2876int CameraService::BasicClient::getCameraOrientation() const {
2877 return mOrientation;
2878}
Ruben Brunkcc776712015-02-17 20:18:47 -08002879
2880int CameraService::BasicClient::getClientPid() const {
2881 return mClientPid;
2882}
2883
Ruben Brunk6267b532015-04-30 17:44:07 -07002884uid_t CameraService::BasicClient::getClientUid() const {
2885 return mClientUid;
2886}
2887
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002888bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
2889 // Defaults to API2.
2890 return level == API_2;
2891}
2892
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002893status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002894 {
2895 Mutex::Autolock l(mAudioRestrictionLock);
2896 mAudioRestriction = mode;
2897 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002898 sCameraService->updateAudioRestriction();
2899 return OK;
2900}
2901
2902int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002903 return sCameraService->updateAudioRestriction();
2904}
2905
2906int32_t CameraService::BasicClient::getAudioRestriction() const {
2907 Mutex::Autolock l(mAudioRestrictionLock);
2908 return mAudioRestriction;
2909}
2910
2911bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
2912 switch (mode) {
2913 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
2914 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
2915 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
2916 return true;
2917 default:
2918 return false;
2919 }
2920}
2921
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002922status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002923 ATRACE_CALL();
2924
Igor Murashkine6800ce2013-03-04 17:25:57 -08002925 {
2926 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002927 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08002928 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002929 if (mAppOpsManager != nullptr) {
2930 // Notify app ops that the camera is not available
2931 mOpsCallback = new OpsCallback(this);
2932 int32_t res;
2933 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
2934 mClientPackageName, mOpsCallback);
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002935 res = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
2936 mClientPackageName, /*startIfModeDefault*/ false, mClientFeatureId,
2937 String16("start camera ") + String16(mCameraIdStr));
Igor Murashkine6800ce2013-03-04 17:25:57 -08002938
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002939 if (res == AppOpsManager::MODE_ERRORED) {
2940 ALOGI("Camera %s: Access for \"%s\" has been revoked",
2941 mCameraIdStr.string(), String8(mClientPackageName).string());
2942 return PERMISSION_DENIED;
2943 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002944
Shuzhen Wang2c656792020-04-13 17:36:49 -07002945 // If the calling Uid is trusted (a native service), the AppOpsManager could
2946 // return MODE_IGNORED. Do not treat such case as error.
2947 if (!mUidIsTrusted && res == AppOpsManager::MODE_IGNORED) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002948 ALOGI("Camera %s: Access for \"%s\" has been restricted",
2949 mCameraIdStr.string(), String8(mClientPackageName).string());
2950 // Return the same error as for device policy manager rejection
2951 return -EACCES;
2952 }
Svetoslav28e8ef72015-05-11 19:21:31 -07002953 }
2954
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002955 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002956
2957 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002958 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002959
Emilian Peev53722fa2019-02-22 17:47:20 -08002960 sCameraService->mUidPolicy->registerMonitorUid(mClientUid);
2961
Shuzhen Wang695044d2020-03-06 09:02:23 -08002962 // Notify listeners of camera open/close status
2963 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
2964
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002965 return OK;
2966}
2967
2968status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002969 ATRACE_CALL();
2970
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002971 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002972 if (mOpsActive) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002973 // Notify app ops that the camera is available again
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002974 if (mAppOpsManager != nullptr) {
2975 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002976 mClientPackageName, mClientFeatureId);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002977 mOpsActive = false;
2978 }
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002979 // This function is called when a client disconnects. This should
2980 // release the camera, but actually only if it was in a proper
2981 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002982 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002983 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002984
Ruben Brunkcc776712015-02-17 20:18:47 -08002985 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002986 sCameraService->updateStatus(StatusInternal::PRESENT,
2987 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002988 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002989 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002990 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
2991 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002992 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002993 mOpsCallback.clear();
2994
Emilian Peev53722fa2019-02-22 17:47:20 -08002995 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid);
2996
Shuzhen Wang695044d2020-03-06 09:02:23 -08002997 // Notify listeners of camera open/close status
2998 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
2999
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003000 return OK;
3001}
3002
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003003void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003004 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003005 if (mAppOpsManager == nullptr) {
3006 return;
3007 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003008 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003009 if (op != AppOpsManager::OP_CAMERA) {
3010 ALOGW("Unexpected app ops notification received: %d", op);
3011 return;
3012 }
3013
3014 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003015 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003016 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003017 ALOGV("checkOp returns: %d, %s ", res,
3018 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
3019 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
3020 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
3021 "UNKNOWN");
3022
Shuzhen Wang64900852021-02-05 09:03:29 -08003023 if (res == AppOpsManager::MODE_ERRORED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003024 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003025 String8(mClientPackageName).string());
Svet Ganova453d0d2018-01-11 15:37:58 -08003026 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08003027 } else if (res == AppOpsManager::MODE_IGNORED) {
3028 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
3029 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d",
3030 mCameraIdStr.string(), String8(mClientPackageName).string(),
3031 mUidIsTrusted, isUidActive);
3032 // If the calling Uid is trusted (a native service), or the client Uid is active (WAR for
3033 // b/175320666), the AppOpsManager could return MODE_IGNORED. Do not treat such cases as
3034 // error.
3035 if (!mUidIsTrusted && !isUidActive) {
3036 block();
3037 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003038 }
3039}
3040
Svet Ganova453d0d2018-01-11 15:37:58 -08003041void CameraService::BasicClient::block() {
3042 ATRACE_CALL();
3043
3044 // Reset the client PID to allow server-initiated disconnect,
3045 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003046 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08003047 CaptureResultExtras resultExtras; // a dummy result (invalid)
3048 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
3049 disconnect();
3050}
3051
Mathias Agopian65ab4712010-07-14 17:59:35 -07003052// ----------------------------------------------------------------------------
3053
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003054void CameraService::Client::notifyError(int32_t errorCode,
Jianing Weicb0652e2014-03-12 18:29:36 -07003055 const CaptureResultExtras& resultExtras) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08003056 (void) resultExtras;
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003057 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07003058 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
3059 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
3060 api1ErrorCode = CAMERA_ERROR_DISABLED;
3061 }
3062 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003063 } else {
3064 ALOGE("mRemoteCallback is NULL!!");
3065 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003066}
3067
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003068// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003069binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003070 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003071 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08003072}
3073
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003074bool CameraService::Client::canCastToApiClient(apiLevel level) const {
3075 return level == API_1;
3076}
3077
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003078CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
3079 mClient(client) {
3080}
3081
3082void CameraService::Client::OpsCallback::opChanged(int32_t op,
3083 const String16& packageName) {
3084 sp<BasicClient> client = mClient.promote();
3085 if (client != NULL) {
3086 client->opChanged(op, packageName);
3087 }
3088}
3089
Mathias Agopian65ab4712010-07-14 17:59:35 -07003090// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08003091// UidPolicy
3092// ----------------------------------------------------------------------------
3093
3094void CameraService::UidPolicy::registerSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003095 Mutex::Autolock _l(mUidLock);
3096
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003097 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07003098 status_t res = mAm.linkToDeath(this);
3099 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08003100 | ActivityManager::UID_OBSERVER_IDLE
Emilian Peev53722fa2019-02-22 17:47:20 -08003101 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganova453d0d2018-01-11 15:37:58 -08003102 ActivityManager::PROCESS_STATE_UNKNOWN,
3103 String16("cameraserver"));
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003104 if (res == OK) {
3105 mRegistered = true;
3106 ALOGV("UidPolicy: Registered with ActivityManager");
3107 }
Svet Ganova453d0d2018-01-11 15:37:58 -08003108}
3109
3110void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003111 Mutex::Autolock _l(mUidLock);
3112
Steven Moreland2f348142019-07-02 15:59:07 -07003113 mAm.unregisterUidObserver(this);
3114 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003115 mRegistered = false;
3116 mActiveUids.clear();
3117 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08003118}
3119
3120void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
3121 onUidIdle(uid, disabled);
3122}
3123
3124void CameraService::UidPolicy::onUidActive(uid_t uid) {
3125 Mutex::Autolock _l(mUidLock);
3126 mActiveUids.insert(uid);
3127}
3128
3129void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
3130 bool deleted = false;
3131 {
3132 Mutex::Autolock _l(mUidLock);
3133 if (mActiveUids.erase(uid) > 0) {
3134 deleted = true;
3135 }
3136 }
3137 if (deleted) {
3138 sp<CameraService> service = mService.promote();
3139 if (service != nullptr) {
3140 service->blockClientsForUid(uid);
3141 }
3142 }
3143}
3144
Emilian Peev53722fa2019-02-22 17:47:20 -08003145void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07003146 int64_t procStateSeq __unused, int32_t capability __unused) {
Emilian Peev53722fa2019-02-22 17:47:20 -08003147 bool procStateChange = false;
3148 {
3149 Mutex::Autolock _l(mUidLock);
3150 if ((mMonitoredUids.find(uid) != mMonitoredUids.end()) &&
3151 (mMonitoredUids[uid].first != procState)) {
3152 mMonitoredUids[uid].first = procState;
3153 procStateChange = true;
3154 }
3155 }
3156
3157 if (procStateChange) {
3158 sp<CameraService> service = mService.promote();
3159 if (service != nullptr) {
3160 service->notifyMonitoredUids();
3161 }
3162 }
3163}
3164
3165void CameraService::UidPolicy::registerMonitorUid(uid_t uid) {
3166 Mutex::Autolock _l(mUidLock);
3167 auto it = mMonitoredUids.find(uid);
3168 if (it != mMonitoredUids.end()) {
3169 it->second.second++;
3170 } else {
3171 mMonitoredUids.emplace(
3172 std::pair<uid_t, std::pair<int32_t, size_t>> (uid,
3173 std::pair<int32_t, size_t> (ActivityManager::PROCESS_STATE_NONEXISTENT, 1)));
3174 }
3175}
3176
3177void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid) {
3178 Mutex::Autolock _l(mUidLock);
3179 auto it = mMonitoredUids.find(uid);
3180 if (it != mMonitoredUids.end()) {
3181 it->second.second--;
3182 if (it->second.second == 0) {
3183 mMonitoredUids.erase(it);
3184 }
3185 } else {
3186 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
3187 }
3188}
3189
Svet Ganov7b4ab782018-03-25 12:48:10 -07003190bool CameraService::UidPolicy::isUidActive(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003191 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003192 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003193}
3194
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003195static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
3196static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003197
Svet Ganov7b4ab782018-03-25 12:48:10 -07003198bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003199 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003200 // If activity manager is unreachable, assume everything is active
3201 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003202 return true;
3203 }
3204 auto it = mOverrideUids.find(uid);
3205 if (it != mOverrideUids.end()) {
3206 return it->second;
3207 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003208 bool active = mActiveUids.find(uid) != mActiveUids.end();
3209 if (!active) {
3210 // We want active UIDs to always access camera with their first attempt since
3211 // there is no guarantee the app is robustly written and would retry getting
3212 // the camera on failure. The inverse case is not a problem as we would take
3213 // camera away soon once we get the callback that the uid is no longer active.
3214 ActivityManager am;
3215 // Okay to access with a lock held as UID changes are dispatched without
3216 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07003217 int64_t startTimeMillis = 0;
3218 do {
3219 // TODO: Fix this b/109950150!
3220 // Okay this is a hack. There is a race between the UID turning active and
3221 // activity being resumed. The proper fix is very risky, so we temporary add
3222 // some polling which should happen pretty rarely anyway as the race is hard
3223 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003224 active = mActiveUids.find(uid) != mActiveUids.end();
Hui Yu12c7ec72020-05-04 17:40:52 +00003225 if (!active) active = am.isUidActive(uid, callingPackage);
Svet Ganov94ec46f2018-06-08 15:03:46 -07003226 if (active) {
3227 break;
3228 }
3229 if (startTimeMillis <= 0) {
3230 startTimeMillis = uptimeMillis();
3231 }
3232 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003233 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003234 if (remainingTimeMillis <= 0) {
3235 break;
3236 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003237 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
3238
3239 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003240 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003241 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003242 } while (true);
3243
Svet Ganov7b4ab782018-03-25 12:48:10 -07003244 if (active) {
3245 // Now that we found out the UID is actually active, cache that
3246 mActiveUids.insert(uid);
3247 }
3248 }
3249 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08003250}
3251
Varun Shahb42f1eb2019-04-16 14:45:13 -07003252int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
3253 Mutex::Autolock _l(mUidLock);
3254 return getProcStateLocked(uid);
3255}
3256
3257int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
3258 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
3259 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
3260 procState = mMonitoredUids[uid].first;
3261 }
3262 return procState;
3263}
3264
Svet Ganov7b4ab782018-03-25 12:48:10 -07003265void CameraService::UidPolicy::UidPolicy::addOverrideUid(uid_t uid,
3266 String16 callingPackage, bool active) {
3267 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08003268}
3269
Svet Ganov7b4ab782018-03-25 12:48:10 -07003270void CameraService::UidPolicy::removeOverrideUid(uid_t uid, String16 callingPackage) {
3271 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08003272}
3273
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003274void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
3275 Mutex::Autolock _l(mUidLock);
3276 ALOGV("UidPolicy: ActivityManager has died");
3277 mRegistered = false;
3278 mActiveUids.clear();
3279}
3280
Svet Ganov7b4ab782018-03-25 12:48:10 -07003281void CameraService::UidPolicy::updateOverrideUid(uid_t uid, String16 callingPackage,
3282 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003283 bool wasActive = false;
3284 bool isActive = false;
3285 {
3286 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003287 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003288 mOverrideUids.erase(uid);
3289 if (insert) {
3290 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
3291 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003292 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003293 }
3294 if (wasActive != isActive && !isActive) {
3295 sp<CameraService> service = mService.promote();
3296 if (service != nullptr) {
3297 service->blockClientsForUid(uid);
3298 }
3299 }
3300}
3301
3302// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08003303// SensorPrivacyPolicy
3304// ----------------------------------------------------------------------------
3305void CameraService::SensorPrivacyPolicy::registerSelf() {
3306 Mutex::Autolock _l(mSensorPrivacyLock);
3307 if (mRegistered) {
3308 return;
3309 }
Steven Moreland3cf67172020-01-29 11:44:22 -08003310 mSpm.addSensorPrivacyListener(this);
3311 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
3312 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003313 if (res == OK) {
3314 mRegistered = true;
3315 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
3316 }
3317}
3318
Evan Severson190ad252021-01-07 20:37:15 -08003319status_t CameraService::SensorPrivacyPolicy::registerSelfForIndividual(int userId) {
3320 Mutex::Autolock _l(mSensorPrivacyLock);
3321 if (mRegistered) {
3322 return OK;
3323 }
3324
3325 status_t res = mSpm.addIndividualSensorPrivacyListener(userId,
3326 SensorPrivacyManager::INDIVIDUAL_SENSOR_CAMERA, this);
3327 if (res != OK) {
3328 ALOGE("Unable to register camera privacy listener: %s (%d)", strerror(-res), res);
3329 return res;
3330 }
3331
3332 res = mSpm.isIndividualSensorPrivacyEnabled(userId,
3333 SensorPrivacyManager::INDIVIDUAL_SENSOR_CAMERA, mSensorPrivacyEnabled);
3334 if (res != OK) {
3335 ALOGE("Unable to check camera privacy: %s (%d)", strerror(-res), res);
3336 return res;
3337 }
3338
3339 res = mSpm.linkToDeath(this);
3340 if (res != OK) {
3341 ALOGE("Register link to death failed for sensor privacy: %s (%d)", strerror(-res), res);
3342 return res;
3343 }
3344
3345 mRegistered = true;
Evan Seversondd51a012021-02-03 09:15:21 -08003346 mIsIndividual = true;
3347 mUserId = userId;
Evan Severson190ad252021-01-07 20:37:15 -08003348 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
3349 return OK;
3350}
3351
Michael Grooverd1d435a2018-12-18 17:39:42 -08003352void CameraService::SensorPrivacyPolicy::unregisterSelf() {
3353 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08003354 mSpm.removeSensorPrivacyListener(this);
3355 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003356 mRegistered = false;
3357 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
3358}
3359
3360bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
3361 Mutex::Autolock _l(mSensorPrivacyLock);
3362 return mSensorPrivacyEnabled;
3363}
3364
3365binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
3366 {
3367 Mutex::Autolock _l(mSensorPrivacyLock);
3368 mSensorPrivacyEnabled = enabled;
3369 }
3370 // if sensor privacy is enabled then block all clients from accessing the camera
Evan Severson190ad252021-01-07 20:37:15 -08003371 sp<CameraService> service = mService.promote();
3372 if (service != nullptr) {
Evan Seversondd51a012021-02-03 09:15:21 -08003373 if (mIsIndividual) {
3374 service->setMuteForAllClients(mUserId, enabled);
Evan Severson190ad252021-01-07 20:37:15 -08003375 } else {
3376 if (enabled) {
3377 service->blockAllClients();
3378 }
Michael Grooverd1d435a2018-12-18 17:39:42 -08003379 }
3380 }
3381 return binder::Status::ok();
3382}
3383
3384void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
3385 Mutex::Autolock _l(mSensorPrivacyLock);
3386 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
3387 mRegistered = false;
3388}
3389
3390// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003391// CameraState
3392// ----------------------------------------------------------------------------
3393
3394CameraService::CameraState::CameraState(const String8& id, int cost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003395 const std::set<String8>& conflicting, SystemCameraKind systemCameraKind) : mId(id),
3396 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
3397 mSystemCameraKind(systemCameraKind) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08003398
3399CameraService::CameraState::~CameraState() {}
3400
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003401CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003402 Mutex::Autolock lock(mStatusLock);
3403 return mStatus;
3404}
3405
Shuzhen Wang43858162020-01-10 13:42:15 -08003406std::vector<String8> CameraService::CameraState::getUnavailablePhysicalIds() const {
3407 Mutex::Autolock lock(mStatusLock);
3408 std::vector<String8> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
3409 return res;
3410}
3411
Ruben Brunkcc776712015-02-17 20:18:47 -08003412CameraParameters CameraService::CameraState::getShimParams() const {
3413 return mShimParams;
3414}
3415
3416void CameraService::CameraState::setShimParams(const CameraParameters& params) {
3417 mShimParams = params;
3418}
3419
3420int CameraService::CameraState::getCost() const {
3421 return mCost;
3422}
3423
3424std::set<String8> CameraService::CameraState::getConflicting() const {
3425 return mConflicting;
3426}
3427
3428String8 CameraService::CameraState::getId() const {
3429 return mId;
3430}
3431
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003432SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
3433 return mSystemCameraKind;
3434}
3435
Shuzhen Wang43858162020-01-10 13:42:15 -08003436bool CameraService::CameraState::addUnavailablePhysicalId(const String8& physicalId) {
3437 Mutex::Autolock lock(mStatusLock);
3438 auto result = mUnavailablePhysicalIds.insert(physicalId);
3439 return result.second;
3440}
3441
3442bool CameraService::CameraState::removeUnavailablePhysicalId(const String8& physicalId) {
3443 Mutex::Autolock lock(mStatusLock);
3444 auto count = mUnavailablePhysicalIds.erase(physicalId);
3445 return count > 0;
3446}
3447
Ruben Brunkcc776712015-02-17 20:18:47 -08003448// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07003449// ClientEventListener
3450// ----------------------------------------------------------------------------
3451
3452void CameraService::ClientEventListener::onClientAdded(
3453 const resource_policy::ClientDescriptor<String8,
3454 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003455 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003456 if (basicClient.get() != nullptr) {
3457 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3458 notifier.noteStartCamera(descriptor.getKey(),
3459 static_cast<int>(basicClient->getClientUid()));
3460 }
3461}
3462
3463void CameraService::ClientEventListener::onClientRemoved(
3464 const resource_policy::ClientDescriptor<String8,
3465 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003466 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003467 if (basicClient.get() != nullptr) {
3468 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3469 notifier.noteStopCamera(descriptor.getKey(),
3470 static_cast<int>(basicClient->getClientUid()));
3471 }
3472}
3473
3474
3475// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003476// CameraClientManager
3477// ----------------------------------------------------------------------------
3478
Ruben Brunk99e69712015-05-26 17:25:07 -07003479CameraService::CameraClientManager::CameraClientManager() {
3480 setListener(std::make_shared<ClientEventListener>());
3481}
3482
Ruben Brunkcc776712015-02-17 20:18:47 -08003483CameraService::CameraClientManager::~CameraClientManager() {}
3484
3485sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
3486 const String8& id) const {
3487 auto descriptor = get(id);
3488 if (descriptor == nullptr) {
3489 return sp<BasicClient>{nullptr};
3490 }
3491 return descriptor->getValue();
3492}
3493
3494String8 CameraService::CameraClientManager::toString() const {
3495 auto all = getAll();
3496 String8 ret("[");
3497 bool hasAny = false;
3498 for (auto& i : all) {
3499 hasAny = true;
3500 String8 key = i->getKey();
3501 int32_t cost = i->getCost();
3502 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00003503 int32_t score = i->getPriority().getScore();
3504 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08003505 auto conflicting = i->getConflicting();
3506 auto clientSp = i->getValue();
3507 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07003508 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08003509 if (clientSp.get() != nullptr) {
3510 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07003511 uid_t clientUid = clientSp->getClientUid();
3512 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003513 }
Emilian Peev8131a262017-02-01 12:33:43 +00003514 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
3515 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08003516
Ruben Brunk6267b532015-04-30 17:44:07 -07003517 if (clientSp.get() != nullptr) {
3518 ret.appendFormat("User Id: %d, ", clientUserId);
3519 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003520 if (packageName.size() != 0) {
3521 ret.appendFormat("Client Package Name: %s", packageName.string());
3522 }
3523
3524 ret.append(", Conflicting Client Devices: {");
3525 for (auto& j : conflicting) {
3526 ret.appendFormat("%s, ", j.string());
3527 }
3528 ret.append("})");
3529 }
3530 if (hasAny) ret.append("\n");
3531 ret.append("]\n");
3532 return ret;
3533}
3534
3535CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3536 const String8& key, const sp<BasicClient>& value, int32_t cost,
Emilian Peev8131a262017-02-01 12:33:43 +00003537 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
3538 int32_t state) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003539
Steven Moreland89a2c5c2020-01-31 15:02:25 -08003540 bool isVendorClient = getCurrentServingCall() == BinderCallType::HWBINDER;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003541 int32_t score_adj = isVendorClient ? kVendorClientScore : score;
3542 int32_t state_adj = isVendorClient ? kVendorClientState: state;
3543
Ruben Brunkcc776712015-02-17 20:18:47 -08003544 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003545 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj, isVendorClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08003546}
3547
3548CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3549 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
3550 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00003551 partial->getConflicting(), partial->getPriority().getScore(),
3552 partial->getOwnerId(), partial->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08003553}
3554
3555// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07003556
3557static const int kDumpLockRetries = 50;
3558static const int kDumpLockSleep = 60000;
3559
3560static bool tryLock(Mutex& mutex)
3561{
3562 bool locked = false;
3563 for (int i = 0; i < kDumpLockRetries; ++i) {
3564 if (mutex.tryLock() == NO_ERROR) {
3565 locked = true;
3566 break;
3567 }
3568 usleep(kDumpLockSleep);
3569 }
3570 return locked;
3571}
3572
3573status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003574 ATRACE_CALL();
3575
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003576 if (checkCallingPermission(sDumpPermission) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003577 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07003578 CameraThreadState::getCallingPid(),
3579 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003580 return NO_ERROR;
3581 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003582 bool locked = tryLock(mServiceLock);
3583 // failed to lock - CameraService is probably deadlocked
3584 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003585 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003586 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003587
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003588 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003589 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07003590
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003591 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003592 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08003593
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003594 if (locked) mServiceLock.unlock();
3595 return NO_ERROR;
3596 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003597 dprintf(fd, "\n== Service global info: ==\n\n");
3598 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003599 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07003600 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
3601 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003602 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
3603 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
3604 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003605 String8 activeClientString = mActiveClientManager.toString();
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003606 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
3607 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003608
3609 dumpEventLog(fd);
3610
3611 bool stateLocked = tryLock(mCameraStatesLock);
3612 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003613 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003614 }
3615
Emilian Peevbd8c5032018-02-14 23:05:40 +00003616 int argSize = args.size();
3617 for (int i = 0; i < argSize; i++) {
3618 if (args[i] == TagMonitor::kMonitorOption) {
3619 if (i + 1 < argSize) {
3620 mMonitorTags = String8(args[i + 1]);
3621 }
3622 break;
3623 }
3624 }
3625
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003626 for (auto& state : mCameraStates) {
3627 String8 cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003628
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003629 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003630
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003631 CameraParameters p = state.second->getShimParams();
3632 if (!p.isEmpty()) {
3633 dprintf(fd, " Camera1 API shim is using parameters:\n ");
3634 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003635 }
3636
3637 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08003638 if (clientDescriptor != nullptr) {
3639 dprintf(fd, " Device %s is open. Client instance dump:\n",
3640 cameraId.string());
3641 dprintf(fd, " Client priority score: %d state: %d\n",
3642 clientDescriptor->getPriority().getScore(),
3643 clientDescriptor->getPriority().getState());
3644 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
3645
3646 auto client = clientDescriptor->getValue();
3647 dprintf(fd, " Client package: %s\n",
3648 String8(client->getPackageName()).string());
3649
3650 client->dumpClient(fd, args);
3651 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003652 dprintf(fd, " Device %s is closed, no client instance\n",
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003653 cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003654 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003655
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003656 }
3657
3658 if (stateLocked) mCameraStatesLock.unlock();
3659
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003660 if (locked) mServiceLock.unlock();
3661
Emilian Peevf53f66e2017-04-11 14:29:43 +01003662 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003663
3664 dprintf(fd, "\n== Vendor tags: ==\n\n");
3665
3666 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
3667 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00003668 sp<VendorTagDescriptorCache> cache =
3669 VendorTagDescriptorCache::getGlobalVendorTagCache();
3670 if (cache == NULL) {
3671 dprintf(fd, "No vendor tags.\n");
3672 } else {
3673 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
3674 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003675 } else {
3676 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
3677 }
3678
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003679 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003680 dprintf(fd, "\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003681 camera3::CameraTraces::dump(fd, args);
3682
3683 // Process dump arguments, if any
3684 int n = args.size();
3685 String16 verboseOption("-v");
3686 String16 unreachableOption("--unreachable");
3687 for (int i = 0; i < n; i++) {
3688 if (args[i] == verboseOption) {
3689 // change logging level
3690 if (i + 1 >= n) continue;
3691 String8 levelStr(args[i+1]);
3692 int level = atoi(levelStr.string());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003693 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003694 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003695 } else if (args[i] == unreachableOption) {
3696 // Dump memory analysis
3697 // TODO - should limit be an argument parameter?
3698 UnreachableMemoryInfo info;
3699 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
3700 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003701 dprintf(fd, "\n== Unable to dump unreachable memory. "
3702 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003703 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003704 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003705 std::string s = info.ToString(/*log_contents*/ true);
3706 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003707 }
3708 }
3709 }
3710 return NO_ERROR;
3711}
3712
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003713void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003714 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003715
3716 Mutex::Autolock l(mLogLock);
3717 for (const auto& msg : mEventLog) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003718 dprintf(fd, " %s\n", msg.string());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003719 }
3720
3721 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003722 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003723 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003724 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003725 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003726 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003727}
3728
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003729void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003730 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003731 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
3732 if (mTorchClientMap[i] == who) {
3733 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003734 String8 cameraId = mTorchClientMap.keyAt(i);
3735 status_t res = mFlashlight->setTorchMode(cameraId, false);
3736 if (res) {
3737 ALOGE("%s: torch client died but couldn't turn off torch: "
3738 "%s (%d)", __FUNCTION__, strerror(-res), res);
3739 return;
3740 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003741 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003742 break;
3743 }
3744 }
3745}
3746
Ruben Brunkcc776712015-02-17 20:18:47 -08003747/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003748
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003749 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07003750 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
3751 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003752 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003753 // PID here is approximate and can be wrong.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003754 logClientDied(CameraThreadState::getCallingPid(), String8("Binder died unexpectedly"));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003755
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003756 // check torch client
3757 handleTorchClientBinderDied(who);
3758
3759 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08003760 if(!evictClientIdByRemote(who)) {
3761 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003762 return;
3763 }
3764
Ruben Brunkcc776712015-02-17 20:18:47 -08003765 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
3766 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003767}
3768
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003769void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003770 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08003771}
3772
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003773void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
3774 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003775 // Do not lock mServiceLock here or can get into a deadlock from
3776 // connect() -> disconnect -> updateStatus
3777
3778 auto state = getCameraState(cameraId);
3779
3780 if (state == nullptr) {
3781 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
3782 cameraId.string());
3783 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07003784 }
3785
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003786 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
3787 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3788 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3789 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
3790 return;
3791 }
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003792 bool supportsHAL3 = false;
3793 // supportsCameraApi also holds mInterfaceMutex, we can't call it in the
3794 // HIDL onStatusChanged wrapper call (we'll hold mStatusListenerLock and
3795 // mInterfaceMutex together, which can lead to deadlocks)
3796 binder::Status sRet =
3797 supportsCameraApi(String16(cameraId), hardware::ICameraService::API_VERSION_2,
3798 &supportsHAL3);
3799 if (!sRet.isOk()) {
3800 ALOGW("%s: Failed to determine if device supports HAL3 %s, supportsCameraApi call failed",
3801 __FUNCTION__, cameraId.string());
3802 return;
3803 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003804
3805 // Collect the logical cameras without holding mStatusLock in updateStatus
3806 // as that can lead to a deadlock(b/162192331).
3807 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08003808 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08003809 // of the listeners with both the mStatusLock and mStatusListenerLock held
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003810 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind, &supportsHAL3,
3811 &logicalCameraIds]
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003812 (const String8& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003813
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003814 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003815 // Update torch status if it has a flash unit.
3816 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003817 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003818 if (getTorchStatusLocked(cameraId, &torchStatus) !=
3819 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003820 TorchModeStatus newTorchStatus =
3821 status == StatusInternal::PRESENT ?
3822 TorchModeStatus::AVAILABLE_OFF :
3823 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003824 if (torchStatus != newTorchStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003825 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003826 }
3827 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003828 }
3829
3830 Mutex::Autolock lock(mStatusListenerLock);
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003831 notifyPhysicalCameraStatusLocked(mapToInterface(status), String16(cameraId),
3832 logicalCameraIds, deviceKind);
Shuzhen Wang43858162020-01-10 13:42:15 -08003833
Ruben Brunkcc776712015-02-17 20:18:47 -08003834 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003835 bool isVendorListener = listener->isVendorListener();
3836 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
3837 listener->getListenerPid(), listener->getListenerUid()) ||
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07003838 (isVendorListener && !supportsHAL3)) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003839 ALOGV("Skipping discovery callback for system-only camera/HAL1 device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003840 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003841 continue;
3842 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003843 listener->getListener()->onStatusChanged(mapToInterface(status),
Emilian Peev53722fa2019-02-22 17:47:20 -08003844 String16(cameraId));
Ruben Brunkcc776712015-02-17 20:18:47 -08003845 }
3846 });
Igor Murashkincba2c162013-03-20 15:56:31 -07003847}
3848
Shuzhen Wang695044d2020-03-06 09:02:23 -08003849void CameraService::updateOpenCloseStatus(const String8& cameraId, bool open,
3850 const String16& clientPackageName) {
3851 Mutex::Autolock lock(mStatusListenerLock);
3852
3853 for (const auto& it : mListenerList) {
3854 if (!it->isOpenCloseCallbackAllowed()) {
3855 continue;
3856 }
3857
3858 binder::Status ret;
3859 String16 cameraId64(cameraId);
3860 if (open) {
3861 ret = it->getListener()->onCameraOpened(cameraId64, clientPackageName);
3862 } else {
3863 ret = it->getListener()->onCameraClosed(cameraId64);
3864 }
3865 if (!ret.isOk()) {
3866 ALOGE("%s: Failed to trigger onCameraOpened/onCameraClosed callback: %d", __FUNCTION__,
3867 ret.exceptionCode());
3868 }
3869 }
3870}
3871
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003872template<class Func>
3873void CameraService::CameraState::updateStatus(StatusInternal status,
3874 const String8& cameraId,
3875 std::initializer_list<StatusInternal> rejectSourceStates,
3876 Func onStatusUpdatedLocked) {
3877 Mutex::Autolock lock(mStatusLock);
3878 StatusInternal oldStatus = mStatus;
3879 mStatus = status;
3880
3881 if (oldStatus == status) {
3882 return;
3883 }
3884
3885 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
3886 cameraId.string(), oldStatus, status);
3887
3888 if (oldStatus == StatusInternal::NOT_PRESENT &&
3889 (status != StatusInternal::PRESENT &&
3890 status != StatusInternal::ENUMERATING)) {
3891
3892 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
3893 __FUNCTION__);
3894 mStatus = oldStatus;
3895 return;
3896 }
3897
3898 /**
3899 * Sometimes we want to conditionally do a transition.
3900 * For example if a client disconnects, we want to go to PRESENT
3901 * only if we weren't already in NOT_PRESENT or ENUMERATING.
3902 */
3903 for (auto& rejectStatus : rejectSourceStates) {
3904 if (oldStatus == rejectStatus) {
3905 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
3906 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
3907 mStatus = oldStatus;
3908 return;
3909 }
3910 }
3911
3912 onStatusUpdatedLocked(cameraId, status);
3913}
3914
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003915status_t CameraService::getTorchStatusLocked(
3916 const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003917 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003918 if (!status) {
3919 return BAD_VALUE;
3920 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003921 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3922 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003923 // invalid camera ID or the camera doesn't have a flash unit
3924 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003925 }
3926
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003927 *status = mTorchStatusMap.valueAt(index);
3928 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003929}
3930
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003931status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003932 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003933 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3934 if (index == NAME_NOT_FOUND) {
3935 return BAD_VALUE;
3936 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003937 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003938
3939 return OK;
3940}
3941
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003942std::list<String16> CameraService::getLogicalCameras(
3943 const String8& physicalCameraId) {
3944 std::list<String16> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08003945 Mutex::Autolock lock(mCameraStatesLock);
3946 for (const auto& state : mCameraStates) {
3947 std::vector<std::string> physicalCameraIds;
3948 if (!mCameraProviderManager->isLogicalCamera(state.first.c_str(), &physicalCameraIds)) {
3949 // This is not a logical multi-camera.
3950 continue;
3951 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003952 if (std::find(physicalCameraIds.begin(), physicalCameraIds.end(), physicalCameraId.c_str())
Shuzhen Wang43858162020-01-10 13:42:15 -08003953 == physicalCameraIds.end()) {
3954 // cameraId is not a physical camera of this logical multi-camera.
3955 continue;
3956 }
3957
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003958 retList.emplace_back(String16(state.first));
3959 }
3960 return retList;
3961}
3962
3963void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
3964 const String16& physicalCameraId, const std::list<String16>& logicalCameraIds,
3965 SystemCameraKind deviceKind) {
3966 // mStatusListenerLock is expected to be locked
3967 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08003968 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003969 // Note: we check only the deviceKind of the physical camera id
3970 // since, logical camera ids and their physical camera ids are
3971 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07003972 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
3973 listener->getListenerPid(), listener->getListenerUid())) {
3974 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003975 String8(physicalCameraId).c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07003976 continue;
3977 }
Shuzhen Wang43858162020-01-10 13:42:15 -08003978 listener->getListener()->onPhysicalCameraStatusChanged(status,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003979 logicalCameraId, physicalCameraId);
Shuzhen Wang43858162020-01-10 13:42:15 -08003980 }
3981 }
3982}
3983
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003984
Svet Ganova453d0d2018-01-11 15:37:58 -08003985void CameraService::blockClientsForUid(uid_t uid) {
3986 const auto clients = mActiveClientManager.getAll();
3987 for (auto& current : clients) {
3988 if (current != nullptr) {
3989 const auto basicClient = current->getValue();
3990 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
3991 basicClient->block();
3992 }
3993 }
3994 }
3995}
3996
Michael Grooverd1d435a2018-12-18 17:39:42 -08003997void CameraService::blockAllClients() {
3998 const auto clients = mActiveClientManager.getAll();
3999 for (auto& current : clients) {
4000 if (current != nullptr) {
4001 const auto basicClient = current->getValue();
4002 if (basicClient.get() != nullptr) {
4003 basicClient->block();
4004 }
4005 }
4006 }
4007}
4008
Evan Severson190ad252021-01-07 20:37:15 -08004009void CameraService::setMuteForAllClients(userid_t userId, bool enabled) {
4010 const auto clients = mActiveClientManager.getAll();
4011 for (auto& current : clients) {
4012 if (current != nullptr) {
4013 const auto basicClient = current->getValue();
4014 if (basicClient.get() != nullptr
4015 && multiuser_get_user_id(basicClient->getClientUid()) == userId) {
4016 basicClient->setCameraMute(enabled);
4017 }
4018 }
4019 }
4020}
4021
Svet Ganova453d0d2018-01-11 15:37:58 -08004022// NOTE: This is a remote API - make sure all args are validated
4023status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
4024 if (!checkCallingPermission(sManageCameraPermission, nullptr, nullptr)) {
4025 return PERMISSION_DENIED;
4026 }
4027 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
4028 return BAD_VALUE;
4029 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004030 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004031 return handleSetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07004032 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004033 return handleResetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07004034 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004035 return handleGetUidState(args, out, err);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004036 } else if (args.size() >= 2 && args[0] == String16("set-rotate-and-crop")) {
4037 return handleSetRotateAndCrop(args);
4038 } else if (args.size() >= 1 && args[0] == String16("get-rotate-and-crop")) {
4039 return handleGetRotateAndCrop(out);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004040 } else if (args.size() >= 2 && args[0] == String16("set-image-dump-mask")) {
4041 return handleSetImageDumpMask(args);
4042 } else if (args.size() >= 1 && args[0] == String16("get-image-dump-mask")) {
4043 return handleGetImageDumpMask(out);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004044 } else if (args.size() >= 2 && args[0] == String16("set-camera-mute")) {
4045 return handleSetCameraMute(args);
Svet Ganova453d0d2018-01-11 15:37:58 -08004046 } else if (args.size() == 1 && args[0] == String16("help")) {
4047 printHelp(out);
4048 return NO_ERROR;
4049 }
4050 printHelp(err);
4051 return BAD_VALUE;
4052}
4053
4054status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004055 String16 packageName = args[1];
4056
Svet Ganova453d0d2018-01-11 15:37:58 -08004057 bool active = false;
4058 if (args[2] == String16("active")) {
4059 active = true;
4060 } else if ((args[2] != String16("idle"))) {
4061 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
4062 return BAD_VALUE;
4063 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004064
4065 int userId = 0;
4066 if (args.size() >= 5 && args[3] == String16("--user")) {
4067 userId = atoi(String8(args[4]));
4068 }
4069
4070 uid_t uid;
4071 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
4072 return BAD_VALUE;
4073 }
4074
4075 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08004076 return NO_ERROR;
4077}
4078
4079status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004080 String16 packageName = args[1];
4081
4082 int userId = 0;
4083 if (args.size() >= 4 && args[2] == String16("--user")) {
4084 userId = atoi(String8(args[3]));
4085 }
4086
4087 uid_t uid;
4088 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004089 return BAD_VALUE;
4090 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004091
4092 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08004093 return NO_ERROR;
4094}
4095
4096status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004097 String16 packageName = args[1];
4098
4099 int userId = 0;
4100 if (args.size() >= 4 && args[2] == String16("--user")) {
4101 userId = atoi(String8(args[3]));
4102 }
4103
4104 uid_t uid;
4105 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004106 return BAD_VALUE;
4107 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004108
4109 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004110 return dprintf(out, "active\n");
4111 } else {
4112 return dprintf(out, "idle\n");
4113 }
4114}
4115
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004116status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
4117 int rotateValue = atoi(String8(args[1]));
4118 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
4119 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
4120 Mutex::Autolock lock(mServiceLock);
4121
4122 mOverrideRotateAndCropMode = rotateValue;
4123
4124 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
4125
4126 const auto clients = mActiveClientManager.getAll();
4127 for (auto& current : clients) {
4128 if (current != nullptr) {
4129 const auto basicClient = current->getValue();
4130 if (basicClient.get() != nullptr) {
4131 basicClient->setRotateAndCropOverride(rotateValue);
4132 }
4133 }
4134 }
4135
4136 return OK;
4137}
4138
4139status_t CameraService::handleGetRotateAndCrop(int out) {
4140 Mutex::Autolock lock(mServiceLock);
4141
4142 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
4143}
4144
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004145status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
4146 char *endPtr;
4147 errno = 0;
4148 String8 maskString8 = String8(args[1]);
4149 long maskValue = strtol(maskString8.c_str(), &endPtr, 10);
4150
4151 if (errno != 0) return BAD_VALUE;
4152 if (endPtr != maskString8.c_str() + maskString8.size()) return BAD_VALUE;
4153 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
4154
4155 Mutex::Autolock lock(mServiceLock);
4156
4157 mImageDumpMask = maskValue;
4158
4159 return OK;
4160}
4161
4162status_t CameraService::handleGetImageDumpMask(int out) {
4163 Mutex::Autolock lock(mServiceLock);
4164
4165 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
4166}
4167
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004168status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
4169 int muteValue = strtol(String8(args[1]), nullptr, 10);
4170 if (errno != 0) return BAD_VALUE;
4171
4172 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
4173 Mutex::Autolock lock(mServiceLock);
4174
4175 mOverrideCameraMuteMode = (muteValue == 1);
4176
4177 const auto clients = mActiveClientManager.getAll();
4178 for (auto& current : clients) {
4179 if (current != nullptr) {
4180 const auto basicClient = current->getValue();
4181 if (basicClient.get() != nullptr) {
4182 if (basicClient->supportsCameraMute()) {
4183 basicClient->setCameraMute(mOverrideCameraMuteMode);
4184 }
4185 }
4186 }
4187 }
4188
4189 return OK;
4190}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004191
Svet Ganova453d0d2018-01-11 15:37:58 -08004192status_t CameraService::printHelp(int out) {
4193 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07004194 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
4195 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
4196 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004197 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
4198 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
4199 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004200 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
4201 " Valid values 0=OFF, 1=ON for JPEG\n"
4202 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004203 " set-camera-mute <0/1> enable or disable camera muting\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08004204 " help print this message\n");
4205}
4206
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004207int32_t CameraService::updateAudioRestriction() {
4208 Mutex::Autolock lock(mServiceLock);
4209 return updateAudioRestrictionLocked();
4210}
4211
4212int32_t CameraService::updateAudioRestrictionLocked() {
4213 int32_t mode = 0;
4214 // iterate through all active client
4215 for (const auto& i : mActiveClientManager.getAll()) {
4216 const auto clientSp = i->getValue();
4217 mode |= clientSp->getAudioRestriction();
4218 }
4219
4220 bool modeChanged = (mAudioRestriction != mode);
4221 mAudioRestriction = mode;
4222 if (modeChanged) {
4223 mAppOps.setCameraAudioRestriction(mode);
4224 }
4225 return mode;
4226}
4227
Evan Severson190ad252021-01-07 20:37:15 -08004228bool CameraService::isUserSensorPrivacyEnabledForUid(uid_t uid) {
4229 userid_t userId = multiuser_get_user_id(uid);
4230 if (mCameraSensorPrivacyPolicies.find(userId) == mCameraSensorPrivacyPolicies.end()) {
4231 sp<SensorPrivacyPolicy> userPolicy = new SensorPrivacyPolicy(this);
4232 if (userPolicy->registerSelfForIndividual(userId) != OK) {
4233 return false;
4234 }
4235 mCameraSensorPrivacyPolicies[userId] = userPolicy;
4236 }
4237 return mCameraSensorPrivacyPolicies[userId]->isSensorPrivacyEnabled();
4238}
4239
Mathias Agopian65ab4712010-07-14 17:59:35 -07004240}; // namespace android