blob: 93c3656bd8be71a38c364e714c545851a8c20621 [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();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700245}
246
Emilian Peevaee727d2017-05-04 16:35:48 +0100247void CameraService::onNewProviderRegistered() {
248 enumerateProviders();
249}
250
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700251void CameraService::filterAPI1SystemCameraLocked(
252 const std::vector<std::string> &normalDeviceIds) {
253 mNormalDeviceIdsWithoutSystemCamera.clear();
254 for (auto &deviceId : normalDeviceIds) {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700255 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
256 if (getSystemCameraKind(String8(deviceId.c_str()), &deviceKind) != OK) {
257 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, deviceId.c_str());
258 continue;
259 }
260 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700261 // All system camera ids will necessarily come after public camera
262 // device ids as per the HAL interface contract.
263 break;
264 }
265 mNormalDeviceIdsWithoutSystemCamera.push_back(deviceId);
266 }
267 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
268 mNormalDeviceIdsWithoutSystemCamera.size());
269}
270
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700271status_t CameraService::getSystemCameraKind(const String8& cameraId, SystemCameraKind *kind) const {
272 auto state = getCameraState(cameraId);
273 if (state != nullptr) {
274 *kind = state->getSystemCameraKind();
275 return OK;
276 }
277 // Hidden physical camera ids won't have CameraState
278 return mCameraProviderManager->getSystemCameraKind(cameraId.c_str(), kind);
279}
280
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800281void CameraService::updateCameraNumAndIds() {
282 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700283 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
284 // Excludes hidden secure cameras
285 mNumberOfCameras =
286 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
287 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800288 mNormalDeviceIds =
289 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700290 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800291}
292
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100293void CameraService::addStates(const String8 id) {
294 std::string cameraId(id.c_str());
295 hardware::camera::common::V1_0::CameraResourceCost cost;
296 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700297 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100298 if (res != OK) {
299 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
300 return;
301 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700302 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
303 if (res != OK) {
304 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
305 return;
306 }
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100307 std::set<String8> conflicting;
308 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
309 conflicting.emplace(String8(cost.conflictingDevices[i].c_str()));
310 }
311
312 {
313 Mutex::Autolock lock(mCameraStatesLock);
314 mCameraStates.emplace(id, std::make_shared<CameraState>(id, cost.resourceCost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700315 conflicting, deviceKind));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100316 }
317
318 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100319 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100320 mTorchStatusMap.add(id, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800321
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700322 broadcastTorchModeStatus(id, TorchModeStatus::AVAILABLE_OFF, deviceKind);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100323 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800324
325 updateCameraNumAndIds();
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100326 logDeviceAdded(id, "Device added");
327}
328
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100329void CameraService::removeStates(const String8 id) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800330 updateCameraNumAndIds();
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100331 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100332 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100333 mTorchStatusMap.removeItem(id);
334 }
335
336 {
337 Mutex::Autolock lock(mCameraStatesLock);
338 mCameraStates.erase(id);
339 }
340}
341
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800342void CameraService::onDeviceStatusChanged(const String8& id,
343 CameraDeviceStatus newHalStatus) {
344 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
345 id.string(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700346
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800347 StatusInternal newStatus = mapToInternal(newHalStatus);
348
Ruben Brunkcc776712015-02-17 20:18:47 -0800349 std::shared_ptr<CameraState> state = getCameraState(id);
350
351 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700352 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100353 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700354 __FUNCTION__, id.string());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100355
356 // First add as absent to make sure clients are notified below
357 addStates(id);
358
359 updateStatus(newStatus, id);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700360 } else {
361 ALOGE("%s: Bad camera ID %s", __FUNCTION__, id.string());
362 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700363 return;
364 }
365
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800366 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800367
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800368 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800369 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700370 return;
371 }
372
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800373 if (newStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700374 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
375 newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800376
377 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
378 // to this device until the status changes
379 updateStatus(StatusInternal::NOT_PRESENT, id);
380
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800381 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700382 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800383 // Don't do this in updateStatus to avoid deadlock over mServiceLock
384 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700385
Ruben Brunkcc776712015-02-17 20:18:47 -0800386 // Remove cached shim parameters
387 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700388
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800389 // Remove online as well as offline client from the list of active clients,
390 // if they are present
391 clientToDisconnectOnline = removeClientLocked(id);
392 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + id);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700393 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800394
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800395 disconnectClient(id, clientToDisconnectOnline);
396 disconnectClient(kOfflineDevice + id, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700397
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100398 removeStates(id);
Ruben Brunkcc776712015-02-17 20:18:47 -0800399 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800400 if (oldStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700401 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
402 newStatus));
403 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800404 updateStatus(newStatus, id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700405 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800406}
Igor Murashkincba2c162013-03-20 15:56:31 -0700407
Shuzhen Wang43858162020-01-10 13:42:15 -0800408void CameraService::onDeviceStatusChanged(const String8& id,
409 const String8& physicalId,
410 CameraDeviceStatus newHalStatus) {
411 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
412 __FUNCTION__, id.string(), physicalId.string(), newHalStatus);
413
414 StatusInternal newStatus = mapToInternal(newHalStatus);
415
416 std::shared_ptr<CameraState> state = getCameraState(id);
417
418 if (state == nullptr) {
419 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
420 __FUNCTION__, id.string(), physicalId.string());
421 return;
422 }
423
424 StatusInternal logicalCameraStatus = state->getStatus();
425 if (logicalCameraStatus != StatusInternal::PRESENT &&
426 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
427 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
428 __FUNCTION__, physicalId.string(), newHalStatus, logicalCameraStatus);
429 return;
430 }
431
432 bool updated = false;
433 if (newStatus == StatusInternal::PRESENT) {
434 updated = state->removeUnavailablePhysicalId(physicalId);
435 } else {
436 updated = state->addUnavailablePhysicalId(physicalId);
437 }
438
439 if (updated) {
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800440 String8 idCombo = id + " : " + physicalId;
441 if (newStatus == StatusInternal::PRESENT) {
442 logDeviceAdded(idCombo,
443 String8::format("Device status changed to %d", newStatus));
444 } else {
445 logDeviceRemoved(idCombo,
446 String8::format("Device status changed to %d", newStatus));
447 }
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700448 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
449 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
450 if (getSystemCameraKind(id, &deviceKind) != OK) {
451 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.string());
452 return;
453 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800454 String16 id16(id), physicalId16(physicalId);
455 Mutex::Autolock lock(mStatusListenerLock);
456 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700457 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
458 listener->getListenerPid(), listener->getListenerUid())) {
459 ALOGV("Skipping discovery callback for system-only camera device %s",
460 id.c_str());
461 continue;
462 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800463 listener->getListener()->onPhysicalCameraStatusChanged(mapToInterface(newStatus),
464 id16, physicalId16);
465 }
466 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700467}
468
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800469void CameraService::disconnectClient(const String8& id, sp<BasicClient> clientToDisconnect) {
470 if (clientToDisconnect.get() != nullptr) {
471 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
472 __FUNCTION__, id.string());
473 // Notify the client of disconnection
474 clientToDisconnect->notifyError(
475 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
476 CaptureResultExtras{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800477 clientToDisconnect->disconnect();
478 }
479}
480
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800481void CameraService::onTorchStatusChanged(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800482 TorchModeStatus newStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700483 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
484 status_t res = getSystemCameraKind(cameraId, &systemCameraKind);
485 if (res != OK) {
486 ALOGE("%s: Could not get system camera kind for camera id %s", __FUNCTION__,
487 cameraId.string());
488 return;
489 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800490 Mutex::Autolock al(mTorchStatusMutex);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700491 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800492}
493
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800494void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700495 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800496 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
497 __FUNCTION__, cameraId.string(), newStatus);
498
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800499 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800500 status_t res = getTorchStatusLocked(cameraId, &status);
501 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700502 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
503 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800504 return;
505 }
506 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800507 return;
508 }
509
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800510 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800511 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800512 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
513 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800514 return;
515 }
516
Ruben Brunkcc776712015-02-17 20:18:47 -0800517 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700518 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700519 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700520 auto iter = mTorchUidMap.find(cameraId);
521 if (iter != mTorchUidMap.end()) {
522 int oldUid = iter->second.second;
523 int newUid = iter->second.first;
524 BatteryNotifier& notifier(BatteryNotifier::getInstance());
525 if (oldUid != newUid) {
526 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800527 if (status == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700528 notifier.noteFlashlightOff(cameraId, oldUid);
529 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800530 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700531 notifier.noteFlashlightOn(cameraId, newUid);
532 }
533 iter->second.second = newUid;
534 } else {
535 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800536 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700537 notifier.noteFlashlightOn(cameraId, oldUid);
538 } else {
539 notifier.noteFlashlightOff(cameraId, oldUid);
540 }
541 }
542 }
543 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700544 broadcastTorchModeStatus(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800545}
546
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700547static bool hasPermissionsForSystemCamera(int callingPid, int callingUid) {
548 return checkPermission(sSystemCameraPermission, callingPid, callingUid) &&
549 checkPermission(sCameraPermission, callingPid, callingUid);
550}
551
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800552Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700553 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100554 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700555 bool hasSystemCameraPermissions =
556 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
557 CameraThreadState::getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700558 switch (type) {
559 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700560 if (hasSystemCameraPermissions) {
561 *numCameras = static_cast<int>(mNormalDeviceIds.size());
562 } else {
563 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
564 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800565 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700566 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700567 if (hasSystemCameraPermissions) {
568 *numCameras = mNumberOfCameras;
569 } else {
570 *numCameras = mNumberOfCamerasWithoutSystemCamera;
571 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800572 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700573 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800574 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700575 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800576 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
577 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700578 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800579 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700580}
581
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800582Status CameraService::getCameraInfo(int cameraId,
583 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700584 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100585 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700586 std::string cameraIdStr = cameraIdIntToStrLocked(cameraId);
587 if (shouldRejectSystemCameraConnection(String8(cameraIdStr.c_str()))) {
588 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
589 "characteristics for system only device %s: ", cameraIdStr.c_str());
590 }
Emilian Peevaee727d2017-05-04 16:35:48 +0100591
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800592 if (!mInitialized) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800593 return STATUS_ERROR(ERROR_DISCONNECTED,
594 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -0700595 }
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700596 bool hasSystemCameraPermissions =
597 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
598 CameraThreadState::getCallingUid());
599 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
600 if (hasSystemCameraPermissions) {
601 cameraIdBound = mNumberOfCameras;
602 }
603 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800604 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
605 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700606 }
607
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800608 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800609 status_t err = mCameraProviderManager->getCameraInfo(
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700610 cameraIdStr.c_str(), cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100611 if (err != OK) {
612 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
613 "Error retrieving camera info from device %d: %s (%d)", cameraId,
614 strerror(-err), err);
Ruben Brunkcc776712015-02-17 20:18:47 -0800615 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100616
Ruben Brunkcc776712015-02-17 20:18:47 -0800617 return ret;
618}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700619
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800620std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700621 const std::vector<std::string> *deviceIds = &mNormalDeviceIdsWithoutSystemCamera;
622 auto callingPid = CameraThreadState::getCallingPid();
623 auto callingUid = CameraThreadState::getCallingUid();
624 if (checkPermission(sSystemCameraPermission, callingPid, callingUid) ||
625 getpid() == callingPid) {
626 deviceIds = &mNormalDeviceIds;
627 }
628 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(deviceIds->size())) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800629 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700630 __FUNCTION__, cameraIdInt, deviceIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800631 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800632 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800633
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700634 return (*deviceIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800635}
636
637String8 CameraService::cameraIdIntToStr(int cameraIdInt) {
638 Mutex::Autolock lock(mServiceLock);
639 return String8(cameraIdIntToStrLocked(cameraIdInt).c_str());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800640}
641
642Status CameraService::getCameraCharacteristics(const String16& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800643 CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700644 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700645 if (!cameraInfo) {
646 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800647 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -0700648 }
649
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800650 if (!mInitialized) {
651 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800652 return STATUS_ERROR(ERROR_DISCONNECTED,
653 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -0700654 }
655
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700656 if (shouldRejectSystemCameraConnection(String8(cameraId))) {
657 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
658 "characteristics for system only device %s: ", String8(cameraId).string());
659 }
660
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800661 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800662
Emilian Peevf53f66e2017-04-11 14:29:43 +0100663 status_t res = mCameraProviderManager->getCameraCharacteristics(
664 String8(cameraId).string(), cameraInfo);
665 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700666 if (res == NAME_NOT_FOUND) {
667 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
668 "characteristics for unknown device %s: %s (%d)", String8(cameraId).string(),
669 strerror(-res), res);
670 } else {
671 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
672 "characteristics for device %s: %s (%d)", String8(cameraId).string(),
673 strerror(-res), res);
674 }
Ruben Brunkb2119af2014-05-09 19:57:56 -0700675 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700676 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
677 if (getSystemCameraKind(String8(cameraId), &deviceKind) != OK) {
678 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, String8(cameraId).string());
679 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera kind "
680 "for device %s", String8(cameraId).string());
681 }
Jayant Chowdhary12361932018-08-27 14:46:13 -0700682 int callingPid = CameraThreadState::getCallingPid();
683 int callingUid = CameraThreadState::getCallingUid();
Emilian Peeve20c6372018-08-14 18:45:53 +0100684 std::vector<int32_t> tagsRemoved;
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700685 // If it's not calling from cameraserver, check the permission only if
686 // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
687 // it would've already been checked in shouldRejectSystemCameraConnection.
Emilian Peeve20c6372018-08-14 18:45:53 +0100688 if ((callingPid != getpid()) &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700689 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700690 !checkPermission(sCameraPermission, callingPid, callingUid)) {
Emilian Peeve20c6372018-08-14 18:45:53 +0100691 res = cameraInfo->removePermissionEntries(
692 mCameraProviderManager->getProviderTagIdLocked(String8(cameraId).string()),
693 &tagsRemoved);
694 if (res != OK) {
695 cameraInfo->clear();
696 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
697 " characteristics needing camera permission for device %s: %s (%d)",
698 String8(cameraId).string(), strerror(-res), res);
699 }
700 }
701
702 if (!tagsRemoved.empty()) {
703 res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
704 tagsRemoved.data(), tagsRemoved.size());
705 if (res != OK) {
706 cameraInfo->clear();
707 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
708 "keys needing permission for device %s: %s (%d)", String8(cameraId).string(),
709 strerror(-res), res);
710 }
711 }
712
Zhijun He2b59be82013-09-25 10:14:30 -0700713 return ret;
714}
715
Ruben Brunkcc776712015-02-17 20:18:47 -0800716String8 CameraService::getFormattedCurrentTime() {
717 time_t now = time(nullptr);
718 char formattedTime[64];
719 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
720 return String8(formattedTime);
721}
722
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800723Status CameraService::getCameraVendorTagDescriptor(
724 /*out*/
725 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700726 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800727 if (!mInitialized) {
728 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800729 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800730 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -0800731 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
732 if (globalDescriptor != nullptr) {
733 *desc = *(globalDescriptor.get());
734 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800735 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800736}
737
Emilian Peev71c73a22017-03-21 16:35:51 +0000738Status CameraService::getCameraVendorTagCache(
739 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
740 ATRACE_CALL();
741 if (!mInitialized) {
742 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
743 return STATUS_ERROR(ERROR_DISCONNECTED,
744 "Camera subsystem not available");
745 }
746 sp<VendorTagDescriptorCache> globalCache =
747 VendorTagDescriptorCache::getGlobalVendorTagCache();
748 if (globalCache != nullptr) {
749 *cache = *(globalCache.get());
750 }
751 return Status::ok();
752}
753
Emilian Peevb91f1802021-03-23 14:50:28 -0700754int CameraService::getDeviceVersion(const String8& cameraId, int* facing, int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700755 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800756
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800757 int deviceVersion = 0;
758
Emilian Peevf53f66e2017-04-11 14:29:43 +0100759 status_t res;
760 hardware::hidl_version maxVersion{0,0};
761 res = mCameraProviderManager->getHighestSupportedVersion(cameraId.string(),
762 &maxVersion);
763 if (res != OK) return -1;
764 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800765
Emilian Peevf53f66e2017-04-11 14:29:43 +0100766 hardware::CameraInfo info;
767 if (facing) {
768 res = mCameraProviderManager->getCameraInfo(cameraId.string(), &info);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -0800769 if (res != OK) return -1;
Emilian Peevf53f66e2017-04-11 14:29:43 +0100770 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -0700771 if (orientation) {
772 *orientation = info.orientation;
773 }
Igor Murashkin634a5152013-02-20 17:15:11 -0800774 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100775
Igor Murashkin634a5152013-02-20 17:15:11 -0800776 return deviceVersion;
777}
778
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800779Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700780 switch(err) {
781 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800782 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800783 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800784 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
785 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800786 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800787 return STATUS_ERROR(ERROR_DISCONNECTED,
788 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700789 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800790 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
791 "Camera HAL encountered error %d: %s",
792 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700793 }
Igor Murashkinbfc99152013-02-27 12:55:20 -0800794}
795
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800796Status CameraService::makeClient(const sp<CameraService>& cameraService,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800797 const sp<IInterface>& cameraCb, const String16& packageName,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700798 const std::optional<String16>& featureId, const String8& cameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -0700799 int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
800 int servicePid, int deviceVersion, apiLevel effectiveApiLevel,
Ruben Brunkcc776712015-02-17 20:18:47 -0800801 /*out*/sp<BasicClient>* client) {
802
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700803 // Create CameraClient based on device version reported by the HAL.
804 switch(deviceVersion) {
805 case CAMERA_DEVICE_API_VERSION_1_0:
806 ALOGE("Camera using old HAL version: %d", deviceVersion);
807 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
808 "Camera device \"%s\" HAL version %d no longer supported",
809 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800810 break;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700811 case CAMERA_DEVICE_API_VERSION_3_0:
812 case CAMERA_DEVICE_API_VERSION_3_1:
813 case CAMERA_DEVICE_API_VERSION_3_2:
814 case CAMERA_DEVICE_API_VERSION_3_3:
815 case CAMERA_DEVICE_API_VERSION_3_4:
816 case CAMERA_DEVICE_API_VERSION_3_5:
817 case CAMERA_DEVICE_API_VERSION_3_6:
Shuzhen Wang83bff122020-11-20 15:51:39 -0800818 case CAMERA_DEVICE_API_VERSION_3_7:
Ruben Brunkcc776712015-02-17 20:18:47 -0800819 if (effectiveApiLevel == API_1) { // Camera1 API route
820 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800821 *client = new Camera2Client(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800822 cameraId, api1CameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -0700823 facing, sensorOrientation, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700824 servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800825 } else { // Camera2 API route
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800826 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
827 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800828 *client = new CameraDeviceClient(cameraService, tmp, packageName, featureId,
Emilian Peev8b64f282021-03-25 16:49:57 -0700829 cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800830 }
831 break;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700832 default:
Ruben Brunkcc776712015-02-17 20:18:47 -0800833 // Should not be reachable
834 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800835 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800836 "Camera device \"%s\" has unknown HAL version %d",
837 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800838 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800839 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800840}
841
Ruben Brunk6267b532015-04-30 17:44:07 -0700842String8 CameraService::toString(std::set<userid_t> intSet) {
843 String8 s("");
844 bool first = true;
845 for (userid_t i : intSet) {
846 if (first) {
847 s.appendFormat("%d", i);
848 first = false;
849 } else {
850 s.appendFormat(", %d", i);
851 }
852 }
853 return s;
854}
855
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800856int32_t CameraService::mapToInterface(TorchModeStatus status) {
857 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
858 switch (status) {
859 case TorchModeStatus::NOT_AVAILABLE:
860 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
861 break;
862 case TorchModeStatus::AVAILABLE_OFF:
863 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
864 break;
865 case TorchModeStatus::AVAILABLE_ON:
866 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
867 break;
868 default:
869 ALOGW("Unknown new flash status: %d", status);
870 }
871 return serviceStatus;
872}
873
874CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
875 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
876 switch (status) {
877 case CameraDeviceStatus::NOT_PRESENT:
878 serviceStatus = StatusInternal::NOT_PRESENT;
879 break;
880 case CameraDeviceStatus::PRESENT:
881 serviceStatus = StatusInternal::PRESENT;
882 break;
883 case CameraDeviceStatus::ENUMERATING:
884 serviceStatus = StatusInternal::ENUMERATING;
885 break;
886 default:
887 ALOGW("Unknown new HAL device status: %d", status);
888 }
889 return serviceStatus;
890}
891
892int32_t CameraService::mapToInterface(StatusInternal status) {
893 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
894 switch (status) {
895 case StatusInternal::NOT_PRESENT:
896 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
897 break;
898 case StatusInternal::PRESENT:
899 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
900 break;
901 case StatusInternal::ENUMERATING:
902 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
903 break;
904 case StatusInternal::NOT_AVAILABLE:
905 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
906 break;
907 case StatusInternal::UNKNOWN:
908 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
909 break;
910 default:
911 ALOGW("Unknown new internal device status: %d", status);
912 }
913 return serviceStatus;
914}
915
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800916Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -0700917 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700918
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800919 String16 internalPackageName("cameraserver");
Ruben Brunkcc776712015-02-17 20:18:47 -0800920 String8 id = String8::format("%d", cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800921 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800922 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800923 if (!(ret = connectHelper<ICameraClient,Client>(
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800924 sp<ICameraClient>{nullptr}, id, cameraId,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +0900925 internalPackageName, {}, uid, USE_CALLING_PID,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700926 API_1, /*shimUpdateOnly*/ true, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800927 ).isOk()) {
928 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
Ruben Brunkb2119af2014-05-09 19:57:56 -0700929 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800930 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700931}
932
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800933Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -0700934 /*out*/
935 CameraParameters* parameters) {
936
937 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
938
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800939 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -0700940
941 if (parameters == NULL) {
942 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800943 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -0700944 }
945
Ruben Brunkcc776712015-02-17 20:18:47 -0800946 String8 id = String8::format("%d", cameraId);
947
948 // Check if we already have parameters
949 {
950 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -0700951 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -0800952 auto cameraState = getCameraState(id);
953 if (cameraState == nullptr) {
954 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800955 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
956 "Invalid camera ID: %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -0800957 }
958 CameraParameters p = cameraState->getShimParams();
959 if (!p.isEmpty()) {
960 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800961 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700962 }
963 }
964
Jayant Chowdhary12361932018-08-27 14:46:13 -0700965 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -0800966 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -0700967 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800968 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800969 // Error already logged by callee
970 return ret;
971 }
972
973 // Check for parameters again
974 {
975 // Scope for service lock
976 Mutex::Autolock lock(mServiceLock);
977 auto cameraState = getCameraState(id);
978 if (cameraState == nullptr) {
979 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800980 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
981 "Invalid camera ID: %s", id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -0700982 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800983 CameraParameters p = cameraState->getShimParams();
984 if (!p.isEmpty()) {
985 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800986 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700987 }
988 }
989
Ruben Brunkcc776712015-02-17 20:18:47 -0800990 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
991 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800992 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -0700993}
994
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800995// Can camera service trust the caller based on the calling UID?
996static bool isTrustedCallingUid(uid_t uid) {
997 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -0700998 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800999 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001000 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001001 return true;
1002 default:
1003 return false;
1004 }
1005}
1006
Nicholas Sauera3620332019-04-03 14:05:17 -07001007static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1008 PermissionController pc;
1009 uid = pc.getPackageUid(packageName, 0);
1010 if (uid <= 0) {
1011 ALOGE("Unknown package: '%s'", String8(packageName).string());
1012 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
1013 return BAD_VALUE;
1014 }
1015
1016 if (userId < 0) {
1017 ALOGE("Invalid user: %d", userId);
1018 dprintf(err, "Invalid user: %d\n", userId);
1019 return BAD_VALUE;
1020 }
1021
1022 uid = multiuser_get_uid(userId, uid);
1023 return NO_ERROR;
1024}
1025
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001026Status CameraService::validateConnectLocked(const String8& cameraId,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001027 const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
1028 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001029
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001030#ifdef __BRILLO__
1031 UNUSED(clientName8);
1032 UNUSED(clientUid);
1033 UNUSED(clientPid);
1034 UNUSED(originalClientPid);
1035#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001036 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1037 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001038 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001039 return allowed;
1040 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001041#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001042
Jayant Chowdhary12361932018-08-27 14:46:13 -07001043 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001044
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001045 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001046 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1047 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001048 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1049 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001050 }
1051
Ruben Brunkcc776712015-02-17 20:18:47 -08001052 if (getCameraState(cameraId) == nullptr) {
1053 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1054 cameraId.string());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001055 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1056 "No camera device with ID \"%s\" available", cameraId.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001057 }
1058
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001059 status_t err = checkIfDeviceIsUsable(cameraId);
1060 if (err != NO_ERROR) {
1061 switch(err) {
1062 case -ENODEV:
1063 case -EBUSY:
1064 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1065 "No camera device with ID \"%s\" currently available", cameraId.string());
1066 default:
1067 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1068 "Unknown error connecting to ID \"%s\"", cameraId.string());
1069 }
1070 }
1071 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001072}
1073
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001074Status CameraService::validateClientPermissionsLocked(const String8& cameraId,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001075 const String8& clientName8, int& clientUid, int& clientPid,
1076 /*out*/int& originalClientPid) const {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001077 int callingPid = CameraThreadState::getCallingPid();
1078 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001079
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001080 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001081 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001082 clientUid = callingUid;
1083 } else if (!isTrustedCallingUid(callingUid)) {
1084 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1085 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001086 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1087 "Untrusted caller (calling PID %d, UID %d) trying to "
1088 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1089 callingPid, callingUid, cameraId.string(),
1090 clientName8.string(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001091 }
1092
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001093 // Check if we can trust clientPid
1094 if (clientPid == USE_CALLING_PID) {
1095 clientPid = callingPid;
1096 } else if (!isTrustedCallingUid(callingUid)) {
1097 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1098 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001099 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1100 "Untrusted caller (calling PID %d, UID %d) trying to "
1101 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1102 callingPid, callingUid, cameraId.string(),
1103 clientName8.string(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001104 }
1105
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001106 if (shouldRejectSystemCameraConnection(cameraId)) {
1107 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1108 cameraId.c_str());
1109 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
1110 "available", cameraId.string());
1111 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001112 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1113 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1114 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
1115 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
1116 "found while trying to query device kind", cameraId.string());
1117
1118 }
1119
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001120 // If it's not calling from cameraserver, check the permission if the
1121 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1122 // android.permission.SYSTEM_CAMERA for system only camera devices).
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001123 if (callingPid != getpid() &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001124 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001125 !checkPermission(sCameraPermission, clientPid, clientUid)) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001126 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001127 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1128 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
1129 clientName8.string(), clientUid, clientPid, cameraId.string());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001130 }
1131
Svet Ganova453d0d2018-01-11 15:37:58 -08001132 // Make sure the UID is in an active state to use the camera
Svet Ganov7b4ab782018-03-25 12:48:10 -07001133 if (!mUidPolicy->isUidActive(callingUid, String16(clientName8))) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001134 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001135 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1136 clientPid, clientUid);
1137 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001138 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1139 "calling UID %d proc state %" PRId32 ")",
1140 clientName8.string(), clientUid, clientPid, cameraId.string(),
1141 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001142 }
1143
Michael Grooverd1d435a2018-12-18 17:39:42 -08001144 // If sensor privacy is enabled then prevent access to the camera
1145 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1146 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1147 return STATUS_ERROR_FMT(ERROR_DISABLED,
1148 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
1149 "is enabled", clientName8.string(), clientUid, clientPid, cameraId.string());
1150 }
1151
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001152 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1153 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001154 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001155 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001156
Ruben Brunk6267b532015-04-30 17:44:07 -07001157 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001158
Ruben Brunka8ca9152015-04-07 14:23:40 -07001159 // Only allow clients who are being used by the current foreground device user, unless calling
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001160 // from our own process OR the caller is using the cameraserver's HIDL interface.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001161 if (getCurrentServingCall() != BinderCallType::HWBINDER && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001162 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001163 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1164 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
1165 toString(mAllowedUsers).string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001166 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1167 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
1168 clientUserId, cameraId.string());
Ruben Brunk36597b22015-03-20 22:15:57 -07001169 }
1170
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001171 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001172}
1173
1174status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
1175 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001176 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001177 if (cameraState == nullptr) {
1178 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1179 cameraId.string());
1180 return -ENODEV;
1181 }
1182
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001183 StatusInternal currentStatus = cameraState->getStatus();
1184 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001185 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
1186 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001187 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001188 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001189 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
1190 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001191 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001192 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001193
Ruben Brunkcc776712015-02-17 20:18:47 -08001194 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001195}
1196
Ruben Brunkcc776712015-02-17 20:18:47 -08001197void CameraService::finishConnectLocked(const sp<BasicClient>& client,
1198 const CameraService::DescriptorPtr& desc) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001199
Ruben Brunkcc776712015-02-17 20:18:47 -08001200 // Make a descriptor for the incoming client
1201 auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
1202 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1203
1204 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
1205 String8(client->getPackageName()));
1206
1207 if (evicted.size() > 0) {
1208 // This should never happen - clients should already have been removed in disconnect
1209 for (auto& i : evicted) {
1210 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
1211 __FUNCTION__, i->getKey().string());
1212 }
1213
1214 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1215 __FUNCTION__);
1216 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001217
1218 // And register a death notification for the client callback. Do
1219 // this last to avoid Binder policy where a nested Binder
1220 // transaction might be pre-empted to service the client death
1221 // notification if the client process dies before linkToDeath is
1222 // invoked.
1223 sp<IBinder> remoteCallback = client->getRemote();
1224 if (remoteCallback != nullptr) {
1225 remoteCallback->linkToDeath(this);
1226 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001227}
1228
1229status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
1230 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
1231 /*out*/
1232 sp<BasicClient>* client,
1233 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001234 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001235 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001236 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001237 DescriptorPtr clientDescriptor;
1238 {
1239 if (effectiveApiLevel == API_1) {
1240 // If we are using API1, any existing client for this camera ID with the same remote
1241 // should be returned rather than evicted to allow MediaRecorder to work properly.
1242
1243 auto current = mActiveClientManager.get(cameraId);
1244 if (current != nullptr) {
1245 auto clientSp = current->getValue();
1246 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001247 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
1248 ALOGW("CameraService connect called from same client, but with a different"
1249 " API level, evicting prior client...");
1250 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001251 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001252 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001253 *client = clientSp;
1254 return NO_ERROR;
1255 }
1256 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001257 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001258 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001259
Ruben Brunkcc776712015-02-17 20:18:47 -08001260 // Get current active client PIDs
1261 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1262 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001263
Emilian Peev8131a262017-02-01 12:33:43 +00001264 std::vector<int> priorityScores(ownerPids.size());
1265 std::vector<int> states(ownerPids.size());
Igor Murashkine6800ce2013-03-04 17:25:57 -08001266
Emilian Peev8131a262017-02-01 12:33:43 +00001267 // Get priority scores of all active PIDs
1268 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1269 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1270 /*out*/&priorityScores[0]);
1271 if (err != OK) {
1272 ALOGE("%s: Priority score query failed: %d",
1273 __FUNCTION__, err);
1274 return err;
1275 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001276
Ruben Brunkcc776712015-02-17 20:18:47 -08001277 // Update all active clients' priorities
Emilian Peev8131a262017-02-01 12:33:43 +00001278 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
Ruben Brunkcc776712015-02-17 20:18:47 -08001279 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
Emilian Peev8131a262017-02-01 12:33:43 +00001280 pidToPriorityMap.emplace(ownerPids[i],
Jayant Chowdharyc578a502019-05-08 10:57:54 -07001281 resource_policy::ClientPriority(priorityScores[i], states[i],
1282 /* isVendorClient won't get copied over*/ false));
Ruben Brunkcc776712015-02-17 20:18:47 -08001283 }
1284 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001285
Ruben Brunkcc776712015-02-17 20:18:47 -08001286 // Get state for the given cameraId
1287 auto state = getCameraState(cameraId);
1288 if (state == nullptr) {
1289 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1290 clientPid, cameraId.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001291 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001292 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001293 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001294
1295 // Make descriptor for incoming client
Shuzhen Wang2db86ff2018-04-25 01:11:17 +00001296 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001297 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1298 state->getConflicting(),
Emilian Peev8131a262017-02-01 12:33:43 +00001299 priorityScores[priorityScores.size() - 1],
1300 clientPid,
1301 states[states.size() - 1]);
Ruben Brunkcc776712015-02-17 20:18:47 -08001302
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001303 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1304
Ruben Brunkcc776712015-02-17 20:18:47 -08001305 // Find clients that would be evicted
1306 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1307
1308 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1309 // background, so we cannot do evictions
1310 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1311 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1312 " priority).", clientPid);
1313
1314 sp<BasicClient> clientSp = clientDescriptor->getValue();
1315 String8 curTime = getFormattedCurrentTime();
1316 auto incompatibleClients =
1317 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1318
1319 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Emilian Peev8131a262017-02-01 12:33:43 +00001320 "(PID %d, score %d state %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001321 cameraId.string(), packageName.string(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001322 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001323
1324 for (auto& i : incompatibleClients) {
1325 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001326 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
1327 i->getKey().string(),
1328 String8{i->getValue()->getPackageName()}.string(),
1329 i->getOwnerId(), i->getPriority().getScore(),
1330 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001331 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00001332 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(),
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001333 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001334 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001335 }
1336
1337 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001338 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001339 mEventLog.add(msg);
1340
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001341 auto current = mActiveClientManager.get(cameraId);
1342 if (current != nullptr) {
1343 return -EBUSY; // CAMERA_IN_USE
1344 } else {
1345 return -EUSERS; // MAX_CAMERAS_IN_USE
1346 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001347 }
1348
1349 for (auto& i : evicted) {
1350 sp<BasicClient> clientSp = i->getValue();
1351 if (clientSp.get() == nullptr) {
1352 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1353
1354 // TODO: Remove this
1355 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1356 __FUNCTION__);
1357 mActiveClientManager.remove(i);
1358 continue;
1359 }
1360
1361 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1362 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001363 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001364
Ruben Brunkcc776712015-02-17 20:18:47 -08001365 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001366 logEvent(String8::format("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00001367 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1368 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001369 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
Emilian Peev8131a262017-02-01 12:33:43 +00001370 i->getOwnerId(), i->getPriority().getScore(),
1371 i->getPriority().getState(), cameraId.string(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001372 packageName.string(), clientPid, clientPriority.getScore(),
1373 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08001374
1375 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001376 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001377 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001378 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001379 }
1380
Ruben Brunkcc776712015-02-17 20:18:47 -08001381 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1382 // other clients from connecting in mServiceLockWrapper if held
1383 mServiceLock.unlock();
1384
1385 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07001386 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001387
1388 // Destroy evicted clients
1389 for (auto& i : evictedClients) {
1390 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001391 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001392 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001393
Jayant Chowdhary12361932018-08-27 14:46:13 -07001394 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08001395
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001396 for (const auto& i : evictedClients) {
1397 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1398 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1399 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1400 if (ret == TIMED_OUT) {
1401 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1402 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1403 mActiveClientManager.toString().string());
1404 return -EBUSY;
1405 }
1406 if (ret != NO_ERROR) {
1407 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1408 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1409 ret, mActiveClientManager.toString().string());
1410 return ret;
1411 }
1412 }
1413
1414 evictedClients.clear();
1415
Ruben Brunkcc776712015-02-17 20:18:47 -08001416 // Once clients have been disconnected, relock
1417 mServiceLock.lock();
1418
1419 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1420 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1421 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001422 }
1423
Ruben Brunkcc776712015-02-17 20:18:47 -08001424 *partial = clientDescriptor;
1425 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001426}
1427
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001428Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001429 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001430 int api1CameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001431 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001432 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001433 int clientPid,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001434 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001435 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001436
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001437 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001438 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001439
1440 String8 id = cameraIdIntToStr(api1CameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001441 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001442 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001443 clientPackageName, {}, clientUid, clientPid, API_1,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001444 /*shimUpdateOnly*/ false, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001445
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001446 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001447 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001448 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001449 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001450 }
1451
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001452 *device = client;
1453 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001454}
1455
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001456bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
1457 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001458 // If the client is not a vendor client, don't add listener if
1459 // a) the camera is a publicly hidden secure camera OR
1460 // b) the camera is a system only camera and the client doesn't
1461 // have android.permission.SYSTEM_CAMERA permissions.
1462 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
1463 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1464 !hasPermissionsForSystemCamera(clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001465 return true;
1466 }
1467 return false;
1468}
1469
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001470bool CameraService::shouldRejectSystemCameraConnection(const String8& cameraId) const {
1471 // Rules for rejection:
1472 // 1) If cameraserver tries to access this camera device, accept the
1473 // connection.
1474 // 2) The camera device is a publicly hidden secure camera device AND some
1475 // component is trying to access it on a non-hwbinder thread (generally a non HAL client),
1476 // reject it.
1477 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
1478 // and the serving thread is a non hwbinder thread, the client must have
1479 // android.permission.SYSTEM_CAMERA permissions to connect.
1480
1481 int cPid = CameraThreadState::getCallingPid();
1482 int cUid = CameraThreadState::getCallingUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001483 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
1484 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001485 // This isn't a known camera ID, so it's not a system camera
1486 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
1487 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001488 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001489
1490 // (1) Cameraserver trying to connect, accept.
1491 if (CameraThreadState::getCallingPid() == getpid()) {
1492 return false;
1493 }
1494 // (2)
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001495 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001496 systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
1497 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
1498 return true;
1499 }
1500 // (3) Here we only check for permissions if it is a system only camera device. This is since
1501 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
1502 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
1503 // same behavior for system camera devices.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001504 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001505 systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1506 !hasPermissionsForSystemCamera(cPid, cUid)) {
1507 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
1508 cameraId.c_str());
1509 return true;
1510 }
1511
1512 return false;
1513}
1514
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001515Status CameraService::connectDevice(
1516 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001517 const String16& cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001518 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001519 const std::optional<String16>& clientFeatureId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001520 int clientUid,
1521 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001522 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001523
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001524 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001525 Status ret = Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001526 String8 id = String8(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001527 sp<CameraDeviceClient> client = nullptr;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001528 String16 clientPackageNameAdj = clientPackageName;
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001529
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001530 if (getCurrentServingCall() == BinderCallType::HWBINDER) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001531 std::string vendorClient =
1532 StringPrintf("vendor.client.pid<%d>", CameraThreadState::getCallingPid());
1533 clientPackageNameAdj = String16(vendorClient.c_str());
1534 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001535 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001536 /*api1CameraId*/-1, clientPackageNameAdj, clientFeatureId,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001537 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08001538
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001539 if(!ret.isOk()) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001540 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageNameAdj),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001541 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001542 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001543 }
1544
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001545 *device = client;
1546 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001547}
1548
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001549template<class CALLBACK, class CLIENT>
1550Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001551 int api1CameraId, const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001552 const std::optional<String16>& clientFeatureId, int clientUid, int clientPid,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001553 apiLevel effectiveApiLevel, bool shimUpdateOnly,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001554 /*out*/sp<CLIENT>& device) {
1555 binder::Status ret = binder::Status::ok();
1556
1557 String8 clientName8(clientPackageName);
1558
1559 int originalClientPid = 0;
1560
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001561 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001562 "Camera API version %d", clientPid, clientName8.string(), cameraId.string(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001563 static_cast<int>(effectiveApiLevel));
1564
Shuzhen Wang316781a2020-08-18 18:11:01 -07001565 nsecs_t openTimeNs = systemTime();
1566
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001567 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001568 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07001569 int orientation = 0;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001570 bool isNdk = (clientPackageName.size() == 0);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001571 {
1572 // Acquire mServiceLock and prevent other clients from connecting
1573 std::unique_ptr<AutoConditionLock> lock =
1574 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1575
1576 if (lock == nullptr) {
1577 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
1578 , clientPid);
1579 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1580 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
1581 cameraId.string(), clientName8.string(), clientPid);
1582 }
1583
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07001584 // Enforce client permissions and do basic validity checks
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001585 if(!(ret = validateConnectLocked(cameraId, clientName8,
1586 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
1587 return ret;
1588 }
1589
1590 // Check the shim parameters after acquiring lock, if they have already been updated and
1591 // we were doing a shim update, return immediately
1592 if (shimUpdateOnly) {
1593 auto cameraState = getCameraState(cameraId);
1594 if (cameraState != nullptr) {
1595 if (!cameraState->getShimParams().isEmpty()) return ret;
1596 }
1597 }
1598
1599 status_t err;
1600
1601 sp<BasicClient> clientTmp = nullptr;
1602 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
1603 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
1604 IInterface::asBinder(cameraCb), clientName8, /*out*/&clientTmp,
1605 /*out*/&partial)) != NO_ERROR) {
1606 switch (err) {
1607 case -ENODEV:
1608 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1609 "No camera device with ID \"%s\" currently available",
1610 cameraId.string());
1611 case -EBUSY:
1612 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1613 "Higher-priority client using camera, ID \"%s\" currently unavailable",
1614 cameraId.string());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001615 case -EUSERS:
1616 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1617 "Too many cameras already open, cannot open camera \"%s\"",
1618 cameraId.string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001619 default:
1620 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1621 "Unexpected error %s (%d) opening camera \"%s\"",
1622 strerror(-err), err, cameraId.string());
1623 }
1624 }
1625
1626 if (clientTmp.get() != nullptr) {
1627 // Handle special case for API1 MediaRecorder where the existing client is returned
1628 device = static_cast<CLIENT*>(clientTmp.get());
1629 return ret;
1630 }
1631
1632 // give flashlight a chance to close devices if necessary.
1633 mFlashlight->prepareDeviceOpen(cameraId);
1634
Emilian Peevb91f1802021-03-23 14:50:28 -07001635 int deviceVersion = getDeviceVersion(cameraId, /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08001636 if (facing == -1) {
1637 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.string());
1638 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1639 "Unable to get camera device \"%s\" facing", cameraId.string());
1640 }
1641
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001642 sp<BasicClient> tmp = nullptr;
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001643 if(!(ret = makeClient(this, cameraCb, clientPackageName, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07001644 cameraId, api1CameraId, facing, orientation,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001645 clientPid, clientUid, getpid(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001646 deviceVersion, effectiveApiLevel,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001647 /*out*/&tmp)).isOk()) {
1648 return ret;
1649 }
1650 client = static_cast<CLIENT*>(tmp.get());
1651
1652 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
1653 __FUNCTION__);
1654
Emilian Peevbd8c5032018-02-14 23:05:40 +00001655 err = client->initialize(mCameraProviderManager, mMonitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001656 if (err != OK) {
1657 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001658 // Errors could be from the HAL module open call or from AppOpsManager
1659 switch(err) {
1660 case BAD_VALUE:
1661 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1662 "Illegal argument to HAL module for camera \"%s\"", cameraId.string());
1663 case -EBUSY:
1664 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1665 "Camera \"%s\" is already open", cameraId.string());
1666 case -EUSERS:
1667 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1668 "Too many cameras already open, cannot open camera \"%s\"",
1669 cameraId.string());
1670 case PERMISSION_DENIED:
1671 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1672 "No permission to open camera \"%s\"", cameraId.string());
1673 case -EACCES:
1674 return STATUS_ERROR_FMT(ERROR_DISABLED,
1675 "Camera \"%s\" disabled by policy", cameraId.string());
1676 case -ENODEV:
1677 default:
1678 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1679 "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
1680 strerror(-err), err);
1681 }
1682 }
1683
1684 // Update shim paremeters for legacy clients
1685 if (effectiveApiLevel == API_1) {
1686 // Assume we have always received a Client subclass for API1
1687 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
1688 String8 rawParams = shimClient->getParameters();
1689 CameraParameters params(rawParams);
1690
1691 auto cameraState = getCameraState(cameraId);
1692 if (cameraState != nullptr) {
1693 cameraState->setShimParams(params);
1694 } else {
1695 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
1696 __FUNCTION__, cameraId.string());
1697 }
1698 }
1699
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001700 // Set rotate-and-crop override behavior
1701 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
1702 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
Emilian Peevb91f1802021-03-23 14:50:28 -07001703 } else if (CameraServiceProxyWrapper::isRotateAndCropOverrideNeeded(clientPackageName,
1704 orientation, facing)) {
1705 client->setRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_90);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001706 }
1707
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08001708 // Set camera muting behavior
1709 if (client->supportsCameraMute()) {
Evan Severson09ab4002021-02-10 14:15:19 -08001710 bool isCameraPrivacyEnabled =
1711 mSensorPrivacyPolicy->isCameraPrivacyEnabled(multiuser_get_user_id(clientUid));
1712 client->setCameraMute(mOverrideCameraMuteMode || isCameraPrivacyEnabled);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08001713 }
1714
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001715 if (shimUpdateOnly) {
1716 // If only updating legacy shim parameters, immediately disconnect client
1717 mServiceLock.unlock();
1718 client->disconnect();
1719 mServiceLock.lock();
1720 } else {
1721 // Otherwise, add client to active clients list
1722 finishConnectLocked(client, partial);
1723 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001724
1725 client->setImageDumpMask(mImageDumpMask);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001726 } // lock is destroyed, allow further connect calls
1727
1728 // Important: release the mutex here so the client can call back into the service from its
1729 // destructor (can be at the end of the call)
1730 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001731
1732 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
1733 CameraServiceProxyWrapper::logOpen(cameraId, facing, clientPackageName,
1734 effectiveApiLevel, isNdk, openLatencyMs);
1735
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001736 return ret;
1737}
1738
Emilian Peevb2bc5a42019-11-20 16:02:14 -08001739status_t CameraService::addOfflineClient(String8 cameraId, sp<BasicClient> offlineClient) {
1740 if (offlineClient.get() == nullptr) {
1741 return BAD_VALUE;
1742 }
1743
1744 {
1745 // Acquire mServiceLock and prevent other clients from connecting
1746 std::unique_ptr<AutoConditionLock> lock =
1747 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1748
1749 if (lock == nullptr) {
1750 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
1751 , __FUNCTION__, offlineClient->getClientPid());
1752 return TIMED_OUT;
1753 }
1754
1755 auto onlineClientDesc = mActiveClientManager.get(cameraId);
1756 if (onlineClientDesc.get() == nullptr) {
1757 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
1758 cameraId.c_str());
1759 return BAD_VALUE;
1760 }
1761
1762 // Offline clients do not evict or conflict with other online devices. Resource sharing
1763 // conflicts are handled by the camera provider which will either succeed or fail before
1764 // reaching this method.
1765 const auto& onlinePriority = onlineClientDesc->getPriority();
1766 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
1767 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
1768 /*conflictingKeys*/ std::set<String8>(), onlinePriority.getScore(),
1769 onlineClientDesc->getOwnerId(), onlinePriority.getState());
1770
1771 // Allow only one offline device per camera
1772 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
1773 if (!incompatibleClients.empty()) {
1774 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
1775 return BAD_VALUE;
1776 }
1777
1778 auto err = offlineClient->initialize(mCameraProviderManager, mMonitorTags);
1779 if (err != OK) {
1780 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
1781 return err;
1782 }
1783
1784 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
1785 if (evicted.size() > 0) {
1786 for (auto& i : evicted) {
1787 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
1788 __FUNCTION__, i->getKey().string());
1789 }
1790
1791 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
1792 "properly", __FUNCTION__);
1793
1794 return BAD_VALUE;
1795 }
1796
1797 logConnectedOffline(offlineClientDesc->getKey(),
1798 static_cast<int>(offlineClientDesc->getOwnerId()),
1799 String8(offlineClient->getPackageName()));
1800
1801 sp<IBinder> remoteCallback = offlineClient->getRemote();
1802 if (remoteCallback != nullptr) {
1803 remoteCallback->linkToDeath(this);
1804 }
1805 } // lock is destroyed, allow further connect calls
1806
1807 return OK;
1808}
1809
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001810Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001811 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001812 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001813
1814 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07001815 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001816 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001817 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1818 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001819 }
1820
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001821 String8 id = String8(cameraId.string());
Jayant Chowdhary12361932018-08-27 14:46:13 -07001822 int uid = CameraThreadState::getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001823
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07001824 if (shouldRejectSystemCameraConnection(id)) {
1825 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
1826 " for system only device %s: ", id.string());
1827 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001828 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08001829 auto state = getCameraState(id);
1830 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001831 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001832 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1833 "Camera ID \"%s\" is a not valid camera ID", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001834 }
1835
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001836 StatusInternal cameraStatus = state->getStatus();
1837 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001838 cameraStatus != StatusInternal::NOT_AVAILABLE) {
1839 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001840 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1841 "Camera ID \"%s\" is a not valid camera ID", id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001842 }
1843
1844 {
1845 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001846 TorchModeStatus status;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001847 status_t err = getTorchStatusLocked(id, &status);
1848 if (err != OK) {
1849 if (err == NAME_NOT_FOUND) {
1850 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1851 "Camera \"%s\" does not have a flash unit", id.string());
1852 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001853 ALOGE("%s: getting current torch status failed for camera %s",
1854 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001855 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1856 "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
1857 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001858 }
1859
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001860 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001861 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001862 ALOGE("%s: torch mode of camera %s is not available because "
1863 "camera is in use", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001864 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1865 "Torch for camera \"%s\" is not available due to an existing camera user",
1866 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001867 } else {
1868 ALOGE("%s: torch mode of camera %s is not available due to "
1869 "insufficient resources", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001870 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1871 "Torch for camera \"%s\" is not available due to insufficient resources",
1872 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001873 }
1874 }
1875 }
1876
Ruben Brunk99e69712015-05-26 17:25:07 -07001877 {
1878 // Update UID map - this is used in the torch status changed callbacks, so must be done
1879 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07001880 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -07001881 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
1882 mTorchUidMap[id].first = uid;
1883 mTorchUidMap[id].second = uid;
1884 } else {
1885 // Set the pending UID
1886 mTorchUidMap[id].first = uid;
1887 }
1888 }
1889
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001890 status_t err = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07001891
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001892 if (err != OK) {
1893 int32_t errorCode;
1894 String8 msg;
1895 switch (err) {
1896 case -ENOSYS:
1897 msg = String8::format("Camera \"%s\" has no flashlight",
1898 id.string());
1899 errorCode = ERROR_ILLEGAL_ARGUMENT;
1900 break;
1901 default:
1902 msg = String8::format(
1903 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
1904 id.string(), enabled, strerror(-err), err);
1905 errorCode = ERROR_INVALID_OPERATION;
1906 }
1907 ALOGE("%s: %s", __FUNCTION__, msg.string());
1908 return STATUS_ERROR(errorCode, msg.string());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001909 }
1910
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001911 {
1912 // update the link to client's death
1913 Mutex::Autolock al(mTorchClientMapMutex);
1914 ssize_t index = mTorchClientMap.indexOfKey(id);
1915 if (enabled) {
1916 if (index == NAME_NOT_FOUND) {
1917 mTorchClientMap.add(id, clientBinder);
1918 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07001919 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001920 mTorchClientMap.replaceValueAt(index, clientBinder);
1921 }
1922 clientBinder->linkToDeath(this);
1923 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07001924 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001925 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001926 }
1927
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07001928 int clientPid = CameraThreadState::getCallingPid();
1929 const char *id_cstr = id.c_str();
1930 const char *torchState = enabled ? "on" : "off";
1931 ALOGI("Torch for camera id %s turned %s for client PID %d", id_cstr, torchState, clientPid);
1932 logTorchEvent(id_cstr, torchState , clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001933 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001934}
1935
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001936Status CameraService::notifySystemEvent(int32_t eventId,
1937 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001938 const int pid = CameraThreadState::getCallingPid();
1939 const int selfPid = getpid();
1940
1941 // Permission checks
1942 if (pid != selfPid) {
1943 // Ensure we're being called by system_server, or similar process with
1944 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001945 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001946 const int uid = CameraThreadState::getCallingUid();
1947 ALOGE("Permission Denial: cannot send updates to camera service about system"
1948 " events from pid=%d, uid=%d", pid, uid);
1949 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09001950 "No permission to send updates to camera service about system events"
1951 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001952 }
1953 }
1954
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001955 ATRACE_CALL();
1956
Ruben Brunk36597b22015-03-20 22:15:57 -07001957 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001958 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001959 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07001960 // from a system server crash
1961 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08001962 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001963 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07001964 break;
1965 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001966 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07001967 default: {
1968 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
1969 eventId);
1970 break;
1971 }
1972 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001973 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07001974}
1975
Emilian Peev53722fa2019-02-22 17:47:20 -08001976void CameraService::notifyMonitoredUids() {
1977 Mutex::Autolock lock(mStatusListenerLock);
1978
1979 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001980 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Emilian Peev53722fa2019-02-22 17:47:20 -08001981 if (!ret.isOk()) {
1982 ALOGE("%s: Failed to trigger permission callback: %d", __FUNCTION__,
1983 ret.exceptionCode());
1984 }
1985 }
1986}
1987
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08001988Status CameraService::notifyDeviceStateChange(int64_t newState) {
1989 const int pid = CameraThreadState::getCallingPid();
1990 const int selfPid = getpid();
1991
1992 // Permission checks
1993 if (pid != selfPid) {
1994 // Ensure we're being called by system_server, or similar process with
1995 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001996 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08001997 const int uid = CameraThreadState::getCallingUid();
1998 ALOGE("Permission Denial: cannot send updates to camera service about device"
1999 " state changes from pid=%d, uid=%d", pid, uid);
2000 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2001 "No permission to send updates to camera service about device state"
2002 " changes from pid=%d, uid=%d", pid, uid);
2003 }
2004 }
2005
2006 ATRACE_CALL();
2007
2008 using hardware::camera::provider::V2_5::DeviceState;
2009 hardware::hidl_bitfield<DeviceState> newDeviceState{};
2010 if (newState & ICameraService::DEVICE_STATE_BACK_COVERED) {
2011 newDeviceState |= DeviceState::BACK_COVERED;
2012 }
2013 if (newState & ICameraService::DEVICE_STATE_FRONT_COVERED) {
2014 newDeviceState |= DeviceState::FRONT_COVERED;
2015 }
2016 if (newState & ICameraService::DEVICE_STATE_FOLDED) {
2017 newDeviceState |= DeviceState::FOLDED;
2018 }
2019 // Only map vendor bits directly
2020 uint64_t vendorBits = static_cast<uint64_t>(newState) & 0xFFFFFFFF00000000l;
2021 newDeviceState |= vendorBits;
2022
2023 ALOGV("%s: New device state 0x%" PRIx64, __FUNCTION__, newDeviceState);
2024 Mutex::Autolock l(mServiceLock);
2025 mCameraProviderManager->notifyDeviceStateChange(newDeviceState);
2026
2027 return Status::ok();
2028}
2029
Emilian Peev8b64f282021-03-25 16:49:57 -07002030Status CameraService::notifyDisplayConfigurationChange() {
2031 ATRACE_CALL();
2032 const int callingPid = CameraThreadState::getCallingPid();
2033 const int selfPid = getpid();
2034
2035 // Permission checks
2036 if (callingPid != selfPid) {
2037 // Ensure we're being called by system_server, or similar process with
2038 // permissions to notify the camera service about system events
2039 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
2040 const int uid = CameraThreadState::getCallingUid();
2041 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
2042 " changes from pid=%d, uid=%d", callingPid, uid);
2043 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2044 "No permission to send updates to camera service about orientation"
2045 " changes from pid=%d, uid=%d", callingPid, uid);
2046 }
2047 }
2048
2049 Mutex::Autolock lock(mServiceLock);
2050
2051 // Don't do anything if rotate-and-crop override via cmd is active
2052 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
2053
2054 const auto clients = mActiveClientManager.getAll();
2055 for (auto& current : clients) {
2056 if (current != nullptr) {
2057 const auto basicClient = current->getValue();
2058 if (basicClient.get() != nullptr) {
2059 if (CameraServiceProxyWrapper::isRotateAndCropOverrideNeeded(
2060 basicClient->getPackageName(), basicClient->getCameraOrientation(),
2061 basicClient->getCameraFacing())) {
2062 basicClient->setRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_90);
2063 } else {
2064 basicClient->setRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE);
2065 }
2066 }
2067 }
2068 }
2069
2070 return Status::ok();
2071}
2072
2073Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002074 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
2075 ATRACE_CALL();
2076 if (!concurrentCameraIds) {
2077 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
2078 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
2079 }
2080
2081 if (!mInitialized) {
2082 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2083 return STATUS_ERROR(ERROR_DISCONNECTED,
2084 "Camera subsystem is not available");
2085 }
2086 // First call into the provider and get the set of concurrent camera
2087 // combinations
2088 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07002089 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002090 for (auto &combination : concurrentCameraCombinations) {
2091 std::vector<std::string> validCombination;
2092 for (auto &cameraId : combination) {
2093 // if the camera state is not present, skip
2094 String8 cameraIdStr(cameraId.c_str());
2095 auto state = getCameraState(cameraIdStr);
2096 if (state == nullptr) {
2097 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
2098 continue;
2099 }
2100 StatusInternal status = state->getStatus();
2101 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
2102 continue;
2103 }
2104 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
2105 continue;
2106 }
2107 validCombination.push_back(cameraId);
2108 }
2109 if (validCombination.size() != 0) {
2110 concurrentCameraIds->push_back(std::move(validCombination));
2111 }
2112 }
2113 return Status::ok();
2114}
2115
2116Status CameraService::isConcurrentSessionConfigurationSupported(
2117 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
2118 /*out*/bool* isSupported) {
2119 if (!isSupported) {
2120 ALOGE("%s: isSupported is NULL", __FUNCTION__);
2121 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
2122 }
2123
2124 if (!mInitialized) {
2125 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2126 return STATUS_ERROR(ERROR_DISCONNECTED,
2127 "Camera subsystem is not available");
2128 }
2129
2130 // Check for camera permissions
2131 int callingPid = CameraThreadState::getCallingPid();
2132 int callingUid = CameraThreadState::getCallingUid();
2133 if ((callingPid != getpid()) && !checkPermission(sCameraPermission, callingPid, callingUid)) {
2134 ALOGE("%s: pid %d doesn't have camera permissions", __FUNCTION__, callingPid);
2135 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2136 "android.permission.CAMERA needed to call"
2137 "isConcurrentSessionConfigurationSupported");
2138 }
2139
2140 status_t res =
2141 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
2142 cameraIdsAndSessionConfigurations, isSupported);
2143 if (res != OK) {
2144 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
2145 "support %s (%d)", strerror(-res), res);
2146 }
2147 return Status::ok();
2148}
2149
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002150Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
2151 /*out*/
2152 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002153 return addListenerHelper(listener, cameraStatuses);
2154}
2155
2156Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
2157 /*out*/
2158 std::vector<hardware::CameraStatus> *cameraStatuses,
2159 bool isVendorListener) {
2160
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002161 ATRACE_CALL();
2162
Igor Murashkinbfc99152013-02-27 12:55:20 -08002163 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08002164
Ruben Brunk3450ba72015-06-16 11:00:37 -07002165 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002166 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002167 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002168 }
2169
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002170 auto clientUid = CameraThreadState::getCallingUid();
2171 auto clientPid = CameraThreadState::getCallingPid();
Shuzhen Wang695044d2020-03-06 09:02:23 -08002172 bool openCloseCallbackAllowed = checkPermission(sCameraOpenCloseListenerPermission,
2173 clientPid, clientUid);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002174
Igor Murashkinbfc99152013-02-27 12:55:20 -08002175 Mutex::Autolock lock(mServiceLock);
2176
Ruben Brunkcc776712015-02-17 20:18:47 -08002177 {
2178 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08002179 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002180 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002181 ALOGW("%s: Tried to add listener %p which was already subscribed",
2182 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002183 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08002184 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002185 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002186
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002187 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08002188 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
2189 openCloseCallbackAllowed);
Emilian Peev53722fa2019-02-22 17:47:20 -08002190 auto ret = serviceListener->initialize();
2191 if (ret != NO_ERROR) {
2192 String8 msg = String8::format("Failed to initialize service listener: %s (%d)",
2193 strerror(-ret), ret);
2194 ALOGE("%s: %s", __FUNCTION__, msg.string());
2195 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
2196 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002197 // The listener still needs to be added to the list of listeners, regardless of what
2198 // permissions the listener process has / whether it is a vendor listener. Since it might be
2199 // eligible to listen to other camera ids.
2200 mListenerList.emplace_back(serviceListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08002201 mUidPolicy->registerMonitorUid(clientUid);
Igor Murashkinbfc99152013-02-27 12:55:20 -08002202 }
2203
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002204 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07002205 {
Ruben Brunkcc776712015-02-17 20:18:47 -08002206 Mutex::Autolock lock(mCameraStatesLock);
2207 for (auto& i : mCameraStates) {
Shuzhen Wang43858162020-01-10 13:42:15 -08002208 cameraStatuses->emplace_back(i.first,
2209 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds());
Igor Murashkincba2c162013-03-20 15:56:31 -07002210 }
2211 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002212 // Remove the camera statuses that should be hidden from the client, we do
2213 // this after collecting the states in order to avoid holding
2214 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
2215 // the same time.
2216 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
2217 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
2218 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
2219 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
2220 ALOGE("%s: Invalid camera id %s, skipping status update",
2221 __FUNCTION__, s.cameraId.c_str());
2222 return true;
2223 }
2224 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
2225 clientUid);}), cameraStatuses->end());
2226
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002227 //cameraStatuses will have non-eligible camera ids removed.
2228 std::set<String16> idsChosenForCallback;
2229 for (const auto &s : *cameraStatuses) {
2230 idsChosenForCallback.insert(String16(s.cameraId));
2231 }
Igor Murashkincba2c162013-03-20 15:56:31 -07002232
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002233 /*
2234 * Immediately signal current torch status to this listener only
2235 * This may be a subset of all the devices, so don't include it in the response directly
2236 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002237 {
2238 Mutex::Autolock al(mTorchStatusMutex);
2239 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002240 String16 id = String16(mTorchStatusMap.keyAt(i).string());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002241 // The camera id is visible to the client. Fine to send torch
2242 // callback.
2243 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
2244 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
2245 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002246 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002247 }
2248
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002249 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08002250}
Ruben Brunkcc776712015-02-17 20:18:47 -08002251
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002252Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002253 ATRACE_CALL();
2254
Igor Murashkinbfc99152013-02-27 12:55:20 -08002255 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
2256
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002257 if (listener == 0) {
2258 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002259 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002260 }
2261
Igor Murashkinbfc99152013-02-27 12:55:20 -08002262 Mutex::Autolock lock(mServiceLock);
2263
Ruben Brunkcc776712015-02-17 20:18:47 -08002264 {
2265 Mutex::Autolock lock(mStatusListenerLock);
2266 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002267 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
2268 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid());
2269 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08002270 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002271 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002272 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002273 }
2274 }
2275
2276 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
2277 __FUNCTION__, listener.get());
2278
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002279 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08002280}
2281
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002282Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002283
2284 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002285 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
2286
2287 if (parameters == NULL) {
2288 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002289 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07002290 }
2291
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002292 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002293
2294 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002295 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07002296 // Error logged by caller
2297 return ret;
2298 }
2299
2300 String8 shimParamsString8 = shimParams.flatten();
2301 String16 shimParamsString16 = String16(shimParamsString8);
2302
2303 *parameters = shimParamsString16;
2304
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002305 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07002306}
2307
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002308Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
2309 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002310 ATRACE_CALL();
2311
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002312 const String8 id = String8(cameraId);
2313
2314 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002315
2316 switch (apiVersion) {
2317 case API_VERSION_1:
2318 case API_VERSION_2:
2319 break;
2320 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002321 String8 msg = String8::format("Unknown API version %d", apiVersion);
2322 ALOGE("%s: %s", __FUNCTION__, msg.string());
2323 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002324 }
2325
Emilian Peev28ad2ea2017-02-07 16:14:32 +00002326 int deviceVersion = getDeviceVersion(id);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002327 switch (deviceVersion) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002328 case CAMERA_DEVICE_API_VERSION_1_0:
2329 case CAMERA_DEVICE_API_VERSION_3_0:
2330 case CAMERA_DEVICE_API_VERSION_3_1:
2331 if (apiVersion == API_VERSION_2) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002332 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without shim",
2333 __FUNCTION__, id.string(), deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002334 *isSupported = false;
2335 } else { // if (apiVersion == API_VERSION_1) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002336 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always supported",
2337 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002338 *isSupported = true;
2339 }
2340 break;
2341 case CAMERA_DEVICE_API_VERSION_3_2:
2342 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -07002343 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002344 case CAMERA_DEVICE_API_VERSION_3_5:
Yin-Chia Yeh56d98ba2020-01-16 16:57:14 -08002345 case CAMERA_DEVICE_API_VERSION_3_6:
Shuzhen Wang83bff122020-11-20 15:51:39 -08002346 case CAMERA_DEVICE_API_VERSION_3_7:
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002347 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
2348 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002349 *isSupported = true;
2350 break;
2351 case -1: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002352 String8 msg = String8::format("Unknown camera ID %s", id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002353 ALOGE("%s: %s", __FUNCTION__, msg.string());
2354 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002355 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002356 default: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002357 String8 msg = String8::format("Unknown device version %x for device %s",
2358 deviceVersion, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002359 ALOGE("%s: %s", __FUNCTION__, msg.string());
2360 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
2361 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07002362 }
2363
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002364 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002365}
2366
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002367Status CameraService::isHiddenPhysicalCamera(const String16& cameraId,
2368 /*out*/ bool *isSupported) {
2369 ATRACE_CALL();
2370
2371 const String8 id = String8(cameraId);
2372
2373 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
2374 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(id.string());
2375
2376 return Status::ok();
2377}
2378
Ruben Brunkcc776712015-02-17 20:18:47 -08002379void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002380 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002381 for (auto& i : mActiveClientManager.getAll()) {
2382 auto clientSp = i->getValue();
2383 if (clientSp.get() == client) {
2384 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08002385 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07002386 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002387 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08002388}
2389
Ruben Brunkcc776712015-02-17 20:18:47 -08002390bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002391 bool ret = false;
2392 {
2393 // Acquire mServiceLock and prevent other clients from connecting
2394 std::unique_ptr<AutoConditionLock> lock =
2395 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08002396
Igor Murashkin634a5152013-02-20 17:15:11 -08002397
Ruben Brunkcc776712015-02-17 20:18:47 -08002398 std::vector<sp<BasicClient>> evicted;
2399 for (auto& i : mActiveClientManager.getAll()) {
2400 auto clientSp = i->getValue();
2401 if (clientSp.get() == nullptr) {
2402 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2403 mActiveClientManager.remove(i);
2404 continue;
2405 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08002406 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002407 mActiveClientManager.remove(i);
2408 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08002409
Ruben Brunkcc776712015-02-17 20:18:47 -08002410 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002411 clientSp->notifyError(
2412 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002413 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08002414 }
2415 }
2416
Ruben Brunkcc776712015-02-17 20:18:47 -08002417 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2418 // other clients from connecting in mServiceLockWrapper if held
2419 mServiceLock.unlock();
2420
Ruben Brunk36597b22015-03-20 22:15:57 -07002421 // Do not clear caller identity, remote caller should be client proccess
2422
Ruben Brunkcc776712015-02-17 20:18:47 -08002423 for (auto& i : evicted) {
2424 if (i.get() != nullptr) {
2425 i->disconnect();
2426 ret = true;
2427 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002428 }
2429
Ruben Brunkcc776712015-02-17 20:18:47 -08002430 // Reacquire mServiceLock
2431 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08002432
Ruben Brunkcc776712015-02-17 20:18:47 -08002433 } // lock is destroyed, allow further connect calls
2434
2435 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07002436}
2437
Ruben Brunkcc776712015-02-17 20:18:47 -08002438std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
2439 const String8& cameraId) const {
2440 std::shared_ptr<CameraState> state;
2441 {
2442 Mutex::Autolock lock(mCameraStatesLock);
2443 auto iter = mCameraStates.find(cameraId);
2444 if (iter != mCameraStates.end()) {
2445 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002446 }
2447 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002448 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002449}
2450
Ruben Brunkcc776712015-02-17 20:18:47 -08002451sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
2452 // Remove from active clients list
2453 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
2454 if (clientDescriptorPtr == nullptr) {
2455 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
2456 cameraId.string());
2457 return sp<BasicClient>{nullptr};
2458 }
2459
2460 return clientDescriptorPtr->getValue();
Keun young Parkd8973a72012-03-28 14:13:09 -07002461}
2462
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002463void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07002464 // Acquire mServiceLock and prevent other clients from connecting
2465 std::unique_ptr<AutoConditionLock> lock =
2466 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
2467
Ruben Brunk6267b532015-04-30 17:44:07 -07002468 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002469 for (size_t i = 0; i < newUserIds.size(); i++) {
2470 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07002471 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002472 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07002473 return;
2474 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002475 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07002476 }
2477
Ruben Brunka8ca9152015-04-07 14:23:40 -07002478
Ruben Brunk6267b532015-04-30 17:44:07 -07002479 if (newAllowedUsers == mAllowedUsers) {
2480 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
2481 return;
2482 }
2483
2484 logUserSwitch(mAllowedUsers, newAllowedUsers);
2485
2486 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07002487
2488 // Current user has switched, evict all current clients.
2489 std::vector<sp<BasicClient>> evicted;
2490 for (auto& i : mActiveClientManager.getAll()) {
2491 auto clientSp = i->getValue();
2492
2493 if (clientSp.get() == nullptr) {
2494 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2495 continue;
2496 }
2497
Ruben Brunk6267b532015-04-30 17:44:07 -07002498 // Don't evict clients that are still allowed.
2499 uid_t clientUid = clientSp->getClientUid();
2500 userid_t clientUserId = multiuser_get_user_id(clientUid);
2501 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
2502 continue;
2503 }
2504
Ruben Brunk36597b22015-03-20 22:15:57 -07002505 evicted.push_back(clientSp);
2506
2507 String8 curTime = getFormattedCurrentTime();
2508
2509 ALOGE("Evicting conflicting client for camera ID %s due to user change",
2510 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07002511
Ruben Brunk36597b22015-03-20 22:15:57 -07002512 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002513 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00002514 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
2515 " to user switch.", i->getKey().string(),
2516 String8{clientSp->getPackageName()}.string(),
2517 i->getOwnerId(), i->getPriority().getScore(),
2518 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07002519
2520 }
2521
2522 // Do not hold mServiceLock while disconnecting clients, but retain the condition
2523 // blocking other clients from connecting in mServiceLockWrapper if held.
2524 mServiceLock.unlock();
2525
2526 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07002527 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07002528
2529 for (auto& i : evicted) {
2530 i->disconnect();
2531 }
2532
Jayant Chowdhary12361932018-08-27 14:46:13 -07002533 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07002534
2535 // Reacquire mServiceLock
2536 mServiceLock.lock();
2537}
Ruben Brunkcc776712015-02-17 20:18:47 -08002538
Ruben Brunka8ca9152015-04-07 14:23:40 -07002539void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002540 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07002541 Mutex::Autolock l(mLogLock);
2542 mEventLog.add(String8::format("%s : %s", curTime.string(), event));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002543}
2544
Ruben Brunka8ca9152015-04-07 14:23:40 -07002545void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002546 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002547 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002548 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002549 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002550}
2551
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002552void CameraService::logDisconnectedOffline(const char* cameraId, int clientPid,
2553 const char* clientPackage) {
2554 // Log the clients evicted
2555 logEvent(String8::format("DISCONNECT offline device %s client for package %s (PID %d)",
2556 cameraId, clientPackage, clientPid));
2557}
2558
Ruben Brunka8ca9152015-04-07 14:23:40 -07002559void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002560 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002561 // Log the clients evicted
2562 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002563 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002564}
2565
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002566void CameraService::logConnectedOffline(const char* cameraId, int clientPid,
2567 const char* clientPackage) {
2568 // Log the clients evicted
2569 logEvent(String8::format("CONNECT offline device %s client for package %s (PID %d)", cameraId,
2570 clientPackage, clientPid));
2571}
2572
Ruben Brunka8ca9152015-04-07 14:23:40 -07002573void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002574 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002575 // Log the client rejected
2576 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002577 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002578}
2579
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002580void CameraService::logTorchEvent(const char* cameraId, const char *torchState, int clientPid) {
2581 // Log torch event
2582 logEvent(String8::format("Torch for camera id %s turned %s for client PID %d", cameraId,
2583 torchState, clientPid));
2584}
2585
Ruben Brunk6267b532015-04-30 17:44:07 -07002586void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
2587 const std::set<userid_t>& newUserIds) {
2588 String8 newUsers = toString(newUserIds);
2589 String8 oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002590 if (oldUsers.size() == 0) {
2591 oldUsers = "<None>";
2592 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07002593 // Log the new and old users
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002594 logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
Ruben Brunk6267b532015-04-30 17:44:07 -07002595 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002596}
2597
2598void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
2599 // Log the device removal
2600 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
2601}
2602
2603void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
2604 // Log the device removal
2605 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
2606}
2607
2608void CameraService::logClientDied(int clientPid, const char* reason) {
2609 // Log the device removal
2610 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07002611}
2612
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002613void CameraService::logServiceError(const char* msg, int errorCode) {
2614 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002615 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002616}
2617
Ruben Brunk36597b22015-03-20 22:15:57 -07002618status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
2619 uint32_t flags) {
2620
Mathias Agopian65ab4712010-07-14 17:59:35 -07002621 // Permission checks
2622 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002623 case SHELL_COMMAND_TRANSACTION: {
2624 int in = data.readFileDescriptor();
2625 int out = data.readFileDescriptor();
2626 int err = data.readFileDescriptor();
2627 int argc = data.readInt32();
2628 Vector<String16> args;
2629 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
2630 args.add(data.readString16());
2631 }
2632 sp<IBinder> unusedCallback;
2633 sp<IResultReceiver> resultReceiver;
2634 status_t status;
2635 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
2636 return status;
2637 }
2638 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
2639 return status;
2640 }
2641 status = shellCommand(in, out, err, args);
2642 if (resultReceiver != nullptr) {
2643 resultReceiver->send(status);
2644 }
2645 return NO_ERROR;
2646 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002647 }
2648
2649 return BnCameraService::onTransact(code, data, reply, flags);
2650}
2651
Mathias Agopian65ab4712010-07-14 17:59:35 -07002652// We share the media players for shutter and recording sound for all clients.
2653// A reference count is kept to determine when we will actually release the
2654// media players.
2655
Jaekyun Seokef498052018-03-23 13:09:44 +09002656sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
2657 sp<MediaPlayer> mp = new MediaPlayer();
2658 status_t error;
2659 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08002660 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09002661 error = mp->prepare();
2662 }
2663 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00002664 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09002665 mp->disconnect();
2666 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002667 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002668 }
2669 return mp;
2670}
2671
username5755fea2018-12-27 09:48:08 +08002672void CameraService::increaseSoundRef() {
2673 Mutex::Autolock lock(mSoundLock);
2674 mSoundRef++;
2675}
2676
2677void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002678 ATRACE_CALL();
2679
username5755fea2018-12-27 09:48:08 +08002680 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
2681 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
2682 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
2683 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
2684 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
2685 }
2686 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
2687 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
2688 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
2689 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002690 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08002691 }
2692 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
2693 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
2694 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
2695 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
2696 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002697 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002698}
2699
username5755fea2018-12-27 09:48:08 +08002700void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002701 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002702 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002703 if (--mSoundRef) return;
2704
2705 for (int i = 0; i < NUM_SOUNDS; i++) {
2706 if (mSoundPlayer[i] != 0) {
2707 mSoundPlayer[i]->disconnect();
2708 mSoundPlayer[i].clear();
2709 }
2710 }
2711}
2712
2713void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002714 ATRACE_CALL();
2715
Mathias Agopian65ab4712010-07-14 17:59:35 -07002716 LOG1("playSound(%d)", kind);
2717 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002718 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002719 sp<MediaPlayer> player = mSoundPlayer[kind];
2720 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08002721 player->seekTo(0);
2722 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002723 }
2724}
2725
2726// ----------------------------------------------------------------------------
2727
2728CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07002729 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002730 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09002731 const std::optional<String16>& clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002732 const String8& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07002733 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002734 int clientPid, uid_t clientUid,
2735 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002736 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08002737 IInterface::asBinder(cameraClient),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002738 clientPackageName, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07002739 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002740 clientPid, clientUid,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002741 servicePid),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002742 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08002743{
Jayant Chowdhary12361932018-08-27 14:46:13 -07002744 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002745 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002746
Igor Murashkin44cfcf02013-03-01 16:22:28 -08002747 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002748
username5755fea2018-12-27 09:48:08 +08002749 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002750
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002751 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002752}
2753
Mathias Agopian65ab4712010-07-14 17:59:35 -07002754// tear down the client
2755CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002756 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08002757 mDestructionStarted = true;
2758
username5755fea2018-12-27 09:48:08 +08002759 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002760 // unconditionally disconnect. function is idempotent
2761 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002762}
2763
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002764sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
2765
Igor Murashkin634a5152013-02-20 17:15:11 -08002766CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002767 const sp<IBinder>& remoteCallback,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09002768 const String16& clientPackageName, const std::optional<String16>& clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07002769 const String8& cameraIdStr, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002770 int clientPid, uid_t clientUid,
2771 int servicePid):
Emilian Peev8b64f282021-03-25 16:49:57 -07002772 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09002773 mClientPackageName(clientPackageName), mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002774 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002775 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07002776 mDisconnected(false), mUidIsTrusted(false),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002777 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002778 mRemoteBinder(remoteCallback)
Igor Murashkin634a5152013-02-20 17:15:11 -08002779{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002780 if (sCameraService == nullptr) {
2781 sCameraService = cameraService;
2782 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002783 mOpsActive = false;
Igor Murashkin634a5152013-02-20 17:15:11 -08002784 mDestructionStarted = false;
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08002785
2786 // In some cases the calling code has no access to the package it runs under.
2787 // For example, NDK camera API.
2788 // In this case we will get the packages for the calling UID and pick the first one
2789 // for attributing the app op. This will work correctly for runtime permissions
2790 // as for legacy apps we will toggle the app op for all packages in the UID.
2791 // The caveat is that the operation may be attributed to the wrong package and
2792 // stats based on app ops may be slightly off.
2793 if (mClientPackageName.size() <= 0) {
2794 sp<IServiceManager> sm = defaultServiceManager();
2795 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
2796 if (binder == 0) {
2797 ALOGE("Cannot get permission service");
2798 // Leave mClientPackageName unchanged (empty) and the further interaction
2799 // with camera will fail in BasicClient::startCameraOps
2800 return;
2801 }
2802
2803 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
2804 Vector<String16> packages;
2805
2806 permCtrl->getPackagesForUid(mClientUid, packages);
2807
2808 if (packages.isEmpty()) {
2809 ALOGE("No packages for calling UID");
2810 // Leave mClientPackageName unchanged (empty) and the further interaction
2811 // with camera will fail in BasicClient::startCameraOps
2812 return;
2813 }
2814 mClientPackageName = packages[0];
2815 }
Steven Moreland89a2c5c2020-01-31 15:02:25 -08002816 if (getCurrentServingCall() != BinderCallType::HWBINDER) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002817 mAppOpsManager = std::make_unique<AppOpsManager>();
2818 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07002819
2820 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08002821}
2822
2823CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002824 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08002825 mDestructionStarted = true;
2826}
2827
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002828binder::Status CameraService::BasicClient::disconnect() {
2829 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002830 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002831 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07002832 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07002833 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002834
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002835 sCameraService->removeByClient(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002836 sCameraService->logDisconnected(mCameraIdStr, mClientPid, String8(mClientPackageName));
Peter Kalauskasa29c1352018-10-10 12:05:42 -07002837 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
2838 mCameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002839
2840 sp<IBinder> remote = getRemote();
2841 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002842 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08002843 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002844
2845 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07002846 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002847 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
2848 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
2849 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002850
Igor Murashkincba2c162013-03-20 15:56:31 -07002851 // client shouldn't be able to call into us anymore
2852 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002853
2854 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08002855}
2856
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002857status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
2858 // No dumping of clients directly over Binder,
2859 // must go through CameraService::dump
2860 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07002861 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002862 return OK;
2863}
2864
Ruben Brunkcc776712015-02-17 20:18:47 -08002865String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002866 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08002867}
2868
Emilian Peev8b64f282021-03-25 16:49:57 -07002869int CameraService::BasicClient::getCameraFacing() const {
2870 return mCameraFacing;
2871}
2872
2873int CameraService::BasicClient::getCameraOrientation() const {
2874 return mOrientation;
2875}
Ruben Brunkcc776712015-02-17 20:18:47 -08002876
2877int CameraService::BasicClient::getClientPid() const {
2878 return mClientPid;
2879}
2880
Ruben Brunk6267b532015-04-30 17:44:07 -07002881uid_t CameraService::BasicClient::getClientUid() const {
2882 return mClientUid;
2883}
2884
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002885bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
2886 // Defaults to API2.
2887 return level == API_2;
2888}
2889
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002890status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002891 {
2892 Mutex::Autolock l(mAudioRestrictionLock);
2893 mAudioRestriction = mode;
2894 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002895 sCameraService->updateAudioRestriction();
2896 return OK;
2897}
2898
2899int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002900 return sCameraService->updateAudioRestriction();
2901}
2902
2903int32_t CameraService::BasicClient::getAudioRestriction() const {
2904 Mutex::Autolock l(mAudioRestrictionLock);
2905 return mAudioRestriction;
2906}
2907
2908bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
2909 switch (mode) {
2910 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
2911 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
2912 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
2913 return true;
2914 default:
2915 return false;
2916 }
2917}
2918
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002919status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002920 ATRACE_CALL();
2921
Igor Murashkine6800ce2013-03-04 17:25:57 -08002922 {
2923 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002924 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08002925 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002926 if (mAppOpsManager != nullptr) {
2927 // Notify app ops that the camera is not available
2928 mOpsCallback = new OpsCallback(this);
2929 int32_t res;
2930 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
2931 mClientPackageName, mOpsCallback);
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002932 res = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
2933 mClientPackageName, /*startIfModeDefault*/ false, mClientFeatureId,
2934 String16("start camera ") + String16(mCameraIdStr));
Igor Murashkine6800ce2013-03-04 17:25:57 -08002935
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002936 if (res == AppOpsManager::MODE_ERRORED) {
2937 ALOGI("Camera %s: Access for \"%s\" has been revoked",
2938 mCameraIdStr.string(), String8(mClientPackageName).string());
2939 return PERMISSION_DENIED;
2940 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002941
Shuzhen Wang2c656792020-04-13 17:36:49 -07002942 // If the calling Uid is trusted (a native service), the AppOpsManager could
2943 // return MODE_IGNORED. Do not treat such case as error.
2944 if (!mUidIsTrusted && res == AppOpsManager::MODE_IGNORED) {
Evan Severson09ab4002021-02-10 14:15:19 -08002945 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
2946 mClientPackageName);
2947 bool isCameraPrivacyEnabled =
2948 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled(
2949 multiuser_get_user_id(mClientUid));
2950 if (!isUidActive || !isCameraPrivacyEnabled) {
2951 ALOGI("Camera %s: Access for \"%s\" has been restricted",
2952 mCameraIdStr.string(), String8(mClientPackageName).string());
2953 // Return the same error as for device policy manager rejection
2954 return -EACCES;
2955 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002956 }
Svetoslav28e8ef72015-05-11 19:21:31 -07002957 }
2958
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002959 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002960
2961 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002962 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002963
Emilian Peev53722fa2019-02-22 17:47:20 -08002964 sCameraService->mUidPolicy->registerMonitorUid(mClientUid);
2965
Shuzhen Wang695044d2020-03-06 09:02:23 -08002966 // Notify listeners of camera open/close status
2967 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
2968
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002969 return OK;
2970}
2971
2972status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002973 ATRACE_CALL();
2974
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002975 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002976 if (mOpsActive) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002977 // Notify app ops that the camera is available again
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002978 if (mAppOpsManager != nullptr) {
2979 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002980 mClientPackageName, mClientFeatureId);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002981 mOpsActive = false;
2982 }
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002983 // This function is called when a client disconnects. This should
2984 // release the camera, but actually only if it was in a proper
2985 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002986 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002987 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002988
Ruben Brunkcc776712015-02-17 20:18:47 -08002989 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002990 sCameraService->updateStatus(StatusInternal::PRESENT,
2991 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002992 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002993 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002994 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
2995 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002996 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002997 mOpsCallback.clear();
2998
Emilian Peev53722fa2019-02-22 17:47:20 -08002999 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid);
3000
Shuzhen Wang695044d2020-03-06 09:02:23 -08003001 // Notify listeners of camera open/close status
3002 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
3003
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003004 return OK;
3005}
3006
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003007void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003008 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003009 if (mAppOpsManager == nullptr) {
3010 return;
3011 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003012 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003013 if (op != AppOpsManager::OP_CAMERA) {
3014 ALOGW("Unexpected app ops notification received: %d", op);
3015 return;
3016 }
3017
3018 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003019 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003020 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003021 ALOGV("checkOp returns: %d, %s ", res,
3022 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
3023 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
3024 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
3025 "UNKNOWN");
3026
Shuzhen Wang64900852021-02-05 09:03:29 -08003027 if (res == AppOpsManager::MODE_ERRORED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003028 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003029 String8(mClientPackageName).string());
Svet Ganova453d0d2018-01-11 15:37:58 -08003030 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08003031 } else if (res == AppOpsManager::MODE_IGNORED) {
3032 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Evan Severson09ab4002021-02-10 14:15:19 -08003033 bool isCameraPrivacyEnabled =
3034 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled(
3035 multiuser_get_user_id(mClientUid));
Shuzhen Wang64900852021-02-05 09:03:29 -08003036 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d",
3037 mCameraIdStr.string(), String8(mClientPackageName).string(),
3038 mUidIsTrusted, isUidActive);
3039 // If the calling Uid is trusted (a native service), or the client Uid is active (WAR for
3040 // b/175320666), the AppOpsManager could return MODE_IGNORED. Do not treat such cases as
3041 // error.
Evan Severson09ab4002021-02-10 14:15:19 -08003042 if (!mUidIsTrusted && isUidActive && isCameraPrivacyEnabled) {
3043 setCameraMute(true);
3044 } else if (!mUidIsTrusted && !isUidActive) {
Shuzhen Wang64900852021-02-05 09:03:29 -08003045 block();
3046 }
Evan Severson09ab4002021-02-10 14:15:19 -08003047 } else if (res == AppOpsManager::MODE_ALLOWED) {
3048 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003049 }
3050}
3051
Svet Ganova453d0d2018-01-11 15:37:58 -08003052void CameraService::BasicClient::block() {
3053 ATRACE_CALL();
3054
3055 // Reset the client PID to allow server-initiated disconnect,
3056 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003057 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08003058 CaptureResultExtras resultExtras; // a dummy result (invalid)
3059 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
3060 disconnect();
3061}
3062
Mathias Agopian65ab4712010-07-14 17:59:35 -07003063// ----------------------------------------------------------------------------
3064
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003065void CameraService::Client::notifyError(int32_t errorCode,
Jianing Weicb0652e2014-03-12 18:29:36 -07003066 const CaptureResultExtras& resultExtras) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08003067 (void) resultExtras;
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003068 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07003069 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
3070 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
3071 api1ErrorCode = CAMERA_ERROR_DISABLED;
3072 }
3073 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003074 } else {
3075 ALOGE("mRemoteCallback is NULL!!");
3076 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003077}
3078
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003079// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003080binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003081 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003082 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08003083}
3084
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003085bool CameraService::Client::canCastToApiClient(apiLevel level) const {
3086 return level == API_1;
3087}
3088
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003089CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
3090 mClient(client) {
3091}
3092
3093void CameraService::Client::OpsCallback::opChanged(int32_t op,
3094 const String16& packageName) {
3095 sp<BasicClient> client = mClient.promote();
3096 if (client != NULL) {
3097 client->opChanged(op, packageName);
3098 }
3099}
3100
Mathias Agopian65ab4712010-07-14 17:59:35 -07003101// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08003102// UidPolicy
3103// ----------------------------------------------------------------------------
3104
3105void CameraService::UidPolicy::registerSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003106 Mutex::Autolock _l(mUidLock);
3107
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003108 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07003109 status_t res = mAm.linkToDeath(this);
3110 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08003111 | ActivityManager::UID_OBSERVER_IDLE
Emilian Peev53722fa2019-02-22 17:47:20 -08003112 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganova453d0d2018-01-11 15:37:58 -08003113 ActivityManager::PROCESS_STATE_UNKNOWN,
3114 String16("cameraserver"));
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003115 if (res == OK) {
3116 mRegistered = true;
3117 ALOGV("UidPolicy: Registered with ActivityManager");
3118 }
Svet Ganova453d0d2018-01-11 15:37:58 -08003119}
3120
3121void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003122 Mutex::Autolock _l(mUidLock);
3123
Steven Moreland2f348142019-07-02 15:59:07 -07003124 mAm.unregisterUidObserver(this);
3125 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003126 mRegistered = false;
3127 mActiveUids.clear();
3128 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08003129}
3130
3131void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
3132 onUidIdle(uid, disabled);
3133}
3134
3135void CameraService::UidPolicy::onUidActive(uid_t uid) {
3136 Mutex::Autolock _l(mUidLock);
3137 mActiveUids.insert(uid);
3138}
3139
3140void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
3141 bool deleted = false;
3142 {
3143 Mutex::Autolock _l(mUidLock);
3144 if (mActiveUids.erase(uid) > 0) {
3145 deleted = true;
3146 }
3147 }
3148 if (deleted) {
3149 sp<CameraService> service = mService.promote();
3150 if (service != nullptr) {
3151 service->blockClientsForUid(uid);
3152 }
3153 }
3154}
3155
Emilian Peev53722fa2019-02-22 17:47:20 -08003156void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07003157 int64_t procStateSeq __unused, int32_t capability __unused) {
Emilian Peev53722fa2019-02-22 17:47:20 -08003158 bool procStateChange = false;
3159 {
3160 Mutex::Autolock _l(mUidLock);
3161 if ((mMonitoredUids.find(uid) != mMonitoredUids.end()) &&
3162 (mMonitoredUids[uid].first != procState)) {
3163 mMonitoredUids[uid].first = procState;
3164 procStateChange = true;
3165 }
3166 }
3167
3168 if (procStateChange) {
3169 sp<CameraService> service = mService.promote();
3170 if (service != nullptr) {
3171 service->notifyMonitoredUids();
3172 }
3173 }
3174}
3175
3176void CameraService::UidPolicy::registerMonitorUid(uid_t uid) {
3177 Mutex::Autolock _l(mUidLock);
3178 auto it = mMonitoredUids.find(uid);
3179 if (it != mMonitoredUids.end()) {
3180 it->second.second++;
3181 } else {
3182 mMonitoredUids.emplace(
3183 std::pair<uid_t, std::pair<int32_t, size_t>> (uid,
3184 std::pair<int32_t, size_t> (ActivityManager::PROCESS_STATE_NONEXISTENT, 1)));
3185 }
3186}
3187
3188void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid) {
3189 Mutex::Autolock _l(mUidLock);
3190 auto it = mMonitoredUids.find(uid);
3191 if (it != mMonitoredUids.end()) {
3192 it->second.second--;
3193 if (it->second.second == 0) {
3194 mMonitoredUids.erase(it);
3195 }
3196 } else {
3197 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
3198 }
3199}
3200
Svet Ganov7b4ab782018-03-25 12:48:10 -07003201bool CameraService::UidPolicy::isUidActive(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003202 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003203 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003204}
3205
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003206static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
3207static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003208
Svet Ganov7b4ab782018-03-25 12:48:10 -07003209bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003210 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003211 // If activity manager is unreachable, assume everything is active
3212 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003213 return true;
3214 }
3215 auto it = mOverrideUids.find(uid);
3216 if (it != mOverrideUids.end()) {
3217 return it->second;
3218 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003219 bool active = mActiveUids.find(uid) != mActiveUids.end();
3220 if (!active) {
3221 // We want active UIDs to always access camera with their first attempt since
3222 // there is no guarantee the app is robustly written and would retry getting
3223 // the camera on failure. The inverse case is not a problem as we would take
3224 // camera away soon once we get the callback that the uid is no longer active.
3225 ActivityManager am;
3226 // Okay to access with a lock held as UID changes are dispatched without
3227 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07003228 int64_t startTimeMillis = 0;
3229 do {
3230 // TODO: Fix this b/109950150!
3231 // Okay this is a hack. There is a race between the UID turning active and
3232 // activity being resumed. The proper fix is very risky, so we temporary add
3233 // some polling which should happen pretty rarely anyway as the race is hard
3234 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003235 active = mActiveUids.find(uid) != mActiveUids.end();
Hui Yu12c7ec72020-05-04 17:40:52 +00003236 if (!active) active = am.isUidActive(uid, callingPackage);
Svet Ganov94ec46f2018-06-08 15:03:46 -07003237 if (active) {
3238 break;
3239 }
3240 if (startTimeMillis <= 0) {
3241 startTimeMillis = uptimeMillis();
3242 }
3243 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003244 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003245 if (remainingTimeMillis <= 0) {
3246 break;
3247 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003248 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
3249
3250 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003251 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003252 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003253 } while (true);
3254
Svet Ganov7b4ab782018-03-25 12:48:10 -07003255 if (active) {
3256 // Now that we found out the UID is actually active, cache that
3257 mActiveUids.insert(uid);
3258 }
3259 }
3260 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08003261}
3262
Varun Shahb42f1eb2019-04-16 14:45:13 -07003263int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
3264 Mutex::Autolock _l(mUidLock);
3265 return getProcStateLocked(uid);
3266}
3267
3268int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
3269 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
3270 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
3271 procState = mMonitoredUids[uid].first;
3272 }
3273 return procState;
3274}
3275
Svet Ganov7b4ab782018-03-25 12:48:10 -07003276void CameraService::UidPolicy::UidPolicy::addOverrideUid(uid_t uid,
3277 String16 callingPackage, bool active) {
3278 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08003279}
3280
Svet Ganov7b4ab782018-03-25 12:48:10 -07003281void CameraService::UidPolicy::removeOverrideUid(uid_t uid, String16 callingPackage) {
3282 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08003283}
3284
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003285void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
3286 Mutex::Autolock _l(mUidLock);
3287 ALOGV("UidPolicy: ActivityManager has died");
3288 mRegistered = false;
3289 mActiveUids.clear();
3290}
3291
Svet Ganov7b4ab782018-03-25 12:48:10 -07003292void CameraService::UidPolicy::updateOverrideUid(uid_t uid, String16 callingPackage,
3293 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003294 bool wasActive = false;
3295 bool isActive = false;
3296 {
3297 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003298 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003299 mOverrideUids.erase(uid);
3300 if (insert) {
3301 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
3302 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003303 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003304 }
3305 if (wasActive != isActive && !isActive) {
3306 sp<CameraService> service = mService.promote();
3307 if (service != nullptr) {
3308 service->blockClientsForUid(uid);
3309 }
3310 }
3311}
3312
3313// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08003314// SensorPrivacyPolicy
3315// ----------------------------------------------------------------------------
3316void CameraService::SensorPrivacyPolicy::registerSelf() {
3317 Mutex::Autolock _l(mSensorPrivacyLock);
3318 if (mRegistered) {
3319 return;
3320 }
Evan Severson09ab4002021-02-10 14:15:19 -08003321 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08003322 mSpm.addSensorPrivacyListener(this);
3323 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
3324 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003325 if (res == OK) {
3326 mRegistered = true;
3327 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
3328 }
3329}
3330
3331void CameraService::SensorPrivacyPolicy::unregisterSelf() {
3332 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08003333 mSpm.removeSensorPrivacyListener(this);
3334 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003335 mRegistered = false;
3336 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
3337}
3338
3339bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
3340 Mutex::Autolock _l(mSensorPrivacyLock);
3341 return mSensorPrivacyEnabled;
3342}
3343
Evan Severson09ab4002021-02-10 14:15:19 -08003344bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled(userid_t userId) {
3345 if (!hasCameraPrivacyFeature()) {
3346 return false;
3347 }
3348 return mSpm.isIndividualSensorPrivacyEnabled(userId,
3349 SensorPrivacyManager::INDIVIDUAL_SENSOR_CAMERA);
3350}
3351
Michael Grooverd1d435a2018-12-18 17:39:42 -08003352binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
3353 {
3354 Mutex::Autolock _l(mSensorPrivacyLock);
3355 mSensorPrivacyEnabled = enabled;
3356 }
3357 // if sensor privacy is enabled then block all clients from accessing the camera
Evan Severson09ab4002021-02-10 14:15:19 -08003358 if (enabled) {
3359 sp<CameraService> service = mService.promote();
3360 if (service != nullptr) {
3361 service->blockAllClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08003362 }
3363 }
3364 return binder::Status::ok();
3365}
3366
3367void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
3368 Mutex::Autolock _l(mSensorPrivacyLock);
3369 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
3370 mRegistered = false;
3371}
3372
Evan Severson09ab4002021-02-10 14:15:19 -08003373bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Severson671806e2021-04-20 16:44:53 -07003374 return mSpm.supportsSensorToggle(SensorPrivacyManager::INDIVIDUAL_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08003375}
3376
Michael Grooverd1d435a2018-12-18 17:39:42 -08003377// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003378// CameraState
3379// ----------------------------------------------------------------------------
3380
3381CameraService::CameraState::CameraState(const String8& id, int cost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003382 const std::set<String8>& conflicting, SystemCameraKind systemCameraKind) : mId(id),
3383 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
3384 mSystemCameraKind(systemCameraKind) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08003385
3386CameraService::CameraState::~CameraState() {}
3387
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003388CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003389 Mutex::Autolock lock(mStatusLock);
3390 return mStatus;
3391}
3392
Shuzhen Wang43858162020-01-10 13:42:15 -08003393std::vector<String8> CameraService::CameraState::getUnavailablePhysicalIds() const {
3394 Mutex::Autolock lock(mStatusLock);
3395 std::vector<String8> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
3396 return res;
3397}
3398
Ruben Brunkcc776712015-02-17 20:18:47 -08003399CameraParameters CameraService::CameraState::getShimParams() const {
3400 return mShimParams;
3401}
3402
3403void CameraService::CameraState::setShimParams(const CameraParameters& params) {
3404 mShimParams = params;
3405}
3406
3407int CameraService::CameraState::getCost() const {
3408 return mCost;
3409}
3410
3411std::set<String8> CameraService::CameraState::getConflicting() const {
3412 return mConflicting;
3413}
3414
3415String8 CameraService::CameraState::getId() const {
3416 return mId;
3417}
3418
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003419SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
3420 return mSystemCameraKind;
3421}
3422
Shuzhen Wang43858162020-01-10 13:42:15 -08003423bool CameraService::CameraState::addUnavailablePhysicalId(const String8& physicalId) {
3424 Mutex::Autolock lock(mStatusLock);
3425 auto result = mUnavailablePhysicalIds.insert(physicalId);
3426 return result.second;
3427}
3428
3429bool CameraService::CameraState::removeUnavailablePhysicalId(const String8& physicalId) {
3430 Mutex::Autolock lock(mStatusLock);
3431 auto count = mUnavailablePhysicalIds.erase(physicalId);
3432 return count > 0;
3433}
3434
Ruben Brunkcc776712015-02-17 20:18:47 -08003435// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07003436// ClientEventListener
3437// ----------------------------------------------------------------------------
3438
3439void CameraService::ClientEventListener::onClientAdded(
3440 const resource_policy::ClientDescriptor<String8,
3441 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003442 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003443 if (basicClient.get() != nullptr) {
3444 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3445 notifier.noteStartCamera(descriptor.getKey(),
3446 static_cast<int>(basicClient->getClientUid()));
3447 }
3448}
3449
3450void CameraService::ClientEventListener::onClientRemoved(
3451 const resource_policy::ClientDescriptor<String8,
3452 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003453 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003454 if (basicClient.get() != nullptr) {
3455 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3456 notifier.noteStopCamera(descriptor.getKey(),
3457 static_cast<int>(basicClient->getClientUid()));
3458 }
3459}
3460
3461
3462// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003463// CameraClientManager
3464// ----------------------------------------------------------------------------
3465
Ruben Brunk99e69712015-05-26 17:25:07 -07003466CameraService::CameraClientManager::CameraClientManager() {
3467 setListener(std::make_shared<ClientEventListener>());
3468}
3469
Ruben Brunkcc776712015-02-17 20:18:47 -08003470CameraService::CameraClientManager::~CameraClientManager() {}
3471
3472sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
3473 const String8& id) const {
3474 auto descriptor = get(id);
3475 if (descriptor == nullptr) {
3476 return sp<BasicClient>{nullptr};
3477 }
3478 return descriptor->getValue();
3479}
3480
3481String8 CameraService::CameraClientManager::toString() const {
3482 auto all = getAll();
3483 String8 ret("[");
3484 bool hasAny = false;
3485 for (auto& i : all) {
3486 hasAny = true;
3487 String8 key = i->getKey();
3488 int32_t cost = i->getCost();
3489 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00003490 int32_t score = i->getPriority().getScore();
3491 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08003492 auto conflicting = i->getConflicting();
3493 auto clientSp = i->getValue();
3494 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07003495 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08003496 if (clientSp.get() != nullptr) {
3497 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07003498 uid_t clientUid = clientSp->getClientUid();
3499 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003500 }
Emilian Peev8131a262017-02-01 12:33:43 +00003501 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
3502 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08003503
Ruben Brunk6267b532015-04-30 17:44:07 -07003504 if (clientSp.get() != nullptr) {
3505 ret.appendFormat("User Id: %d, ", clientUserId);
3506 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003507 if (packageName.size() != 0) {
3508 ret.appendFormat("Client Package Name: %s", packageName.string());
3509 }
3510
3511 ret.append(", Conflicting Client Devices: {");
3512 for (auto& j : conflicting) {
3513 ret.appendFormat("%s, ", j.string());
3514 }
3515 ret.append("})");
3516 }
3517 if (hasAny) ret.append("\n");
3518 ret.append("]\n");
3519 return ret;
3520}
3521
3522CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3523 const String8& key, const sp<BasicClient>& value, int32_t cost,
Emilian Peev8131a262017-02-01 12:33:43 +00003524 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
3525 int32_t state) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003526
Steven Moreland89a2c5c2020-01-31 15:02:25 -08003527 bool isVendorClient = getCurrentServingCall() == BinderCallType::HWBINDER;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003528 int32_t score_adj = isVendorClient ? kVendorClientScore : score;
3529 int32_t state_adj = isVendorClient ? kVendorClientState: state;
3530
Ruben Brunkcc776712015-02-17 20:18:47 -08003531 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003532 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj, isVendorClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08003533}
3534
3535CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3536 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
3537 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00003538 partial->getConflicting(), partial->getPriority().getScore(),
3539 partial->getOwnerId(), partial->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08003540}
3541
3542// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07003543
3544static const int kDumpLockRetries = 50;
3545static const int kDumpLockSleep = 60000;
3546
3547static bool tryLock(Mutex& mutex)
3548{
3549 bool locked = false;
3550 for (int i = 0; i < kDumpLockRetries; ++i) {
3551 if (mutex.tryLock() == NO_ERROR) {
3552 locked = true;
3553 break;
3554 }
3555 usleep(kDumpLockSleep);
3556 }
3557 return locked;
3558}
3559
3560status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003561 ATRACE_CALL();
3562
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003563 if (checkCallingPermission(sDumpPermission) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003564 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07003565 CameraThreadState::getCallingPid(),
3566 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003567 return NO_ERROR;
3568 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003569 bool locked = tryLock(mServiceLock);
3570 // failed to lock - CameraService is probably deadlocked
3571 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003572 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003573 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003574
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003575 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003576 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07003577
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003578 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003579 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08003580
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003581 if (locked) mServiceLock.unlock();
3582 return NO_ERROR;
3583 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003584 dprintf(fd, "\n== Service global info: ==\n\n");
3585 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003586 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07003587 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
3588 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003589 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
3590 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
3591 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003592 String8 activeClientString = mActiveClientManager.toString();
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003593 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
3594 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003595
3596 dumpEventLog(fd);
3597
3598 bool stateLocked = tryLock(mCameraStatesLock);
3599 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003600 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003601 }
3602
Emilian Peevbd8c5032018-02-14 23:05:40 +00003603 int argSize = args.size();
3604 for (int i = 0; i < argSize; i++) {
3605 if (args[i] == TagMonitor::kMonitorOption) {
3606 if (i + 1 < argSize) {
3607 mMonitorTags = String8(args[i + 1]);
3608 }
3609 break;
3610 }
3611 }
3612
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003613 for (auto& state : mCameraStates) {
3614 String8 cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003615
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003616 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003617
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003618 CameraParameters p = state.second->getShimParams();
3619 if (!p.isEmpty()) {
3620 dprintf(fd, " Camera1 API shim is using parameters:\n ");
3621 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003622 }
3623
3624 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08003625 if (clientDescriptor != nullptr) {
3626 dprintf(fd, " Device %s is open. Client instance dump:\n",
3627 cameraId.string());
3628 dprintf(fd, " Client priority score: %d state: %d\n",
3629 clientDescriptor->getPriority().getScore(),
3630 clientDescriptor->getPriority().getState());
3631 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
3632
3633 auto client = clientDescriptor->getValue();
3634 dprintf(fd, " Client package: %s\n",
3635 String8(client->getPackageName()).string());
3636
3637 client->dumpClient(fd, args);
3638 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003639 dprintf(fd, " Device %s is closed, no client instance\n",
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003640 cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003641 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003642
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003643 }
3644
3645 if (stateLocked) mCameraStatesLock.unlock();
3646
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003647 if (locked) mServiceLock.unlock();
3648
Emilian Peevf53f66e2017-04-11 14:29:43 +01003649 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003650
3651 dprintf(fd, "\n== Vendor tags: ==\n\n");
3652
3653 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
3654 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00003655 sp<VendorTagDescriptorCache> cache =
3656 VendorTagDescriptorCache::getGlobalVendorTagCache();
3657 if (cache == NULL) {
3658 dprintf(fd, "No vendor tags.\n");
3659 } else {
3660 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
3661 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003662 } else {
3663 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
3664 }
3665
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003666 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003667 dprintf(fd, "\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003668 camera3::CameraTraces::dump(fd, args);
3669
3670 // Process dump arguments, if any
3671 int n = args.size();
3672 String16 verboseOption("-v");
3673 String16 unreachableOption("--unreachable");
3674 for (int i = 0; i < n; i++) {
3675 if (args[i] == verboseOption) {
3676 // change logging level
3677 if (i + 1 >= n) continue;
3678 String8 levelStr(args[i+1]);
3679 int level = atoi(levelStr.string());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003680 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003681 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003682 } else if (args[i] == unreachableOption) {
3683 // Dump memory analysis
3684 // TODO - should limit be an argument parameter?
3685 UnreachableMemoryInfo info;
3686 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
3687 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003688 dprintf(fd, "\n== Unable to dump unreachable memory. "
3689 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003690 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003691 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003692 std::string s = info.ToString(/*log_contents*/ true);
3693 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003694 }
3695 }
3696 }
3697 return NO_ERROR;
3698}
3699
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003700void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003701 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003702
3703 Mutex::Autolock l(mLogLock);
3704 for (const auto& msg : mEventLog) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003705 dprintf(fd, " %s\n", msg.string());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003706 }
3707
3708 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003709 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003710 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003711 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003712 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003713 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003714}
3715
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003716void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003717 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003718 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
3719 if (mTorchClientMap[i] == who) {
3720 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003721 String8 cameraId = mTorchClientMap.keyAt(i);
3722 status_t res = mFlashlight->setTorchMode(cameraId, false);
3723 if (res) {
3724 ALOGE("%s: torch client died but couldn't turn off torch: "
3725 "%s (%d)", __FUNCTION__, strerror(-res), res);
3726 return;
3727 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003728 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003729 break;
3730 }
3731 }
3732}
3733
Ruben Brunkcc776712015-02-17 20:18:47 -08003734/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003735
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003736 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07003737 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
3738 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003739 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003740 // PID here is approximate and can be wrong.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003741 logClientDied(CameraThreadState::getCallingPid(), String8("Binder died unexpectedly"));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003742
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003743 // check torch client
3744 handleTorchClientBinderDied(who);
3745
3746 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08003747 if(!evictClientIdByRemote(who)) {
3748 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003749 return;
3750 }
3751
Ruben Brunkcc776712015-02-17 20:18:47 -08003752 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
3753 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003754}
3755
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003756void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003757 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08003758}
3759
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003760void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
3761 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003762 // Do not lock mServiceLock here or can get into a deadlock from
3763 // connect() -> disconnect -> updateStatus
3764
3765 auto state = getCameraState(cameraId);
3766
3767 if (state == nullptr) {
3768 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
3769 cameraId.string());
3770 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07003771 }
3772
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003773 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
3774 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3775 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3776 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
3777 return;
3778 }
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003779 bool supportsHAL3 = false;
3780 // supportsCameraApi also holds mInterfaceMutex, we can't call it in the
3781 // HIDL onStatusChanged wrapper call (we'll hold mStatusListenerLock and
3782 // mInterfaceMutex together, which can lead to deadlocks)
3783 binder::Status sRet =
3784 supportsCameraApi(String16(cameraId), hardware::ICameraService::API_VERSION_2,
3785 &supportsHAL3);
3786 if (!sRet.isOk()) {
3787 ALOGW("%s: Failed to determine if device supports HAL3 %s, supportsCameraApi call failed",
3788 __FUNCTION__, cameraId.string());
3789 return;
3790 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003791
3792 // Collect the logical cameras without holding mStatusLock in updateStatus
3793 // as that can lead to a deadlock(b/162192331).
3794 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08003795 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08003796 // of the listeners with both the mStatusLock and mStatusListenerLock held
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003797 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind, &supportsHAL3,
3798 &logicalCameraIds]
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003799 (const String8& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003800
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003801 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003802 // Update torch status if it has a flash unit.
3803 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003804 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003805 if (getTorchStatusLocked(cameraId, &torchStatus) !=
3806 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003807 TorchModeStatus newTorchStatus =
3808 status == StatusInternal::PRESENT ?
3809 TorchModeStatus::AVAILABLE_OFF :
3810 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003811 if (torchStatus != newTorchStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003812 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003813 }
3814 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003815 }
3816
3817 Mutex::Autolock lock(mStatusListenerLock);
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003818 notifyPhysicalCameraStatusLocked(mapToInterface(status), String16(cameraId),
3819 logicalCameraIds, deviceKind);
Shuzhen Wang43858162020-01-10 13:42:15 -08003820
Ruben Brunkcc776712015-02-17 20:18:47 -08003821 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003822 bool isVendorListener = listener->isVendorListener();
3823 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
3824 listener->getListenerPid(), listener->getListenerUid()) ||
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07003825 (isVendorListener && !supportsHAL3)) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003826 ALOGV("Skipping discovery callback for system-only camera/HAL1 device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003827 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003828 continue;
3829 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003830 listener->getListener()->onStatusChanged(mapToInterface(status),
Emilian Peev53722fa2019-02-22 17:47:20 -08003831 String16(cameraId));
Ruben Brunkcc776712015-02-17 20:18:47 -08003832 }
3833 });
Igor Murashkincba2c162013-03-20 15:56:31 -07003834}
3835
Shuzhen Wang695044d2020-03-06 09:02:23 -08003836void CameraService::updateOpenCloseStatus(const String8& cameraId, bool open,
3837 const String16& clientPackageName) {
3838 Mutex::Autolock lock(mStatusListenerLock);
3839
3840 for (const auto& it : mListenerList) {
3841 if (!it->isOpenCloseCallbackAllowed()) {
3842 continue;
3843 }
3844
3845 binder::Status ret;
3846 String16 cameraId64(cameraId);
3847 if (open) {
3848 ret = it->getListener()->onCameraOpened(cameraId64, clientPackageName);
3849 } else {
3850 ret = it->getListener()->onCameraClosed(cameraId64);
3851 }
3852 if (!ret.isOk()) {
3853 ALOGE("%s: Failed to trigger onCameraOpened/onCameraClosed callback: %d", __FUNCTION__,
3854 ret.exceptionCode());
3855 }
3856 }
3857}
3858
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003859template<class Func>
3860void CameraService::CameraState::updateStatus(StatusInternal status,
3861 const String8& cameraId,
3862 std::initializer_list<StatusInternal> rejectSourceStates,
3863 Func onStatusUpdatedLocked) {
3864 Mutex::Autolock lock(mStatusLock);
3865 StatusInternal oldStatus = mStatus;
3866 mStatus = status;
3867
3868 if (oldStatus == status) {
3869 return;
3870 }
3871
3872 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
3873 cameraId.string(), oldStatus, status);
3874
3875 if (oldStatus == StatusInternal::NOT_PRESENT &&
3876 (status != StatusInternal::PRESENT &&
3877 status != StatusInternal::ENUMERATING)) {
3878
3879 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
3880 __FUNCTION__);
3881 mStatus = oldStatus;
3882 return;
3883 }
3884
3885 /**
3886 * Sometimes we want to conditionally do a transition.
3887 * For example if a client disconnects, we want to go to PRESENT
3888 * only if we weren't already in NOT_PRESENT or ENUMERATING.
3889 */
3890 for (auto& rejectStatus : rejectSourceStates) {
3891 if (oldStatus == rejectStatus) {
3892 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
3893 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
3894 mStatus = oldStatus;
3895 return;
3896 }
3897 }
3898
3899 onStatusUpdatedLocked(cameraId, status);
3900}
3901
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003902status_t CameraService::getTorchStatusLocked(
3903 const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003904 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003905 if (!status) {
3906 return BAD_VALUE;
3907 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003908 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3909 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003910 // invalid camera ID or the camera doesn't have a flash unit
3911 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003912 }
3913
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003914 *status = mTorchStatusMap.valueAt(index);
3915 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003916}
3917
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003918status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003919 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003920 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3921 if (index == NAME_NOT_FOUND) {
3922 return BAD_VALUE;
3923 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003924 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003925
3926 return OK;
3927}
3928
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003929std::list<String16> CameraService::getLogicalCameras(
3930 const String8& physicalCameraId) {
3931 std::list<String16> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08003932 Mutex::Autolock lock(mCameraStatesLock);
3933 for (const auto& state : mCameraStates) {
3934 std::vector<std::string> physicalCameraIds;
3935 if (!mCameraProviderManager->isLogicalCamera(state.first.c_str(), &physicalCameraIds)) {
3936 // This is not a logical multi-camera.
3937 continue;
3938 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003939 if (std::find(physicalCameraIds.begin(), physicalCameraIds.end(), physicalCameraId.c_str())
Shuzhen Wang43858162020-01-10 13:42:15 -08003940 == physicalCameraIds.end()) {
3941 // cameraId is not a physical camera of this logical multi-camera.
3942 continue;
3943 }
3944
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003945 retList.emplace_back(String16(state.first));
3946 }
3947 return retList;
3948}
3949
3950void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
3951 const String16& physicalCameraId, const std::list<String16>& logicalCameraIds,
3952 SystemCameraKind deviceKind) {
3953 // mStatusListenerLock is expected to be locked
3954 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08003955 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003956 // Note: we check only the deviceKind of the physical camera id
3957 // since, logical camera ids and their physical camera ids are
3958 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07003959 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
3960 listener->getListenerPid(), listener->getListenerUid())) {
3961 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003962 String8(physicalCameraId).c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07003963 continue;
3964 }
Shuzhen Wang43858162020-01-10 13:42:15 -08003965 listener->getListener()->onPhysicalCameraStatusChanged(status,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003966 logicalCameraId, physicalCameraId);
Shuzhen Wang43858162020-01-10 13:42:15 -08003967 }
3968 }
3969}
3970
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003971
Svet Ganova453d0d2018-01-11 15:37:58 -08003972void CameraService::blockClientsForUid(uid_t uid) {
3973 const auto clients = mActiveClientManager.getAll();
3974 for (auto& current : clients) {
3975 if (current != nullptr) {
3976 const auto basicClient = current->getValue();
3977 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
3978 basicClient->block();
3979 }
3980 }
3981 }
3982}
3983
Michael Grooverd1d435a2018-12-18 17:39:42 -08003984void CameraService::blockAllClients() {
3985 const auto clients = mActiveClientManager.getAll();
3986 for (auto& current : clients) {
3987 if (current != nullptr) {
3988 const auto basicClient = current->getValue();
3989 if (basicClient.get() != nullptr) {
3990 basicClient->block();
3991 }
3992 }
3993 }
3994}
3995
Svet Ganova453d0d2018-01-11 15:37:58 -08003996// NOTE: This is a remote API - make sure all args are validated
3997status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
3998 if (!checkCallingPermission(sManageCameraPermission, nullptr, nullptr)) {
3999 return PERMISSION_DENIED;
4000 }
4001 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
4002 return BAD_VALUE;
4003 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004004 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004005 return handleSetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07004006 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004007 return handleResetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07004008 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004009 return handleGetUidState(args, out, err);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004010 } else if (args.size() >= 2 && args[0] == String16("set-rotate-and-crop")) {
4011 return handleSetRotateAndCrop(args);
4012 } else if (args.size() >= 1 && args[0] == String16("get-rotate-and-crop")) {
4013 return handleGetRotateAndCrop(out);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004014 } else if (args.size() >= 2 && args[0] == String16("set-image-dump-mask")) {
4015 return handleSetImageDumpMask(args);
4016 } else if (args.size() >= 1 && args[0] == String16("get-image-dump-mask")) {
4017 return handleGetImageDumpMask(out);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004018 } else if (args.size() >= 2 && args[0] == String16("set-camera-mute")) {
4019 return handleSetCameraMute(args);
Svet Ganova453d0d2018-01-11 15:37:58 -08004020 } else if (args.size() == 1 && args[0] == String16("help")) {
4021 printHelp(out);
4022 return NO_ERROR;
4023 }
4024 printHelp(err);
4025 return BAD_VALUE;
4026}
4027
4028status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004029 String16 packageName = args[1];
4030
Svet Ganova453d0d2018-01-11 15:37:58 -08004031 bool active = false;
4032 if (args[2] == String16("active")) {
4033 active = true;
4034 } else if ((args[2] != String16("idle"))) {
4035 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
4036 return BAD_VALUE;
4037 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004038
4039 int userId = 0;
4040 if (args.size() >= 5 && args[3] == String16("--user")) {
4041 userId = atoi(String8(args[4]));
4042 }
4043
4044 uid_t uid;
4045 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
4046 return BAD_VALUE;
4047 }
4048
4049 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08004050 return NO_ERROR;
4051}
4052
4053status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004054 String16 packageName = args[1];
4055
4056 int userId = 0;
4057 if (args.size() >= 4 && args[2] == String16("--user")) {
4058 userId = atoi(String8(args[3]));
4059 }
4060
4061 uid_t uid;
4062 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004063 return BAD_VALUE;
4064 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004065
4066 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08004067 return NO_ERROR;
4068}
4069
4070status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004071 String16 packageName = args[1];
4072
4073 int userId = 0;
4074 if (args.size() >= 4 && args[2] == String16("--user")) {
4075 userId = atoi(String8(args[3]));
4076 }
4077
4078 uid_t uid;
4079 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004080 return BAD_VALUE;
4081 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004082
4083 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004084 return dprintf(out, "active\n");
4085 } else {
4086 return dprintf(out, "idle\n");
4087 }
4088}
4089
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004090status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
4091 int rotateValue = atoi(String8(args[1]));
4092 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
4093 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
4094 Mutex::Autolock lock(mServiceLock);
4095
4096 mOverrideRotateAndCropMode = rotateValue;
4097
4098 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
4099
4100 const auto clients = mActiveClientManager.getAll();
4101 for (auto& current : clients) {
4102 if (current != nullptr) {
4103 const auto basicClient = current->getValue();
4104 if (basicClient.get() != nullptr) {
4105 basicClient->setRotateAndCropOverride(rotateValue);
4106 }
4107 }
4108 }
4109
4110 return OK;
4111}
4112
4113status_t CameraService::handleGetRotateAndCrop(int out) {
4114 Mutex::Autolock lock(mServiceLock);
4115
4116 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
4117}
4118
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004119status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
4120 char *endPtr;
4121 errno = 0;
4122 String8 maskString8 = String8(args[1]);
4123 long maskValue = strtol(maskString8.c_str(), &endPtr, 10);
4124
4125 if (errno != 0) return BAD_VALUE;
4126 if (endPtr != maskString8.c_str() + maskString8.size()) return BAD_VALUE;
4127 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
4128
4129 Mutex::Autolock lock(mServiceLock);
4130
4131 mImageDumpMask = maskValue;
4132
4133 return OK;
4134}
4135
4136status_t CameraService::handleGetImageDumpMask(int out) {
4137 Mutex::Autolock lock(mServiceLock);
4138
4139 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
4140}
4141
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004142status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
4143 int muteValue = strtol(String8(args[1]), nullptr, 10);
4144 if (errno != 0) return BAD_VALUE;
4145
4146 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
4147 Mutex::Autolock lock(mServiceLock);
4148
4149 mOverrideCameraMuteMode = (muteValue == 1);
4150
4151 const auto clients = mActiveClientManager.getAll();
4152 for (auto& current : clients) {
4153 if (current != nullptr) {
4154 const auto basicClient = current->getValue();
4155 if (basicClient.get() != nullptr) {
4156 if (basicClient->supportsCameraMute()) {
4157 basicClient->setCameraMute(mOverrideCameraMuteMode);
4158 }
4159 }
4160 }
4161 }
4162
4163 return OK;
4164}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004165
Svet Ganova453d0d2018-01-11 15:37:58 -08004166status_t CameraService::printHelp(int out) {
4167 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07004168 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
4169 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
4170 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004171 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
4172 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
4173 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004174 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
4175 " Valid values 0=OFF, 1=ON for JPEG\n"
4176 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004177 " set-camera-mute <0/1> enable or disable camera muting\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08004178 " help print this message\n");
4179}
4180
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004181int32_t CameraService::updateAudioRestriction() {
4182 Mutex::Autolock lock(mServiceLock);
4183 return updateAudioRestrictionLocked();
4184}
4185
4186int32_t CameraService::updateAudioRestrictionLocked() {
4187 int32_t mode = 0;
4188 // iterate through all active client
4189 for (const auto& i : mActiveClientManager.getAll()) {
4190 const auto clientSp = i->getValue();
4191 mode |= clientSp->getAudioRestriction();
4192 }
4193
4194 bool modeChanged = (mAudioRestriction != mode);
4195 mAudioRestriction = mode;
4196 if (modeChanged) {
4197 mAppOps.setCameraAudioRestriction(mode);
4198 }
4199 return mode;
4200}
4201
Mathias Agopian65ab4712010-07-14 17:59:35 -07004202}; // namespace android