blob: 99d10d2ee2de96316e84d70a0b83b8d1a3fcdd19 [file] [log] [blame]
Mathias Agopian65ab4712010-07-14 17:59:35 -07001/*
Ruben Brunkd1176ef2014-02-21 10:51:38 -08002 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Mathias Agopian65ab4712010-07-14 17:59:35 -070016
17#define LOG_TAG "CameraService"
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -070018#define ATRACE_TAG ATRACE_TAG_CAMERA
Iliyan Malchev8951a972011-04-14 16:55:59 -070019//#define LOG_NDEBUG 0
Mathias Agopian65ab4712010-07-14 17:59:35 -070020
Ruben Brunkcc776712015-02-17 20:18:47 -080021#include <algorithm>
22#include <climits>
Mathias Agopian65ab4712010-07-14 17:59:35 -070023#include <stdio.h>
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -080024#include <cstdlib>
Ruben Brunkcc776712015-02-17 20:18:47 -080025#include <cstring>
26#include <ctime>
27#include <string>
Mathias Agopian65ab4712010-07-14 17:59:35 -070028#include <sys/types.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080029#include <inttypes.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070030#include <pthread.h>
31
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080032#include <android/hardware/ICamera.h>
33#include <android/hardware/ICameraClient.h>
34
Alex Deymo9c2a2c22016-08-25 11:59:14 -070035#include <android-base/macros.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080036#include <android-base/parseint.h>
Jayant Chowdharyb61526c2019-05-13 19:37:42 -070037#include <android-base/stringprintf.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080038#include <binder/ActivityManager.h>
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -080039#include <binder/AppOpsManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070040#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070041#include <binder/MemoryBase.h>
42#include <binder/MemoryHeapBase.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080043#include <binder/PermissionController.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080044#include <binder/ProcessInfoService.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080045#include <binder/IResultReceiver.h>
Steven Moreland89a2c5c2020-01-31 15:02:25 -080046#include <binderthreadstate/CallerUtils.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070047#include <cutils/atomic.h>
Nipun Kwatrab5ca4612010-09-11 19:31:10 -070048#include <cutils/properties.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080049#include <cutils/misc.h>
Mathias Agopiandf712ea2012-02-25 18:48:35 -080050#include <gui/Surface.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070051#include <hardware/hardware.h>
Jayant Chowdharybe543d42018-08-15 13:16:14 -070052#include "hidl/HidlCameraService.h"
53#include <hidl/HidlTransportSupport.h>
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -080054#include <hwbinder/IPCThreadState.h>
Eino-Ville Talvalad89821e2016-04-20 11:23:50 -070055#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070056#include <media/AudioSystem.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080057#include <media/IMediaHTTPService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070058#include <media/mediaplayer.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070059#include <mediautils/BatteryNotifier.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070060#include <utils/Errors.h>
61#include <utils/Log.h>
62#include <utils/String16.h>
Svet Ganov94ec46f2018-06-08 15:03:46 -070063#include <utils/SystemClock.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080064#include <utils/Trace.h>
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080065#include <utils/CallStack.h>
Chien-Yu Chen98a668f2015-12-18 14:10:33 -080066#include <private/android_filesystem_config.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080067#include <system/camera_vendor_tags.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070068#include <system/camera_metadata.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080069
Ruben Brunkb2119af2014-05-09 19:57:56 -070070#include <system/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070071
72#include "CameraService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070073#include "api1/Camera2Client.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070074#include "api2/CameraDeviceClient.h"
Igor Murashkinff3e31d2013-10-23 16:40:06 -070075#include "utils/CameraTraces.h"
Emilian Peevbd8c5032018-02-14 23:05:40 +000076#include "utils/TagMonitor.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070077#include "utils/CameraThreadState.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070078#include "utils/CameraServiceProxyWrapper.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070079
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080080namespace {
81 const char* kPermissionServiceName = "permission";
82}; // namespace anonymous
83
Mathias Agopian65ab4712010-07-14 17:59:35 -070084namespace android {
85
Jayant Chowdharyb61526c2019-05-13 19:37:42 -070086using base::StringPrintf;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080087using binder::Status;
Jayant Chowdharybe543d42018-08-15 13:16:14 -070088using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -080089using hardware::ICamera;
90using hardware::ICameraClient;
91using hardware::ICameraServiceListener;
92using hardware::camera::common::V1_0::CameraDeviceStatus;
93using hardware::camera::common::V1_0::TorchModeStatus;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080094using hardware::camera2::utils::CameraIdAndSessionConfiguration;
95using hardware::camera2::utils::ConcurrentCameraIdCombination;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080096
Mathias Agopian65ab4712010-07-14 17:59:35 -070097// ----------------------------------------------------------------------------
98// Logging support -- this is for debugging only
99// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700100volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700101
Steve Blockb8a80522011-12-20 16:23:08 +0000102#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
103#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700104
105static void setLogLevel(int level) {
106 android_atomic_write(level, &gLogLevel);
107}
108
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800109// Convenience methods for constructing binder::Status objects for error returns
110
111#define STATUS_ERROR(errorCode, errorString) \
112 binder::Status::fromServiceSpecificError(errorCode, \
113 String8::format("%s:%d: %s", __FUNCTION__, __LINE__, errorString))
114
115#define STATUS_ERROR_FMT(errorCode, errorString, ...) \
116 binder::Status::fromServiceSpecificError(errorCode, \
117 String8::format("%s:%d: " errorString, __FUNCTION__, __LINE__, \
118 __VA_ARGS__))
119
Mathias Agopian65ab4712010-07-14 17:59:35 -0700120// ----------------------------------------------------------------------------
121
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700122static const String16 sDumpPermission("android.permission.DUMP");
Svet Ganova453d0d2018-01-11 15:37:58 -0800123static const String16 sManageCameraPermission("android.permission.MANAGE_CAMERA");
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700124static const String16 sCameraPermission("android.permission.CAMERA");
125static const String16 sSystemCameraPermission("android.permission.SYSTEM_CAMERA");
126static const String16
127 sCameraSendSystemEventsPermission("android.permission.CAMERA_SEND_SYSTEM_EVENTS");
Shuzhen Wang695044d2020-03-06 09:02:23 -0800128static const String16 sCameraOpenCloseListenerPermission(
129 "android.permission.CAMERA_OPEN_CLOSE_LISTENER");
Svet Ganova453d0d2018-01-11 15:37:58 -0800130
Eino-Ville Talvala7c602c32021-03-20 17:00:18 -0700131static constexpr int32_t kVendorClientScore = resource_policy::PERCEPTIBLE_APP_ADJ;
132static constexpr int32_t kVendorClientState = ActivityManager::PROCESS_STATE_PERSISTENT_UI;
133
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800134const String8 CameraService::kOfflineDevice("offline-");
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700135
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800136CameraService::CameraService() :
137 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800138 mNumberOfCameras(0),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700139 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700140 mSoundRef(0), mInitialized(false),
141 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000142 ALOGI("CameraService started (pid=%d)", getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800143 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700144}
145
Iliyan Malchev8951a972011-04-14 16:55:59 -0700146void CameraService::onFirstRef()
147{
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
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800227void CameraService::broadcastTorchModeStatus(const String8& cameraId, TorchModeStatus status) {
228 Mutex::Autolock lock(mStatusListenerLock);
229
230 for (auto& i : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700231 i->getListener()->onTorchStatusChanged(mapToInterface(status), String16{cameraId});
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800232 }
233}
234
Mathias Agopian65ab4712010-07-14 17:59:35 -0700235CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800236 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800237 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800238 mSensorPrivacyPolicy->unregisterSelf();
Evan Severson190ad252021-01-07 20:37:15 -0800239
240 for (auto const& [_, policy] : mCameraSensorPrivacyPolicies) {
241 policy->unregisterSelf();
242 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700243}
244
Emilian Peevaee727d2017-05-04 16:35:48 +0100245void CameraService::onNewProviderRegistered() {
246 enumerateProviders();
247}
248
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700249void CameraService::filterAPI1SystemCameraLocked(
250 const std::vector<std::string> &normalDeviceIds) {
251 mNormalDeviceIdsWithoutSystemCamera.clear();
252 for (auto &deviceId : normalDeviceIds) {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700253 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
254 if (getSystemCameraKind(String8(deviceId.c_str()), &deviceKind) != OK) {
255 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, deviceId.c_str());
256 continue;
257 }
258 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700259 // All system camera ids will necessarily come after public camera
260 // device ids as per the HAL interface contract.
261 break;
262 }
263 mNormalDeviceIdsWithoutSystemCamera.push_back(deviceId);
264 }
265 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
266 mNormalDeviceIdsWithoutSystemCamera.size());
267}
268
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700269status_t CameraService::getSystemCameraKind(const String8& cameraId, SystemCameraKind *kind) const {
270 auto state = getCameraState(cameraId);
271 if (state != nullptr) {
272 *kind = state->getSystemCameraKind();
273 return OK;
274 }
275 // Hidden physical camera ids won't have CameraState
276 return mCameraProviderManager->getSystemCameraKind(cameraId.c_str(), kind);
277}
278
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800279void CameraService::updateCameraNumAndIds() {
280 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700281 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
282 // Excludes hidden secure cameras
283 mNumberOfCameras =
284 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
285 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800286 mNormalDeviceIds =
287 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700288 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800289}
290
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100291void CameraService::addStates(const String8 id) {
292 std::string cameraId(id.c_str());
293 hardware::camera::common::V1_0::CameraResourceCost cost;
294 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700295 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100296 if (res != OK) {
297 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
298 return;
299 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700300 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
301 if (res != OK) {
302 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
303 return;
304 }
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100305 std::set<String8> conflicting;
306 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
307 conflicting.emplace(String8(cost.conflictingDevices[i].c_str()));
308 }
309
310 {
311 Mutex::Autolock lock(mCameraStatesLock);
312 mCameraStates.emplace(id, std::make_shared<CameraState>(id, cost.resourceCost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700313 conflicting, deviceKind));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100314 }
315
316 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100317 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100318 mTorchStatusMap.add(id, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800319
320 broadcastTorchModeStatus(id, TorchModeStatus::AVAILABLE_OFF);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100321 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800322
323 updateCameraNumAndIds();
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100324 logDeviceAdded(id, "Device added");
325}
326
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100327void CameraService::removeStates(const String8 id) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800328 updateCameraNumAndIds();
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100329 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100330 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100331 mTorchStatusMap.removeItem(id);
332 }
333
334 {
335 Mutex::Autolock lock(mCameraStatesLock);
336 mCameraStates.erase(id);
337 }
338}
339
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800340void CameraService::onDeviceStatusChanged(const String8& id,
341 CameraDeviceStatus newHalStatus) {
342 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
343 id.string(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700344
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800345 StatusInternal newStatus = mapToInternal(newHalStatus);
346
Ruben Brunkcc776712015-02-17 20:18:47 -0800347 std::shared_ptr<CameraState> state = getCameraState(id);
348
349 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700350 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100351 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700352 __FUNCTION__, id.string());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100353
354 // First add as absent to make sure clients are notified below
355 addStates(id);
356
357 updateStatus(newStatus, id);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700358 } else {
359 ALOGE("%s: Bad camera ID %s", __FUNCTION__, id.string());
360 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700361 return;
362 }
363
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800364 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800365
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800366 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800367 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700368 return;
369 }
370
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800371 if (newStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700372 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
373 newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800374
375 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
376 // to this device until the status changes
377 updateStatus(StatusInternal::NOT_PRESENT, id);
378
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800379 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700380 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800381 // Don't do this in updateStatus to avoid deadlock over mServiceLock
382 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700383
Ruben Brunkcc776712015-02-17 20:18:47 -0800384 // Remove cached shim parameters
385 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700386
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800387 // Remove online as well as offline client from the list of active clients,
388 // if they are present
389 clientToDisconnectOnline = removeClientLocked(id);
390 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + id);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700391 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800392
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800393 disconnectClient(id, clientToDisconnectOnline);
394 disconnectClient(kOfflineDevice + id, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700395
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100396 removeStates(id);
Ruben Brunkcc776712015-02-17 20:18:47 -0800397 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800398 if (oldStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700399 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
400 newStatus));
401 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800402 updateStatus(newStatus, id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700403 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800404}
Igor Murashkincba2c162013-03-20 15:56:31 -0700405
Shuzhen Wang43858162020-01-10 13:42:15 -0800406void CameraService::onDeviceStatusChanged(const String8& id,
407 const String8& physicalId,
408 CameraDeviceStatus newHalStatus) {
409 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
410 __FUNCTION__, id.string(), physicalId.string(), newHalStatus);
411
412 StatusInternal newStatus = mapToInternal(newHalStatus);
413
414 std::shared_ptr<CameraState> state = getCameraState(id);
415
416 if (state == nullptr) {
417 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
418 __FUNCTION__, id.string(), physicalId.string());
419 return;
420 }
421
422 StatusInternal logicalCameraStatus = state->getStatus();
423 if (logicalCameraStatus != StatusInternal::PRESENT &&
424 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
425 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
426 __FUNCTION__, physicalId.string(), newHalStatus, logicalCameraStatus);
427 return;
428 }
429
430 bool updated = false;
431 if (newStatus == StatusInternal::PRESENT) {
432 updated = state->removeUnavailablePhysicalId(physicalId);
433 } else {
434 updated = state->addUnavailablePhysicalId(physicalId);
435 }
436
437 if (updated) {
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800438 String8 idCombo = id + " : " + physicalId;
439 if (newStatus == StatusInternal::PRESENT) {
440 logDeviceAdded(idCombo,
441 String8::format("Device status changed to %d", newStatus));
442 } else {
443 logDeviceRemoved(idCombo,
444 String8::format("Device status changed to %d", newStatus));
445 }
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700446 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
447 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
448 if (getSystemCameraKind(id, &deviceKind) != OK) {
449 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.string());
450 return;
451 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800452 String16 id16(id), physicalId16(physicalId);
453 Mutex::Autolock lock(mStatusListenerLock);
454 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700455 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
456 listener->getListenerPid(), listener->getListenerUid())) {
457 ALOGV("Skipping discovery callback for system-only camera device %s",
458 id.c_str());
459 continue;
460 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800461 listener->getListener()->onPhysicalCameraStatusChanged(mapToInterface(newStatus),
462 id16, physicalId16);
463 }
464 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700465}
466
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800467void CameraService::disconnectClient(const String8& id, sp<BasicClient> clientToDisconnect) {
468 if (clientToDisconnect.get() != nullptr) {
469 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
470 __FUNCTION__, id.string());
471 // Notify the client of disconnection
472 clientToDisconnect->notifyError(
473 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
474 CaptureResultExtras{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800475 clientToDisconnect->disconnect();
476 }
477}
478
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800479void CameraService::onTorchStatusChanged(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800480 TorchModeStatus newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800481 Mutex::Autolock al(mTorchStatusMutex);
482 onTorchStatusChangedLocked(cameraId, newStatus);
483}
484
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800485void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800486 TorchModeStatus newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800487 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
488 __FUNCTION__, cameraId.string(), newStatus);
489
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800490 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800491 status_t res = getTorchStatusLocked(cameraId, &status);
492 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700493 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
494 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800495 return;
496 }
497 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800498 return;
499 }
500
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800501 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800502 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800503 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
504 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800505 return;
506 }
507
Ruben Brunkcc776712015-02-17 20:18:47 -0800508 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700509 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700510 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700511 auto iter = mTorchUidMap.find(cameraId);
512 if (iter != mTorchUidMap.end()) {
513 int oldUid = iter->second.second;
514 int newUid = iter->second.first;
515 BatteryNotifier& notifier(BatteryNotifier::getInstance());
516 if (oldUid != newUid) {
517 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800518 if (status == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700519 notifier.noteFlashlightOff(cameraId, oldUid);
520 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800521 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700522 notifier.noteFlashlightOn(cameraId, newUid);
523 }
524 iter->second.second = newUid;
525 } else {
526 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800527 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700528 notifier.noteFlashlightOn(cameraId, oldUid);
529 } else {
530 notifier.noteFlashlightOff(cameraId, oldUid);
531 }
532 }
533 }
534 }
535
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800536 broadcastTorchModeStatus(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800537}
538
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700539static bool hasPermissionsForSystemCamera(int callingPid, int callingUid) {
540 return checkPermission(sSystemCameraPermission, callingPid, callingUid) &&
541 checkPermission(sCameraPermission, callingPid, callingUid);
542}
543
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800544Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700545 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100546 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700547 bool hasSystemCameraPermissions =
548 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
549 CameraThreadState::getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700550 switch (type) {
551 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700552 if (hasSystemCameraPermissions) {
553 *numCameras = static_cast<int>(mNormalDeviceIds.size());
554 } else {
555 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
556 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800557 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700558 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700559 if (hasSystemCameraPermissions) {
560 *numCameras = mNumberOfCameras;
561 } else {
562 *numCameras = mNumberOfCamerasWithoutSystemCamera;
563 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800564 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700565 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800566 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700567 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800568 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
569 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700570 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800571 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700572}
573
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800574Status CameraService::getCameraInfo(int cameraId,
575 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700576 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100577 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700578 std::string cameraIdStr = cameraIdIntToStrLocked(cameraId);
579 if (shouldRejectSystemCameraConnection(String8(cameraIdStr.c_str()))) {
580 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
581 "characteristics for system only device %s: ", cameraIdStr.c_str());
582 }
Emilian Peevaee727d2017-05-04 16:35:48 +0100583
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800584 if (!mInitialized) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800585 return STATUS_ERROR(ERROR_DISCONNECTED,
586 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -0700587 }
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700588 bool hasSystemCameraPermissions =
589 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
590 CameraThreadState::getCallingUid());
591 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
592 if (hasSystemCameraPermissions) {
593 cameraIdBound = mNumberOfCameras;
594 }
595 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800596 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
597 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700598 }
599
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800600 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800601 status_t err = mCameraProviderManager->getCameraInfo(
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700602 cameraIdStr.c_str(), cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100603 if (err != OK) {
604 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
605 "Error retrieving camera info from device %d: %s (%d)", cameraId,
606 strerror(-err), err);
Ruben Brunkcc776712015-02-17 20:18:47 -0800607 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100608
Ruben Brunkcc776712015-02-17 20:18:47 -0800609 return ret;
610}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700611
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800612std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700613 const std::vector<std::string> *deviceIds = &mNormalDeviceIdsWithoutSystemCamera;
614 auto callingPid = CameraThreadState::getCallingPid();
615 auto callingUid = CameraThreadState::getCallingUid();
616 if (checkPermission(sSystemCameraPermission, callingPid, callingUid) ||
617 getpid() == callingPid) {
618 deviceIds = &mNormalDeviceIds;
619 }
620 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(deviceIds->size())) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800621 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700622 __FUNCTION__, cameraIdInt, deviceIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800623 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800624 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800625
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700626 return (*deviceIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800627}
628
629String8 CameraService::cameraIdIntToStr(int cameraIdInt) {
630 Mutex::Autolock lock(mServiceLock);
631 return String8(cameraIdIntToStrLocked(cameraIdInt).c_str());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800632}
633
634Status CameraService::getCameraCharacteristics(const String16& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800635 CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700636 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700637 if (!cameraInfo) {
638 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800639 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -0700640 }
641
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800642 if (!mInitialized) {
643 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800644 return STATUS_ERROR(ERROR_DISCONNECTED,
645 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -0700646 }
647
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700648 if (shouldRejectSystemCameraConnection(String8(cameraId))) {
649 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
650 "characteristics for system only device %s: ", String8(cameraId).string());
651 }
652
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800653 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800654
Emilian Peevf53f66e2017-04-11 14:29:43 +0100655 status_t res = mCameraProviderManager->getCameraCharacteristics(
656 String8(cameraId).string(), cameraInfo);
657 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700658 if (res == NAME_NOT_FOUND) {
659 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
660 "characteristics for unknown device %s: %s (%d)", String8(cameraId).string(),
661 strerror(-res), res);
662 } else {
663 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
664 "characteristics for device %s: %s (%d)", String8(cameraId).string(),
665 strerror(-res), res);
666 }
Ruben Brunkb2119af2014-05-09 19:57:56 -0700667 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700668 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
669 if (getSystemCameraKind(String8(cameraId), &deviceKind) != OK) {
670 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, String8(cameraId).string());
671 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera kind "
672 "for device %s", String8(cameraId).string());
673 }
Jayant Chowdhary12361932018-08-27 14:46:13 -0700674 int callingPid = CameraThreadState::getCallingPid();
675 int callingUid = CameraThreadState::getCallingUid();
Emilian Peeve20c6372018-08-14 18:45:53 +0100676 std::vector<int32_t> tagsRemoved;
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700677 // If it's not calling from cameraserver, check the permission only if
678 // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
679 // it would've already been checked in shouldRejectSystemCameraConnection.
Emilian Peeve20c6372018-08-14 18:45:53 +0100680 if ((callingPid != getpid()) &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700681 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700682 !checkPermission(sCameraPermission, callingPid, callingUid)) {
Emilian Peeve20c6372018-08-14 18:45:53 +0100683 res = cameraInfo->removePermissionEntries(
684 mCameraProviderManager->getProviderTagIdLocked(String8(cameraId).string()),
685 &tagsRemoved);
686 if (res != OK) {
687 cameraInfo->clear();
688 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
689 " characteristics needing camera permission for device %s: %s (%d)",
690 String8(cameraId).string(), strerror(-res), res);
691 }
692 }
693
694 if (!tagsRemoved.empty()) {
695 res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
696 tagsRemoved.data(), tagsRemoved.size());
697 if (res != OK) {
698 cameraInfo->clear();
699 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
700 "keys needing permission for device %s: %s (%d)", String8(cameraId).string(),
701 strerror(-res), res);
702 }
703 }
704
Zhijun He2b59be82013-09-25 10:14:30 -0700705 return ret;
706}
707
Ruben Brunkcc776712015-02-17 20:18:47 -0800708String8 CameraService::getFormattedCurrentTime() {
709 time_t now = time(nullptr);
710 char formattedTime[64];
711 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
712 return String8(formattedTime);
713}
714
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800715Status CameraService::getCameraVendorTagDescriptor(
716 /*out*/
717 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700718 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800719 if (!mInitialized) {
720 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800721 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800722 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -0800723 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
724 if (globalDescriptor != nullptr) {
725 *desc = *(globalDescriptor.get());
726 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800727 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800728}
729
Emilian Peev71c73a22017-03-21 16:35:51 +0000730Status CameraService::getCameraVendorTagCache(
731 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
732 ATRACE_CALL();
733 if (!mInitialized) {
734 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
735 return STATUS_ERROR(ERROR_DISCONNECTED,
736 "Camera subsystem not available");
737 }
738 sp<VendorTagDescriptorCache> globalCache =
739 VendorTagDescriptorCache::getGlobalVendorTagCache();
740 if (globalCache != nullptr) {
741 *cache = *(globalCache.get());
742 }
743 return Status::ok();
744}
745
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800746int CameraService::getDeviceVersion(const String8& cameraId, int* facing) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700747 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800748
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800749 int deviceVersion = 0;
750
Emilian Peevf53f66e2017-04-11 14:29:43 +0100751 status_t res;
752 hardware::hidl_version maxVersion{0,0};
753 res = mCameraProviderManager->getHighestSupportedVersion(cameraId.string(),
754 &maxVersion);
755 if (res != OK) return -1;
756 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800757
Emilian Peevf53f66e2017-04-11 14:29:43 +0100758 hardware::CameraInfo info;
759 if (facing) {
760 res = mCameraProviderManager->getCameraInfo(cameraId.string(), &info);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -0800761 if (res != OK) return -1;
Emilian Peevf53f66e2017-04-11 14:29:43 +0100762 *facing = info.facing;
Igor Murashkin634a5152013-02-20 17:15:11 -0800763 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100764
Igor Murashkin634a5152013-02-20 17:15:11 -0800765 return deviceVersion;
766}
767
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800768Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700769 switch(err) {
770 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800771 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800772 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800773 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
774 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800775 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800776 return STATUS_ERROR(ERROR_DISCONNECTED,
777 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700778 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800779 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
780 "Camera HAL encountered error %d: %s",
781 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700782 }
Igor Murashkinbfc99152013-02-27 12:55:20 -0800783}
784
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800785Status CameraService::makeClient(const sp<CameraService>& cameraService,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800786 const sp<IInterface>& cameraCb, const String16& packageName,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700787 const std::optional<String16>& featureId, const String8& cameraId,
788 int api1CameraId, int facing, int clientPid, uid_t clientUid, int servicePid,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800789 int deviceVersion, apiLevel effectiveApiLevel,
Ruben Brunkcc776712015-02-17 20:18:47 -0800790 /*out*/sp<BasicClient>* client) {
791
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700792 // Create CameraClient based on device version reported by the HAL.
793 switch(deviceVersion) {
794 case CAMERA_DEVICE_API_VERSION_1_0:
795 ALOGE("Camera using old HAL version: %d", deviceVersion);
796 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
797 "Camera device \"%s\" HAL version %d no longer supported",
798 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800799 break;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700800 case CAMERA_DEVICE_API_VERSION_3_0:
801 case CAMERA_DEVICE_API_VERSION_3_1:
802 case CAMERA_DEVICE_API_VERSION_3_2:
803 case CAMERA_DEVICE_API_VERSION_3_3:
804 case CAMERA_DEVICE_API_VERSION_3_4:
805 case CAMERA_DEVICE_API_VERSION_3_5:
806 case CAMERA_DEVICE_API_VERSION_3_6:
Shuzhen Wang83bff122020-11-20 15:51:39 -0800807 case CAMERA_DEVICE_API_VERSION_3_7:
Ruben Brunkcc776712015-02-17 20:18:47 -0800808 if (effectiveApiLevel == API_1) { // Camera1 API route
809 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800810 *client = new Camera2Client(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800811 cameraId, api1CameraId,
812 facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700813 servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800814 } else { // Camera2 API route
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800815 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
816 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800817 *client = new CameraDeviceClient(cameraService, tmp, packageName, featureId,
818 cameraId, facing, clientPid, clientUid, servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800819 }
820 break;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700821 default:
Ruben Brunkcc776712015-02-17 20:18:47 -0800822 // Should not be reachable
823 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800824 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800825 "Camera device \"%s\" has unknown HAL version %d",
826 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800827 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800828 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800829}
830
Ruben Brunk6267b532015-04-30 17:44:07 -0700831String8 CameraService::toString(std::set<userid_t> intSet) {
832 String8 s("");
833 bool first = true;
834 for (userid_t i : intSet) {
835 if (first) {
836 s.appendFormat("%d", i);
837 first = false;
838 } else {
839 s.appendFormat(", %d", i);
840 }
841 }
842 return s;
843}
844
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800845int32_t CameraService::mapToInterface(TorchModeStatus status) {
846 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
847 switch (status) {
848 case TorchModeStatus::NOT_AVAILABLE:
849 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
850 break;
851 case TorchModeStatus::AVAILABLE_OFF:
852 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
853 break;
854 case TorchModeStatus::AVAILABLE_ON:
855 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
856 break;
857 default:
858 ALOGW("Unknown new flash status: %d", status);
859 }
860 return serviceStatus;
861}
862
863CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
864 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
865 switch (status) {
866 case CameraDeviceStatus::NOT_PRESENT:
867 serviceStatus = StatusInternal::NOT_PRESENT;
868 break;
869 case CameraDeviceStatus::PRESENT:
870 serviceStatus = StatusInternal::PRESENT;
871 break;
872 case CameraDeviceStatus::ENUMERATING:
873 serviceStatus = StatusInternal::ENUMERATING;
874 break;
875 default:
876 ALOGW("Unknown new HAL device status: %d", status);
877 }
878 return serviceStatus;
879}
880
881int32_t CameraService::mapToInterface(StatusInternal status) {
882 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
883 switch (status) {
884 case StatusInternal::NOT_PRESENT:
885 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
886 break;
887 case StatusInternal::PRESENT:
888 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
889 break;
890 case StatusInternal::ENUMERATING:
891 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
892 break;
893 case StatusInternal::NOT_AVAILABLE:
894 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
895 break;
896 case StatusInternal::UNKNOWN:
897 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
898 break;
899 default:
900 ALOGW("Unknown new internal device status: %d", status);
901 }
902 return serviceStatus;
903}
904
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800905Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -0700906 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700907
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800908 String16 internalPackageName("cameraserver");
Ruben Brunkcc776712015-02-17 20:18:47 -0800909 String8 id = String8::format("%d", cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800910 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800911 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800912 if (!(ret = connectHelper<ICameraClient,Client>(
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800913 sp<ICameraClient>{nullptr}, id, cameraId,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +0900914 internalPackageName, {}, uid, USE_CALLING_PID,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700915 API_1, /*shimUpdateOnly*/ true, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800916 ).isOk()) {
917 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
Ruben Brunkb2119af2014-05-09 19:57:56 -0700918 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800919 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700920}
921
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800922Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -0700923 /*out*/
924 CameraParameters* parameters) {
925
926 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
927
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800928 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -0700929
930 if (parameters == NULL) {
931 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800932 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -0700933 }
934
Ruben Brunkcc776712015-02-17 20:18:47 -0800935 String8 id = String8::format("%d", cameraId);
936
937 // Check if we already have parameters
938 {
939 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -0700940 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -0800941 auto cameraState = getCameraState(id);
942 if (cameraState == nullptr) {
943 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800944 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
945 "Invalid camera ID: %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -0800946 }
947 CameraParameters p = cameraState->getShimParams();
948 if (!p.isEmpty()) {
949 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800950 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700951 }
952 }
953
Jayant Chowdhary12361932018-08-27 14:46:13 -0700954 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -0800955 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -0700956 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800957 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800958 // Error already logged by callee
959 return ret;
960 }
961
962 // Check for parameters again
963 {
964 // Scope for service lock
965 Mutex::Autolock lock(mServiceLock);
966 auto cameraState = getCameraState(id);
967 if (cameraState == nullptr) {
968 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800969 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
970 "Invalid camera ID: %s", id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -0700971 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800972 CameraParameters p = cameraState->getShimParams();
973 if (!p.isEmpty()) {
974 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800975 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700976 }
977 }
978
Ruben Brunkcc776712015-02-17 20:18:47 -0800979 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
980 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800981 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -0700982}
983
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800984// Can camera service trust the caller based on the calling UID?
985static bool isTrustedCallingUid(uid_t uid) {
986 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -0700987 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800988 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -0700989 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800990 return true;
991 default:
992 return false;
993 }
994}
995
Nicholas Sauera3620332019-04-03 14:05:17 -0700996static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
997 PermissionController pc;
998 uid = pc.getPackageUid(packageName, 0);
999 if (uid <= 0) {
1000 ALOGE("Unknown package: '%s'", String8(packageName).string());
1001 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
1002 return BAD_VALUE;
1003 }
1004
1005 if (userId < 0) {
1006 ALOGE("Invalid user: %d", userId);
1007 dprintf(err, "Invalid user: %d\n", userId);
1008 return BAD_VALUE;
1009 }
1010
1011 uid = multiuser_get_uid(userId, uid);
1012 return NO_ERROR;
1013}
1014
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001015Status CameraService::validateConnectLocked(const String8& cameraId,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001016 const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
1017 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001018
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001019#ifdef __BRILLO__
1020 UNUSED(clientName8);
1021 UNUSED(clientUid);
1022 UNUSED(clientPid);
1023 UNUSED(originalClientPid);
1024#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001025 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1026 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001027 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001028 return allowed;
1029 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001030#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001031
Jayant Chowdhary12361932018-08-27 14:46:13 -07001032 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001033
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001034 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001035 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1036 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001037 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1038 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001039 }
1040
Ruben Brunkcc776712015-02-17 20:18:47 -08001041 if (getCameraState(cameraId) == nullptr) {
1042 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1043 cameraId.string());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001044 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1045 "No camera device with ID \"%s\" available", cameraId.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001046 }
1047
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001048 status_t err = checkIfDeviceIsUsable(cameraId);
1049 if (err != NO_ERROR) {
1050 switch(err) {
1051 case -ENODEV:
1052 case -EBUSY:
1053 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1054 "No camera device with ID \"%s\" currently available", cameraId.string());
1055 default:
1056 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1057 "Unknown error connecting to ID \"%s\"", cameraId.string());
1058 }
1059 }
1060 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001061}
1062
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001063Status CameraService::validateClientPermissionsLocked(const String8& cameraId,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001064 const String8& clientName8, int& clientUid, int& clientPid,
1065 /*out*/int& originalClientPid) const {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001066 int callingPid = CameraThreadState::getCallingPid();
1067 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001068
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001069 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001070 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001071 clientUid = callingUid;
1072 } else if (!isTrustedCallingUid(callingUid)) {
1073 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1074 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001075 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1076 "Untrusted caller (calling PID %d, UID %d) trying to "
1077 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1078 callingPid, callingUid, cameraId.string(),
1079 clientName8.string(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001080 }
1081
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001082 // Check if we can trust clientPid
1083 if (clientPid == USE_CALLING_PID) {
1084 clientPid = callingPid;
1085 } else if (!isTrustedCallingUid(callingUid)) {
1086 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1087 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001088 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1089 "Untrusted caller (calling PID %d, UID %d) trying to "
1090 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1091 callingPid, callingUid, cameraId.string(),
1092 clientName8.string(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001093 }
1094
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001095 if (shouldRejectSystemCameraConnection(cameraId)) {
1096 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1097 cameraId.c_str());
1098 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
1099 "available", cameraId.string());
1100 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001101 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1102 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1103 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
1104 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
1105 "found while trying to query device kind", cameraId.string());
1106
1107 }
1108
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001109 // If it's not calling from cameraserver, check the permission if the
1110 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1111 // android.permission.SYSTEM_CAMERA for system only camera devices).
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001112 if (callingPid != getpid() &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001113 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001114 !checkPermission(sCameraPermission, clientPid, clientUid)) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001115 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001116 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1117 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
1118 clientName8.string(), clientUid, clientPid, cameraId.string());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001119 }
1120
Svet Ganova453d0d2018-01-11 15:37:58 -08001121 // Make sure the UID is in an active state to use the camera
Svet Ganov7b4ab782018-03-25 12:48:10 -07001122 if (!mUidPolicy->isUidActive(callingUid, String16(clientName8))) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001123 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001124 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1125 clientPid, clientUid);
1126 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001127 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1128 "calling UID %d proc state %" PRId32 ")",
1129 clientName8.string(), clientUid, clientPid, cameraId.string(),
1130 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001131 }
1132
Michael Grooverd1d435a2018-12-18 17:39:42 -08001133 // If sensor privacy is enabled then prevent access to the camera
1134 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1135 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1136 return STATUS_ERROR_FMT(ERROR_DISABLED,
1137 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
1138 "is enabled", clientName8.string(), clientUid, clientPid, cameraId.string());
1139 }
1140
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001141 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1142 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001143 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001144 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001145
Ruben Brunk6267b532015-04-30 17:44:07 -07001146 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001147
Ruben Brunka8ca9152015-04-07 14:23:40 -07001148 // Only allow clients who are being used by the current foreground device user, unless calling
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001149 // from our own process OR the caller is using the cameraserver's HIDL interface.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001150 if (getCurrentServingCall() != BinderCallType::HWBINDER && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001151 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001152 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1153 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
1154 toString(mAllowedUsers).string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001155 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1156 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
1157 clientUserId, cameraId.string());
Ruben Brunk36597b22015-03-20 22:15:57 -07001158 }
1159
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001160 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001161}
1162
1163status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
1164 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001165 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001166 if (cameraState == nullptr) {
1167 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1168 cameraId.string());
1169 return -ENODEV;
1170 }
1171
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001172 StatusInternal currentStatus = cameraState->getStatus();
1173 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001174 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
1175 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001176 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001177 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001178 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
1179 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001180 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001181 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001182
Ruben Brunkcc776712015-02-17 20:18:47 -08001183 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001184}
1185
Ruben Brunkcc776712015-02-17 20:18:47 -08001186void CameraService::finishConnectLocked(const sp<BasicClient>& client,
1187 const CameraService::DescriptorPtr& desc) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001188
Ruben Brunkcc776712015-02-17 20:18:47 -08001189 // Make a descriptor for the incoming client
1190 auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
1191 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1192
1193 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
1194 String8(client->getPackageName()));
1195
1196 if (evicted.size() > 0) {
1197 // This should never happen - clients should already have been removed in disconnect
1198 for (auto& i : evicted) {
1199 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
1200 __FUNCTION__, i->getKey().string());
1201 }
1202
1203 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1204 __FUNCTION__);
1205 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001206
1207 // And register a death notification for the client callback. Do
1208 // this last to avoid Binder policy where a nested Binder
1209 // transaction might be pre-empted to service the client death
1210 // notification if the client process dies before linkToDeath is
1211 // invoked.
1212 sp<IBinder> remoteCallback = client->getRemote();
1213 if (remoteCallback != nullptr) {
1214 remoteCallback->linkToDeath(this);
1215 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001216}
1217
1218status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
1219 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
1220 /*out*/
1221 sp<BasicClient>* client,
1222 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001223 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001224 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001225 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001226 DescriptorPtr clientDescriptor;
1227 {
1228 if (effectiveApiLevel == API_1) {
1229 // If we are using API1, any existing client for this camera ID with the same remote
1230 // should be returned rather than evicted to allow MediaRecorder to work properly.
1231
1232 auto current = mActiveClientManager.get(cameraId);
1233 if (current != nullptr) {
1234 auto clientSp = current->getValue();
1235 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001236 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
1237 ALOGW("CameraService connect called from same client, but with a different"
1238 " API level, evicting prior client...");
1239 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001240 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001241 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001242 *client = clientSp;
1243 return NO_ERROR;
1244 }
1245 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001246 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001247 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001248
Ruben Brunkcc776712015-02-17 20:18:47 -08001249 // Get current active client PIDs
1250 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1251 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001252
Emilian Peev8131a262017-02-01 12:33:43 +00001253 std::vector<int> priorityScores(ownerPids.size());
1254 std::vector<int> states(ownerPids.size());
Igor Murashkine6800ce2013-03-04 17:25:57 -08001255
Emilian Peev8131a262017-02-01 12:33:43 +00001256 // Get priority scores of all active PIDs
1257 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1258 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1259 /*out*/&priorityScores[0]);
1260 if (err != OK) {
1261 ALOGE("%s: Priority score query failed: %d",
1262 __FUNCTION__, err);
1263 return err;
1264 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001265
Ruben Brunkcc776712015-02-17 20:18:47 -08001266 // Update all active clients' priorities
Emilian Peev8131a262017-02-01 12:33:43 +00001267 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
Ruben Brunkcc776712015-02-17 20:18:47 -08001268 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
Emilian Peev8131a262017-02-01 12:33:43 +00001269 pidToPriorityMap.emplace(ownerPids[i],
Jayant Chowdharyc578a502019-05-08 10:57:54 -07001270 resource_policy::ClientPriority(priorityScores[i], states[i],
1271 /* isVendorClient won't get copied over*/ false));
Ruben Brunkcc776712015-02-17 20:18:47 -08001272 }
1273 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001274
Ruben Brunkcc776712015-02-17 20:18:47 -08001275 // Get state for the given cameraId
1276 auto state = getCameraState(cameraId);
1277 if (state == nullptr) {
1278 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1279 clientPid, cameraId.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001280 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001281 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001282 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001283
1284 // Make descriptor for incoming client
Shuzhen Wang2db86ff2018-04-25 01:11:17 +00001285 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001286 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1287 state->getConflicting(),
Emilian Peev8131a262017-02-01 12:33:43 +00001288 priorityScores[priorityScores.size() - 1],
1289 clientPid,
1290 states[states.size() - 1]);
Ruben Brunkcc776712015-02-17 20:18:47 -08001291
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001292 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1293
Ruben Brunkcc776712015-02-17 20:18:47 -08001294 // Find clients that would be evicted
1295 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1296
1297 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1298 // background, so we cannot do evictions
1299 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1300 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1301 " priority).", clientPid);
1302
1303 sp<BasicClient> clientSp = clientDescriptor->getValue();
1304 String8 curTime = getFormattedCurrentTime();
1305 auto incompatibleClients =
1306 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1307
1308 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Emilian Peev8131a262017-02-01 12:33:43 +00001309 "(PID %d, score %d state %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001310 cameraId.string(), packageName.string(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001311 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001312
1313 for (auto& i : incompatibleClients) {
1314 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001315 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
1316 i->getKey().string(),
1317 String8{i->getValue()->getPackageName()}.string(),
1318 i->getOwnerId(), i->getPriority().getScore(),
1319 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001320 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00001321 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(),
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001322 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001323 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001324 }
1325
1326 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001327 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001328 mEventLog.add(msg);
1329
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001330 auto current = mActiveClientManager.get(cameraId);
1331 if (current != nullptr) {
1332 return -EBUSY; // CAMERA_IN_USE
1333 } else {
1334 return -EUSERS; // MAX_CAMERAS_IN_USE
1335 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001336 }
1337
1338 for (auto& i : evicted) {
1339 sp<BasicClient> clientSp = i->getValue();
1340 if (clientSp.get() == nullptr) {
1341 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1342
1343 // TODO: Remove this
1344 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1345 __FUNCTION__);
1346 mActiveClientManager.remove(i);
1347 continue;
1348 }
1349
1350 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1351 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001352 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001353
Ruben Brunkcc776712015-02-17 20:18:47 -08001354 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001355 logEvent(String8::format("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00001356 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1357 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001358 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
Emilian Peev8131a262017-02-01 12:33:43 +00001359 i->getOwnerId(), i->getPriority().getScore(),
1360 i->getPriority().getState(), cameraId.string(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001361 packageName.string(), clientPid, clientPriority.getScore(),
1362 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08001363
1364 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001365 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001366 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001367 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001368 }
1369
Ruben Brunkcc776712015-02-17 20:18:47 -08001370 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1371 // other clients from connecting in mServiceLockWrapper if held
1372 mServiceLock.unlock();
1373
1374 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07001375 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001376
1377 // Destroy evicted clients
1378 for (auto& i : evictedClients) {
1379 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001380 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001381 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001382
Jayant Chowdhary12361932018-08-27 14:46:13 -07001383 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08001384
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001385 for (const auto& i : evictedClients) {
1386 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1387 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1388 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1389 if (ret == TIMED_OUT) {
1390 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1391 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1392 mActiveClientManager.toString().string());
1393 return -EBUSY;
1394 }
1395 if (ret != NO_ERROR) {
1396 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1397 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1398 ret, mActiveClientManager.toString().string());
1399 return ret;
1400 }
1401 }
1402
1403 evictedClients.clear();
1404
Ruben Brunkcc776712015-02-17 20:18:47 -08001405 // Once clients have been disconnected, relock
1406 mServiceLock.lock();
1407
1408 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1409 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1410 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001411 }
1412
Ruben Brunkcc776712015-02-17 20:18:47 -08001413 *partial = clientDescriptor;
1414 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001415}
1416
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001417Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001418 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001419 int api1CameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001420 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001421 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001422 int clientPid,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001423 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001424 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001425
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001426 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001427 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001428
1429 String8 id = cameraIdIntToStr(api1CameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001430 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001431 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001432 clientPackageName, {}, clientUid, clientPid, API_1,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001433 /*shimUpdateOnly*/ false, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001434
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001435 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001436 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001437 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001438 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001439 }
1440
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001441 *device = client;
1442 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001443}
1444
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001445bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
1446 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001447 // If the client is not a vendor client, don't add listener if
1448 // a) the camera is a publicly hidden secure camera OR
1449 // b) the camera is a system only camera and the client doesn't
1450 // have android.permission.SYSTEM_CAMERA permissions.
1451 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
1452 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1453 !hasPermissionsForSystemCamera(clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001454 return true;
1455 }
1456 return false;
1457}
1458
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001459bool CameraService::shouldRejectSystemCameraConnection(const String8& cameraId) const {
1460 // Rules for rejection:
1461 // 1) If cameraserver tries to access this camera device, accept the
1462 // connection.
1463 // 2) The camera device is a publicly hidden secure camera device AND some
1464 // component is trying to access it on a non-hwbinder thread (generally a non HAL client),
1465 // reject it.
1466 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
1467 // and the serving thread is a non hwbinder thread, the client must have
1468 // android.permission.SYSTEM_CAMERA permissions to connect.
1469
1470 int cPid = CameraThreadState::getCallingPid();
1471 int cUid = CameraThreadState::getCallingUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001472 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
1473 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001474 // This isn't a known camera ID, so it's not a system camera
1475 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
1476 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001477 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001478
1479 // (1) Cameraserver trying to connect, accept.
1480 if (CameraThreadState::getCallingPid() == getpid()) {
1481 return false;
1482 }
1483 // (2)
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001484 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001485 systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
1486 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
1487 return true;
1488 }
1489 // (3) Here we only check for permissions if it is a system only camera device. This is since
1490 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
1491 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
1492 // same behavior for system camera devices.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001493 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001494 systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1495 !hasPermissionsForSystemCamera(cPid, cUid)) {
1496 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
1497 cameraId.c_str());
1498 return true;
1499 }
1500
1501 return false;
1502}
1503
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001504Status CameraService::connectDevice(
1505 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001506 const String16& cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001507 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001508 const std::optional<String16>& clientFeatureId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001509 int clientUid,
1510 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001511 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001512
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001513 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001514 Status ret = Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001515 String8 id = String8(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001516 sp<CameraDeviceClient> client = nullptr;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001517 String16 clientPackageNameAdj = clientPackageName;
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001518
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001519 if (getCurrentServingCall() == BinderCallType::HWBINDER) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001520 std::string vendorClient =
1521 StringPrintf("vendor.client.pid<%d>", CameraThreadState::getCallingPid());
1522 clientPackageNameAdj = String16(vendorClient.c_str());
1523 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001524 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001525 /*api1CameraId*/-1, clientPackageNameAdj, clientFeatureId,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001526 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08001527
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001528 if(!ret.isOk()) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001529 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageNameAdj),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001530 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001531 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001532 }
1533
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001534 *device = client;
1535 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001536}
1537
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001538template<class CALLBACK, class CLIENT>
1539Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001540 int api1CameraId, const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001541 const std::optional<String16>& clientFeatureId, int clientUid, int clientPid,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001542 apiLevel effectiveApiLevel, bool shimUpdateOnly,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001543 /*out*/sp<CLIENT>& device) {
1544 binder::Status ret = binder::Status::ok();
1545
1546 String8 clientName8(clientPackageName);
1547
1548 int originalClientPid = 0;
1549
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001550 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001551 "Camera API version %d", clientPid, clientName8.string(), cameraId.string(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001552 static_cast<int>(effectiveApiLevel));
1553
Shuzhen Wang316781a2020-08-18 18:11:01 -07001554 nsecs_t openTimeNs = systemTime();
1555
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001556 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001557 int facing = -1;
1558 bool isNdk = (clientPackageName.size() == 0);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001559 {
1560 // Acquire mServiceLock and prevent other clients from connecting
1561 std::unique_ptr<AutoConditionLock> lock =
1562 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1563
1564 if (lock == nullptr) {
1565 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
1566 , clientPid);
1567 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1568 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
1569 cameraId.string(), clientName8.string(), clientPid);
1570 }
1571
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07001572 // Enforce client permissions and do basic validity checks
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001573 if(!(ret = validateConnectLocked(cameraId, clientName8,
1574 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
1575 return ret;
1576 }
1577
1578 // Check the shim parameters after acquiring lock, if they have already been updated and
1579 // we were doing a shim update, return immediately
1580 if (shimUpdateOnly) {
1581 auto cameraState = getCameraState(cameraId);
1582 if (cameraState != nullptr) {
1583 if (!cameraState->getShimParams().isEmpty()) return ret;
1584 }
1585 }
1586
1587 status_t err;
1588
1589 sp<BasicClient> clientTmp = nullptr;
1590 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
1591 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
1592 IInterface::asBinder(cameraCb), clientName8, /*out*/&clientTmp,
1593 /*out*/&partial)) != NO_ERROR) {
1594 switch (err) {
1595 case -ENODEV:
1596 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1597 "No camera device with ID \"%s\" currently available",
1598 cameraId.string());
1599 case -EBUSY:
1600 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1601 "Higher-priority client using camera, ID \"%s\" currently unavailable",
1602 cameraId.string());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001603 case -EUSERS:
1604 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1605 "Too many cameras already open, cannot open camera \"%s\"",
1606 cameraId.string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001607 default:
1608 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1609 "Unexpected error %s (%d) opening camera \"%s\"",
1610 strerror(-err), err, cameraId.string());
1611 }
1612 }
1613
1614 if (clientTmp.get() != nullptr) {
1615 // Handle special case for API1 MediaRecorder where the existing client is returned
1616 device = static_cast<CLIENT*>(clientTmp.get());
1617 return ret;
1618 }
1619
1620 // give flashlight a chance to close devices if necessary.
1621 mFlashlight->prepareDeviceOpen(cameraId);
1622
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001623 int deviceVersion = getDeviceVersion(cameraId, /*out*/&facing);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08001624 if (facing == -1) {
1625 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.string());
1626 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1627 "Unable to get camera device \"%s\" facing", cameraId.string());
1628 }
1629
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001630 sp<BasicClient> tmp = nullptr;
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001631 if(!(ret = makeClient(this, cameraCb, clientPackageName, clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001632 cameraId, api1CameraId, facing,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001633 clientPid, clientUid, getpid(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001634 deviceVersion, effectiveApiLevel,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001635 /*out*/&tmp)).isOk()) {
1636 return ret;
1637 }
1638 client = static_cast<CLIENT*>(tmp.get());
1639
1640 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
1641 __FUNCTION__);
1642
Emilian Peevbd8c5032018-02-14 23:05:40 +00001643 err = client->initialize(mCameraProviderManager, mMonitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001644 if (err != OK) {
1645 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001646 // Errors could be from the HAL module open call or from AppOpsManager
1647 switch(err) {
1648 case BAD_VALUE:
1649 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1650 "Illegal argument to HAL module for camera \"%s\"", cameraId.string());
1651 case -EBUSY:
1652 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1653 "Camera \"%s\" is already open", cameraId.string());
1654 case -EUSERS:
1655 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1656 "Too many cameras already open, cannot open camera \"%s\"",
1657 cameraId.string());
1658 case PERMISSION_DENIED:
1659 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1660 "No permission to open camera \"%s\"", cameraId.string());
1661 case -EACCES:
1662 return STATUS_ERROR_FMT(ERROR_DISABLED,
1663 "Camera \"%s\" disabled by policy", cameraId.string());
1664 case -ENODEV:
1665 default:
1666 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1667 "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
1668 strerror(-err), err);
1669 }
1670 }
1671
1672 // Update shim paremeters for legacy clients
1673 if (effectiveApiLevel == API_1) {
1674 // Assume we have always received a Client subclass for API1
1675 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
1676 String8 rawParams = shimClient->getParameters();
1677 CameraParameters params(rawParams);
1678
1679 auto cameraState = getCameraState(cameraId);
1680 if (cameraState != nullptr) {
1681 cameraState->setShimParams(params);
1682 } else {
1683 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
1684 __FUNCTION__, cameraId.string());
1685 }
1686 }
1687
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001688 // Set rotate-and-crop override behavior
1689 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
1690 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
1691 }
1692
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08001693 // Set camera muting behavior
1694 if (client->supportsCameraMute()) {
Evan Severson190ad252021-01-07 20:37:15 -08001695 client->setCameraMute(mOverrideCameraMuteMode ||
1696 isUserSensorPrivacyEnabledForUid(clientUid));
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08001697 }
1698
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001699 if (shimUpdateOnly) {
1700 // If only updating legacy shim parameters, immediately disconnect client
1701 mServiceLock.unlock();
1702 client->disconnect();
1703 mServiceLock.lock();
1704 } else {
1705 // Otherwise, add client to active clients list
1706 finishConnectLocked(client, partial);
1707 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001708
1709 client->setImageDumpMask(mImageDumpMask);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001710 } // lock is destroyed, allow further connect calls
1711
1712 // Important: release the mutex here so the client can call back into the service from its
1713 // destructor (can be at the end of the call)
1714 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001715
1716 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
1717 CameraServiceProxyWrapper::logOpen(cameraId, facing, clientPackageName,
1718 effectiveApiLevel, isNdk, openLatencyMs);
1719
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001720 return ret;
1721}
1722
Emilian Peevb2bc5a42019-11-20 16:02:14 -08001723status_t CameraService::addOfflineClient(String8 cameraId, sp<BasicClient> offlineClient) {
1724 if (offlineClient.get() == nullptr) {
1725 return BAD_VALUE;
1726 }
1727
1728 {
1729 // Acquire mServiceLock and prevent other clients from connecting
1730 std::unique_ptr<AutoConditionLock> lock =
1731 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1732
1733 if (lock == nullptr) {
1734 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
1735 , __FUNCTION__, offlineClient->getClientPid());
1736 return TIMED_OUT;
1737 }
1738
1739 auto onlineClientDesc = mActiveClientManager.get(cameraId);
1740 if (onlineClientDesc.get() == nullptr) {
1741 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
1742 cameraId.c_str());
1743 return BAD_VALUE;
1744 }
1745
1746 // Offline clients do not evict or conflict with other online devices. Resource sharing
1747 // conflicts are handled by the camera provider which will either succeed or fail before
1748 // reaching this method.
1749 const auto& onlinePriority = onlineClientDesc->getPriority();
1750 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
1751 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
1752 /*conflictingKeys*/ std::set<String8>(), onlinePriority.getScore(),
1753 onlineClientDesc->getOwnerId(), onlinePriority.getState());
1754
1755 // Allow only one offline device per camera
1756 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
1757 if (!incompatibleClients.empty()) {
1758 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
1759 return BAD_VALUE;
1760 }
1761
1762 auto err = offlineClient->initialize(mCameraProviderManager, mMonitorTags);
1763 if (err != OK) {
1764 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
1765 return err;
1766 }
1767
1768 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
1769 if (evicted.size() > 0) {
1770 for (auto& i : evicted) {
1771 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
1772 __FUNCTION__, i->getKey().string());
1773 }
1774
1775 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
1776 "properly", __FUNCTION__);
1777
1778 return BAD_VALUE;
1779 }
1780
1781 logConnectedOffline(offlineClientDesc->getKey(),
1782 static_cast<int>(offlineClientDesc->getOwnerId()),
1783 String8(offlineClient->getPackageName()));
1784
1785 sp<IBinder> remoteCallback = offlineClient->getRemote();
1786 if (remoteCallback != nullptr) {
1787 remoteCallback->linkToDeath(this);
1788 }
1789 } // lock is destroyed, allow further connect calls
1790
1791 return OK;
1792}
1793
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001794Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001795 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001796 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001797
1798 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07001799 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001800 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001801 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1802 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001803 }
1804
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001805 String8 id = String8(cameraId.string());
Jayant Chowdhary12361932018-08-27 14:46:13 -07001806 int uid = CameraThreadState::getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001807
1808 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08001809 auto state = getCameraState(id);
1810 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001811 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001812 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1813 "Camera ID \"%s\" is a not valid camera ID", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001814 }
1815
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001816 StatusInternal cameraStatus = state->getStatus();
1817 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001818 cameraStatus != StatusInternal::NOT_AVAILABLE) {
1819 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001820 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1821 "Camera ID \"%s\" is a not valid camera ID", id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001822 }
1823
1824 {
1825 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001826 TorchModeStatus status;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001827 status_t err = getTorchStatusLocked(id, &status);
1828 if (err != OK) {
1829 if (err == NAME_NOT_FOUND) {
1830 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1831 "Camera \"%s\" does not have a flash unit", id.string());
1832 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001833 ALOGE("%s: getting current torch status failed for camera %s",
1834 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001835 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1836 "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
1837 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001838 }
1839
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001840 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001841 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001842 ALOGE("%s: torch mode of camera %s is not available because "
1843 "camera is in use", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001844 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1845 "Torch for camera \"%s\" is not available due to an existing camera user",
1846 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001847 } else {
1848 ALOGE("%s: torch mode of camera %s is not available due to "
1849 "insufficient resources", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001850 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1851 "Torch for camera \"%s\" is not available due to insufficient resources",
1852 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001853 }
1854 }
1855 }
1856
Ruben Brunk99e69712015-05-26 17:25:07 -07001857 {
1858 // Update UID map - this is used in the torch status changed callbacks, so must be done
1859 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07001860 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -07001861 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
1862 mTorchUidMap[id].first = uid;
1863 mTorchUidMap[id].second = uid;
1864 } else {
1865 // Set the pending UID
1866 mTorchUidMap[id].first = uid;
1867 }
1868 }
1869
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001870 status_t err = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07001871
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001872 if (err != OK) {
1873 int32_t errorCode;
1874 String8 msg;
1875 switch (err) {
1876 case -ENOSYS:
1877 msg = String8::format("Camera \"%s\" has no flashlight",
1878 id.string());
1879 errorCode = ERROR_ILLEGAL_ARGUMENT;
1880 break;
1881 default:
1882 msg = String8::format(
1883 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
1884 id.string(), enabled, strerror(-err), err);
1885 errorCode = ERROR_INVALID_OPERATION;
1886 }
1887 ALOGE("%s: %s", __FUNCTION__, msg.string());
1888 return STATUS_ERROR(errorCode, msg.string());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001889 }
1890
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001891 {
1892 // update the link to client's death
1893 Mutex::Autolock al(mTorchClientMapMutex);
1894 ssize_t index = mTorchClientMap.indexOfKey(id);
1895 if (enabled) {
1896 if (index == NAME_NOT_FOUND) {
1897 mTorchClientMap.add(id, clientBinder);
1898 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07001899 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001900 mTorchClientMap.replaceValueAt(index, clientBinder);
1901 }
1902 clientBinder->linkToDeath(this);
1903 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07001904 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001905 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001906 }
1907
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07001908 int clientPid = CameraThreadState::getCallingPid();
1909 const char *id_cstr = id.c_str();
1910 const char *torchState = enabled ? "on" : "off";
1911 ALOGI("Torch for camera id %s turned %s for client PID %d", id_cstr, torchState, clientPid);
1912 logTorchEvent(id_cstr, torchState , clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001913 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001914}
1915
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001916Status CameraService::notifySystemEvent(int32_t eventId,
1917 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001918 const int pid = CameraThreadState::getCallingPid();
1919 const int selfPid = getpid();
1920
1921 // Permission checks
1922 if (pid != selfPid) {
1923 // Ensure we're being called by system_server, or similar process with
1924 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001925 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001926 const int uid = CameraThreadState::getCallingUid();
1927 ALOGE("Permission Denial: cannot send updates to camera service about system"
1928 " events from pid=%d, uid=%d", pid, uid);
1929 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09001930 "No permission to send updates to camera service about system events"
1931 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001932 }
1933 }
1934
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001935 ATRACE_CALL();
1936
Ruben Brunk36597b22015-03-20 22:15:57 -07001937 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001938 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001939 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07001940 // from a system server crash
1941 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08001942 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001943 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07001944 break;
1945 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001946 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07001947 default: {
1948 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
1949 eventId);
1950 break;
1951 }
1952 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001953 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07001954}
1955
Emilian Peev53722fa2019-02-22 17:47:20 -08001956void CameraService::notifyMonitoredUids() {
1957 Mutex::Autolock lock(mStatusListenerLock);
1958
1959 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001960 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Emilian Peev53722fa2019-02-22 17:47:20 -08001961 if (!ret.isOk()) {
1962 ALOGE("%s: Failed to trigger permission callback: %d", __FUNCTION__,
1963 ret.exceptionCode());
1964 }
1965 }
1966}
1967
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08001968Status CameraService::notifyDeviceStateChange(int64_t newState) {
1969 const int pid = CameraThreadState::getCallingPid();
1970 const int selfPid = getpid();
1971
1972 // Permission checks
1973 if (pid != selfPid) {
1974 // Ensure we're being called by system_server, or similar process with
1975 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001976 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08001977 const int uid = CameraThreadState::getCallingUid();
1978 ALOGE("Permission Denial: cannot send updates to camera service about device"
1979 " state changes from pid=%d, uid=%d", pid, uid);
1980 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1981 "No permission to send updates to camera service about device state"
1982 " changes from pid=%d, uid=%d", pid, uid);
1983 }
1984 }
1985
1986 ATRACE_CALL();
1987
1988 using hardware::camera::provider::V2_5::DeviceState;
1989 hardware::hidl_bitfield<DeviceState> newDeviceState{};
1990 if (newState & ICameraService::DEVICE_STATE_BACK_COVERED) {
1991 newDeviceState |= DeviceState::BACK_COVERED;
1992 }
1993 if (newState & ICameraService::DEVICE_STATE_FRONT_COVERED) {
1994 newDeviceState |= DeviceState::FRONT_COVERED;
1995 }
1996 if (newState & ICameraService::DEVICE_STATE_FOLDED) {
1997 newDeviceState |= DeviceState::FOLDED;
1998 }
1999 // Only map vendor bits directly
2000 uint64_t vendorBits = static_cast<uint64_t>(newState) & 0xFFFFFFFF00000000l;
2001 newDeviceState |= vendorBits;
2002
2003 ALOGV("%s: New device state 0x%" PRIx64, __FUNCTION__, newDeviceState);
2004 Mutex::Autolock l(mServiceLock);
2005 mCameraProviderManager->notifyDeviceStateChange(newDeviceState);
2006
2007 return Status::ok();
2008}
2009
Jayant Chowdharycad23c22020-03-10 15:04:59 -07002010 Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002011 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
2012 ATRACE_CALL();
2013 if (!concurrentCameraIds) {
2014 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
2015 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
2016 }
2017
2018 if (!mInitialized) {
2019 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2020 return STATUS_ERROR(ERROR_DISCONNECTED,
2021 "Camera subsystem is not available");
2022 }
2023 // First call into the provider and get the set of concurrent camera
2024 // combinations
2025 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07002026 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002027 for (auto &combination : concurrentCameraCombinations) {
2028 std::vector<std::string> validCombination;
2029 for (auto &cameraId : combination) {
2030 // if the camera state is not present, skip
2031 String8 cameraIdStr(cameraId.c_str());
2032 auto state = getCameraState(cameraIdStr);
2033 if (state == nullptr) {
2034 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
2035 continue;
2036 }
2037 StatusInternal status = state->getStatus();
2038 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
2039 continue;
2040 }
2041 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
2042 continue;
2043 }
2044 validCombination.push_back(cameraId);
2045 }
2046 if (validCombination.size() != 0) {
2047 concurrentCameraIds->push_back(std::move(validCombination));
2048 }
2049 }
2050 return Status::ok();
2051}
2052
2053Status CameraService::isConcurrentSessionConfigurationSupported(
2054 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
2055 /*out*/bool* isSupported) {
2056 if (!isSupported) {
2057 ALOGE("%s: isSupported is NULL", __FUNCTION__);
2058 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
2059 }
2060
2061 if (!mInitialized) {
2062 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2063 return STATUS_ERROR(ERROR_DISCONNECTED,
2064 "Camera subsystem is not available");
2065 }
2066
2067 // Check for camera permissions
2068 int callingPid = CameraThreadState::getCallingPid();
2069 int callingUid = CameraThreadState::getCallingUid();
2070 if ((callingPid != getpid()) && !checkPermission(sCameraPermission, callingPid, callingUid)) {
2071 ALOGE("%s: pid %d doesn't have camera permissions", __FUNCTION__, callingPid);
2072 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2073 "android.permission.CAMERA needed to call"
2074 "isConcurrentSessionConfigurationSupported");
2075 }
2076
2077 status_t res =
2078 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
2079 cameraIdsAndSessionConfigurations, isSupported);
2080 if (res != OK) {
2081 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
2082 "support %s (%d)", strerror(-res), res);
2083 }
2084 return Status::ok();
2085}
2086
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002087Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
2088 /*out*/
2089 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002090 return addListenerHelper(listener, cameraStatuses);
2091}
2092
2093Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
2094 /*out*/
2095 std::vector<hardware::CameraStatus> *cameraStatuses,
2096 bool isVendorListener) {
2097
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002098 ATRACE_CALL();
2099
Igor Murashkinbfc99152013-02-27 12:55:20 -08002100 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08002101
Ruben Brunk3450ba72015-06-16 11:00:37 -07002102 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002103 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002104 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002105 }
2106
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002107 auto clientUid = CameraThreadState::getCallingUid();
2108 auto clientPid = CameraThreadState::getCallingPid();
Shuzhen Wang695044d2020-03-06 09:02:23 -08002109 bool openCloseCallbackAllowed = checkPermission(sCameraOpenCloseListenerPermission,
2110 clientPid, clientUid);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002111
Igor Murashkinbfc99152013-02-27 12:55:20 -08002112 Mutex::Autolock lock(mServiceLock);
2113
Ruben Brunkcc776712015-02-17 20:18:47 -08002114 {
2115 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08002116 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002117 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002118 ALOGW("%s: Tried to add listener %p which was already subscribed",
2119 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002120 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08002121 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002122 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002123
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002124 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08002125 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
2126 openCloseCallbackAllowed);
Emilian Peev53722fa2019-02-22 17:47:20 -08002127 auto ret = serviceListener->initialize();
2128 if (ret != NO_ERROR) {
2129 String8 msg = String8::format("Failed to initialize service listener: %s (%d)",
2130 strerror(-ret), ret);
2131 ALOGE("%s: %s", __FUNCTION__, msg.string());
2132 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
2133 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002134 // The listener still needs to be added to the list of listeners, regardless of what
2135 // permissions the listener process has / whether it is a vendor listener. Since it might be
2136 // eligible to listen to other camera ids.
2137 mListenerList.emplace_back(serviceListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08002138 mUidPolicy->registerMonitorUid(clientUid);
Igor Murashkinbfc99152013-02-27 12:55:20 -08002139 }
2140
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002141 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07002142 {
Ruben Brunkcc776712015-02-17 20:18:47 -08002143 Mutex::Autolock lock(mCameraStatesLock);
2144 for (auto& i : mCameraStates) {
Shuzhen Wang43858162020-01-10 13:42:15 -08002145 cameraStatuses->emplace_back(i.first,
2146 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds());
Igor Murashkincba2c162013-03-20 15:56:31 -07002147 }
2148 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002149 // Remove the camera statuses that should be hidden from the client, we do
2150 // this after collecting the states in order to avoid holding
2151 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
2152 // the same time.
2153 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
2154 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
2155 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
2156 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
2157 ALOGE("%s: Invalid camera id %s, skipping status update",
2158 __FUNCTION__, s.cameraId.c_str());
2159 return true;
2160 }
2161 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
2162 clientUid);}), cameraStatuses->end());
2163
Igor Murashkincba2c162013-03-20 15:56:31 -07002164
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002165 /*
2166 * Immediately signal current torch status to this listener only
2167 * This may be a subset of all the devices, so don't include it in the response directly
2168 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002169 {
2170 Mutex::Autolock al(mTorchStatusMutex);
2171 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002172 String16 id = String16(mTorchStatusMap.keyAt(i).string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002173 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002174 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002175 }
2176
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002177 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08002178}
Ruben Brunkcc776712015-02-17 20:18:47 -08002179
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002180Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002181 ATRACE_CALL();
2182
Igor Murashkinbfc99152013-02-27 12:55:20 -08002183 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
2184
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002185 if (listener == 0) {
2186 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002187 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002188 }
2189
Igor Murashkinbfc99152013-02-27 12:55:20 -08002190 Mutex::Autolock lock(mServiceLock);
2191
Ruben Brunkcc776712015-02-17 20:18:47 -08002192 {
2193 Mutex::Autolock lock(mStatusListenerLock);
2194 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002195 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
2196 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid());
2197 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08002198 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002199 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002200 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002201 }
2202 }
2203
2204 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
2205 __FUNCTION__, listener.get());
2206
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002207 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08002208}
2209
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002210Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002211
2212 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002213 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
2214
2215 if (parameters == NULL) {
2216 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002217 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07002218 }
2219
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002220 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002221
2222 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002223 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07002224 // Error logged by caller
2225 return ret;
2226 }
2227
2228 String8 shimParamsString8 = shimParams.flatten();
2229 String16 shimParamsString16 = String16(shimParamsString8);
2230
2231 *parameters = shimParamsString16;
2232
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002233 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07002234}
2235
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002236Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
2237 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002238 ATRACE_CALL();
2239
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002240 const String8 id = String8(cameraId);
2241
2242 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002243
2244 switch (apiVersion) {
2245 case API_VERSION_1:
2246 case API_VERSION_2:
2247 break;
2248 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002249 String8 msg = String8::format("Unknown API version %d", apiVersion);
2250 ALOGE("%s: %s", __FUNCTION__, msg.string());
2251 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002252 }
2253
Emilian Peev28ad2ea2017-02-07 16:14:32 +00002254 int deviceVersion = getDeviceVersion(id);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002255 switch (deviceVersion) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002256 case CAMERA_DEVICE_API_VERSION_1_0:
2257 case CAMERA_DEVICE_API_VERSION_3_0:
2258 case CAMERA_DEVICE_API_VERSION_3_1:
2259 if (apiVersion == API_VERSION_2) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002260 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without shim",
2261 __FUNCTION__, id.string(), deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002262 *isSupported = false;
2263 } else { // if (apiVersion == API_VERSION_1) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002264 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always supported",
2265 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002266 *isSupported = true;
2267 }
2268 break;
2269 case CAMERA_DEVICE_API_VERSION_3_2:
2270 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -07002271 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002272 case CAMERA_DEVICE_API_VERSION_3_5:
Yin-Chia Yeh56d98ba2020-01-16 16:57:14 -08002273 case CAMERA_DEVICE_API_VERSION_3_6:
Shuzhen Wang83bff122020-11-20 15:51:39 -08002274 case CAMERA_DEVICE_API_VERSION_3_7:
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002275 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
2276 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002277 *isSupported = true;
2278 break;
2279 case -1: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002280 String8 msg = String8::format("Unknown camera ID %s", id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002281 ALOGE("%s: %s", __FUNCTION__, msg.string());
2282 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002283 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002284 default: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002285 String8 msg = String8::format("Unknown device version %x for device %s",
2286 deviceVersion, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002287 ALOGE("%s: %s", __FUNCTION__, msg.string());
2288 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
2289 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07002290 }
2291
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002292 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002293}
2294
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002295Status CameraService::isHiddenPhysicalCamera(const String16& cameraId,
2296 /*out*/ bool *isSupported) {
2297 ATRACE_CALL();
2298
2299 const String8 id = String8(cameraId);
2300
2301 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
2302 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(id.string());
2303
2304 return Status::ok();
2305}
2306
Ruben Brunkcc776712015-02-17 20:18:47 -08002307void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002308 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002309 for (auto& i : mActiveClientManager.getAll()) {
2310 auto clientSp = i->getValue();
2311 if (clientSp.get() == client) {
2312 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08002313 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07002314 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002315 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08002316}
2317
Ruben Brunkcc776712015-02-17 20:18:47 -08002318bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002319 bool ret = false;
2320 {
2321 // Acquire mServiceLock and prevent other clients from connecting
2322 std::unique_ptr<AutoConditionLock> lock =
2323 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08002324
Igor Murashkin634a5152013-02-20 17:15:11 -08002325
Ruben Brunkcc776712015-02-17 20:18:47 -08002326 std::vector<sp<BasicClient>> evicted;
2327 for (auto& i : mActiveClientManager.getAll()) {
2328 auto clientSp = i->getValue();
2329 if (clientSp.get() == nullptr) {
2330 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2331 mActiveClientManager.remove(i);
2332 continue;
2333 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08002334 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002335 mActiveClientManager.remove(i);
2336 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08002337
Ruben Brunkcc776712015-02-17 20:18:47 -08002338 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002339 clientSp->notifyError(
2340 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002341 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08002342 }
2343 }
2344
Ruben Brunkcc776712015-02-17 20:18:47 -08002345 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2346 // other clients from connecting in mServiceLockWrapper if held
2347 mServiceLock.unlock();
2348
Ruben Brunk36597b22015-03-20 22:15:57 -07002349 // Do not clear caller identity, remote caller should be client proccess
2350
Ruben Brunkcc776712015-02-17 20:18:47 -08002351 for (auto& i : evicted) {
2352 if (i.get() != nullptr) {
2353 i->disconnect();
2354 ret = true;
2355 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002356 }
2357
Ruben Brunkcc776712015-02-17 20:18:47 -08002358 // Reacquire mServiceLock
2359 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08002360
Ruben Brunkcc776712015-02-17 20:18:47 -08002361 } // lock is destroyed, allow further connect calls
2362
2363 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07002364}
2365
Ruben Brunkcc776712015-02-17 20:18:47 -08002366std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
2367 const String8& cameraId) const {
2368 std::shared_ptr<CameraState> state;
2369 {
2370 Mutex::Autolock lock(mCameraStatesLock);
2371 auto iter = mCameraStates.find(cameraId);
2372 if (iter != mCameraStates.end()) {
2373 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002374 }
2375 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002376 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002377}
2378
Ruben Brunkcc776712015-02-17 20:18:47 -08002379sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
2380 // Remove from active clients list
2381 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
2382 if (clientDescriptorPtr == nullptr) {
2383 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
2384 cameraId.string());
2385 return sp<BasicClient>{nullptr};
2386 }
2387
2388 return clientDescriptorPtr->getValue();
Keun young Parkd8973a72012-03-28 14:13:09 -07002389}
2390
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002391void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07002392 // Acquire mServiceLock and prevent other clients from connecting
2393 std::unique_ptr<AutoConditionLock> lock =
2394 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
2395
Ruben Brunk6267b532015-04-30 17:44:07 -07002396 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002397 for (size_t i = 0; i < newUserIds.size(); i++) {
2398 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07002399 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002400 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07002401 return;
2402 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002403 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07002404 }
2405
Ruben Brunka8ca9152015-04-07 14:23:40 -07002406
Ruben Brunk6267b532015-04-30 17:44:07 -07002407 if (newAllowedUsers == mAllowedUsers) {
2408 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
2409 return;
2410 }
2411
2412 logUserSwitch(mAllowedUsers, newAllowedUsers);
2413
2414 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07002415
2416 // Current user has switched, evict all current clients.
2417 std::vector<sp<BasicClient>> evicted;
2418 for (auto& i : mActiveClientManager.getAll()) {
2419 auto clientSp = i->getValue();
2420
2421 if (clientSp.get() == nullptr) {
2422 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2423 continue;
2424 }
2425
Ruben Brunk6267b532015-04-30 17:44:07 -07002426 // Don't evict clients that are still allowed.
2427 uid_t clientUid = clientSp->getClientUid();
2428 userid_t clientUserId = multiuser_get_user_id(clientUid);
2429 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
2430 continue;
2431 }
2432
Ruben Brunk36597b22015-03-20 22:15:57 -07002433 evicted.push_back(clientSp);
2434
2435 String8 curTime = getFormattedCurrentTime();
2436
2437 ALOGE("Evicting conflicting client for camera ID %s due to user change",
2438 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07002439
Ruben Brunk36597b22015-03-20 22:15:57 -07002440 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002441 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00002442 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
2443 " to user switch.", i->getKey().string(),
2444 String8{clientSp->getPackageName()}.string(),
2445 i->getOwnerId(), i->getPriority().getScore(),
2446 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07002447
2448 }
2449
2450 // Do not hold mServiceLock while disconnecting clients, but retain the condition
2451 // blocking other clients from connecting in mServiceLockWrapper if held.
2452 mServiceLock.unlock();
2453
2454 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07002455 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07002456
2457 for (auto& i : evicted) {
2458 i->disconnect();
2459 }
2460
Jayant Chowdhary12361932018-08-27 14:46:13 -07002461 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07002462
2463 // Reacquire mServiceLock
2464 mServiceLock.lock();
2465}
Ruben Brunkcc776712015-02-17 20:18:47 -08002466
Ruben Brunka8ca9152015-04-07 14:23:40 -07002467void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002468 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07002469 Mutex::Autolock l(mLogLock);
2470 mEventLog.add(String8::format("%s : %s", curTime.string(), event));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002471}
2472
Ruben Brunka8ca9152015-04-07 14:23:40 -07002473void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002474 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002475 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002476 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002477 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002478}
2479
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002480void CameraService::logDisconnectedOffline(const char* cameraId, int clientPid,
2481 const char* clientPackage) {
2482 // Log the clients evicted
2483 logEvent(String8::format("DISCONNECT offline device %s client for package %s (PID %d)",
2484 cameraId, clientPackage, clientPid));
2485}
2486
Ruben Brunka8ca9152015-04-07 14:23:40 -07002487void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002488 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002489 // Log the clients evicted
2490 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002491 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002492}
2493
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002494void CameraService::logConnectedOffline(const char* cameraId, int clientPid,
2495 const char* clientPackage) {
2496 // Log the clients evicted
2497 logEvent(String8::format("CONNECT offline device %s client for package %s (PID %d)", cameraId,
2498 clientPackage, clientPid));
2499}
2500
Ruben Brunka8ca9152015-04-07 14:23:40 -07002501void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002502 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002503 // Log the client rejected
2504 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002505 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002506}
2507
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002508void CameraService::logTorchEvent(const char* cameraId, const char *torchState, int clientPid) {
2509 // Log torch event
2510 logEvent(String8::format("Torch for camera id %s turned %s for client PID %d", cameraId,
2511 torchState, clientPid));
2512}
2513
Ruben Brunk6267b532015-04-30 17:44:07 -07002514void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
2515 const std::set<userid_t>& newUserIds) {
2516 String8 newUsers = toString(newUserIds);
2517 String8 oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002518 if (oldUsers.size() == 0) {
2519 oldUsers = "<None>";
2520 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07002521 // Log the new and old users
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002522 logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
Ruben Brunk6267b532015-04-30 17:44:07 -07002523 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002524}
2525
2526void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
2527 // Log the device removal
2528 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
2529}
2530
2531void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
2532 // Log the device removal
2533 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
2534}
2535
2536void CameraService::logClientDied(int clientPid, const char* reason) {
2537 // Log the device removal
2538 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07002539}
2540
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002541void CameraService::logServiceError(const char* msg, int errorCode) {
2542 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002543 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002544}
2545
Ruben Brunk36597b22015-03-20 22:15:57 -07002546status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
2547 uint32_t flags) {
2548
Mathias Agopian65ab4712010-07-14 17:59:35 -07002549 // Permission checks
2550 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002551 case SHELL_COMMAND_TRANSACTION: {
2552 int in = data.readFileDescriptor();
2553 int out = data.readFileDescriptor();
2554 int err = data.readFileDescriptor();
2555 int argc = data.readInt32();
2556 Vector<String16> args;
2557 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
2558 args.add(data.readString16());
2559 }
2560 sp<IBinder> unusedCallback;
2561 sp<IResultReceiver> resultReceiver;
2562 status_t status;
2563 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
2564 return status;
2565 }
2566 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
2567 return status;
2568 }
2569 status = shellCommand(in, out, err, args);
2570 if (resultReceiver != nullptr) {
2571 resultReceiver->send(status);
2572 }
2573 return NO_ERROR;
2574 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002575 }
2576
2577 return BnCameraService::onTransact(code, data, reply, flags);
2578}
2579
Mathias Agopian65ab4712010-07-14 17:59:35 -07002580// We share the media players for shutter and recording sound for all clients.
2581// A reference count is kept to determine when we will actually release the
2582// media players.
2583
Jaekyun Seokef498052018-03-23 13:09:44 +09002584sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
2585 sp<MediaPlayer> mp = new MediaPlayer();
2586 status_t error;
2587 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08002588 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09002589 error = mp->prepare();
2590 }
2591 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00002592 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09002593 mp->disconnect();
2594 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002595 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002596 }
2597 return mp;
2598}
2599
username5755fea2018-12-27 09:48:08 +08002600void CameraService::increaseSoundRef() {
2601 Mutex::Autolock lock(mSoundLock);
2602 mSoundRef++;
2603}
2604
2605void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002606 ATRACE_CALL();
2607
username5755fea2018-12-27 09:48:08 +08002608 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
2609 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
2610 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
2611 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
2612 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
2613 }
2614 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
2615 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
2616 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
2617 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002618 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08002619 }
2620 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
2621 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
2622 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
2623 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
2624 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002625 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002626}
2627
username5755fea2018-12-27 09:48:08 +08002628void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002629 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002630 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002631 if (--mSoundRef) return;
2632
2633 for (int i = 0; i < NUM_SOUNDS; i++) {
2634 if (mSoundPlayer[i] != 0) {
2635 mSoundPlayer[i]->disconnect();
2636 mSoundPlayer[i].clear();
2637 }
2638 }
2639}
2640
2641void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002642 ATRACE_CALL();
2643
Mathias Agopian65ab4712010-07-14 17:59:35 -07002644 LOG1("playSound(%d)", kind);
2645 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002646 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002647 sp<MediaPlayer> player = mSoundPlayer[kind];
2648 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08002649 player->seekTo(0);
2650 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002651 }
2652}
2653
2654// ----------------------------------------------------------------------------
2655
2656CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07002657 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002658 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09002659 const std::optional<String16>& clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002660 const String8& cameraIdStr,
2661 int api1CameraId, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002662 int clientPid, uid_t clientUid,
2663 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002664 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08002665 IInterface::asBinder(cameraClient),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002666 clientPackageName, clientFeatureId,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002667 cameraIdStr, cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002668 clientPid, clientUid,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002669 servicePid),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002670 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08002671{
Jayant Chowdhary12361932018-08-27 14:46:13 -07002672 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002673 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002674
Igor Murashkin44cfcf02013-03-01 16:22:28 -08002675 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002676
username5755fea2018-12-27 09:48:08 +08002677 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002678
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002679 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002680}
2681
Mathias Agopian65ab4712010-07-14 17:59:35 -07002682// tear down the client
2683CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002684 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08002685 mDestructionStarted = true;
2686
username5755fea2018-12-27 09:48:08 +08002687 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002688 // unconditionally disconnect. function is idempotent
2689 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002690}
2691
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002692sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
2693
Igor Murashkin634a5152013-02-20 17:15:11 -08002694CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002695 const sp<IBinder>& remoteCallback,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09002696 const String16& clientPackageName, const std::optional<String16>& clientFeatureId,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002697 const String8& cameraIdStr, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002698 int clientPid, uid_t clientUid,
2699 int servicePid):
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002700 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing),
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09002701 mClientPackageName(clientPackageName), mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002702 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002703 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07002704 mDisconnected(false), mUidIsTrusted(false),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002705 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002706 mRemoteBinder(remoteCallback)
Igor Murashkin634a5152013-02-20 17:15:11 -08002707{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002708 if (sCameraService == nullptr) {
2709 sCameraService = cameraService;
2710 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002711 mOpsActive = false;
Igor Murashkin634a5152013-02-20 17:15:11 -08002712 mDestructionStarted = false;
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08002713
2714 // In some cases the calling code has no access to the package it runs under.
2715 // For example, NDK camera API.
2716 // In this case we will get the packages for the calling UID and pick the first one
2717 // for attributing the app op. This will work correctly for runtime permissions
2718 // as for legacy apps we will toggle the app op for all packages in the UID.
2719 // The caveat is that the operation may be attributed to the wrong package and
2720 // stats based on app ops may be slightly off.
2721 if (mClientPackageName.size() <= 0) {
2722 sp<IServiceManager> sm = defaultServiceManager();
2723 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
2724 if (binder == 0) {
2725 ALOGE("Cannot get permission service");
2726 // Leave mClientPackageName unchanged (empty) and the further interaction
2727 // with camera will fail in BasicClient::startCameraOps
2728 return;
2729 }
2730
2731 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
2732 Vector<String16> packages;
2733
2734 permCtrl->getPackagesForUid(mClientUid, packages);
2735
2736 if (packages.isEmpty()) {
2737 ALOGE("No packages for calling UID");
2738 // Leave mClientPackageName unchanged (empty) and the further interaction
2739 // with camera will fail in BasicClient::startCameraOps
2740 return;
2741 }
2742 mClientPackageName = packages[0];
2743 }
Steven Moreland89a2c5c2020-01-31 15:02:25 -08002744 if (getCurrentServingCall() != BinderCallType::HWBINDER) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002745 mAppOpsManager = std::make_unique<AppOpsManager>();
2746 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07002747
2748 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08002749}
2750
2751CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002752 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08002753 mDestructionStarted = true;
2754}
2755
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002756binder::Status CameraService::BasicClient::disconnect() {
2757 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002758 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002759 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07002760 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07002761 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002762
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002763 sCameraService->removeByClient(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002764 sCameraService->logDisconnected(mCameraIdStr, mClientPid, String8(mClientPackageName));
Peter Kalauskasa29c1352018-10-10 12:05:42 -07002765 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
2766 mCameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002767
2768 sp<IBinder> remote = getRemote();
2769 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002770 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08002771 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002772
2773 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07002774 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002775 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
2776 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
2777 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002778
Igor Murashkincba2c162013-03-20 15:56:31 -07002779 // client shouldn't be able to call into us anymore
2780 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002781
2782 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08002783}
2784
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002785status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
2786 // No dumping of clients directly over Binder,
2787 // must go through CameraService::dump
2788 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07002789 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002790 return OK;
2791}
2792
Ruben Brunkcc776712015-02-17 20:18:47 -08002793String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002794 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08002795}
2796
2797
2798int CameraService::BasicClient::getClientPid() const {
2799 return mClientPid;
2800}
2801
Ruben Brunk6267b532015-04-30 17:44:07 -07002802uid_t CameraService::BasicClient::getClientUid() const {
2803 return mClientUid;
2804}
2805
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002806bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
2807 // Defaults to API2.
2808 return level == API_2;
2809}
2810
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002811status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002812 {
2813 Mutex::Autolock l(mAudioRestrictionLock);
2814 mAudioRestriction = mode;
2815 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002816 sCameraService->updateAudioRestriction();
2817 return OK;
2818}
2819
2820int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002821 return sCameraService->updateAudioRestriction();
2822}
2823
2824int32_t CameraService::BasicClient::getAudioRestriction() const {
2825 Mutex::Autolock l(mAudioRestrictionLock);
2826 return mAudioRestriction;
2827}
2828
2829bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
2830 switch (mode) {
2831 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
2832 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
2833 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
2834 return true;
2835 default:
2836 return false;
2837 }
2838}
2839
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002840status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002841 ATRACE_CALL();
2842
Igor Murashkine6800ce2013-03-04 17:25:57 -08002843 {
2844 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002845 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08002846 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002847 if (mAppOpsManager != nullptr) {
2848 // Notify app ops that the camera is not available
2849 mOpsCallback = new OpsCallback(this);
2850 int32_t res;
2851 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
2852 mClientPackageName, mOpsCallback);
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002853 res = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
2854 mClientPackageName, /*startIfModeDefault*/ false, mClientFeatureId,
2855 String16("start camera ") + String16(mCameraIdStr));
Igor Murashkine6800ce2013-03-04 17:25:57 -08002856
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002857 if (res == AppOpsManager::MODE_ERRORED) {
2858 ALOGI("Camera %s: Access for \"%s\" has been revoked",
2859 mCameraIdStr.string(), String8(mClientPackageName).string());
2860 return PERMISSION_DENIED;
2861 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002862
Shuzhen Wang2c656792020-04-13 17:36:49 -07002863 // If the calling Uid is trusted (a native service), the AppOpsManager could
2864 // return MODE_IGNORED. Do not treat such case as error.
2865 if (!mUidIsTrusted && res == AppOpsManager::MODE_IGNORED) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002866 ALOGI("Camera %s: Access for \"%s\" has been restricted",
2867 mCameraIdStr.string(), String8(mClientPackageName).string());
2868 // Return the same error as for device policy manager rejection
2869 return -EACCES;
2870 }
Svetoslav28e8ef72015-05-11 19:21:31 -07002871 }
2872
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002873 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002874
2875 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002876 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002877
Emilian Peev53722fa2019-02-22 17:47:20 -08002878 sCameraService->mUidPolicy->registerMonitorUid(mClientUid);
2879
Shuzhen Wang695044d2020-03-06 09:02:23 -08002880 // Notify listeners of camera open/close status
2881 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
2882
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002883 return OK;
2884}
2885
2886status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002887 ATRACE_CALL();
2888
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002889 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002890 if (mOpsActive) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002891 // Notify app ops that the camera is available again
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002892 if (mAppOpsManager != nullptr) {
2893 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002894 mClientPackageName, mClientFeatureId);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002895 mOpsActive = false;
2896 }
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002897 // This function is called when a client disconnects. This should
2898 // release the camera, but actually only if it was in a proper
2899 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002900 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002901 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002902
Ruben Brunkcc776712015-02-17 20:18:47 -08002903 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002904 sCameraService->updateStatus(StatusInternal::PRESENT,
2905 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002906 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002907 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002908 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
2909 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002910 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002911 mOpsCallback.clear();
2912
Emilian Peev53722fa2019-02-22 17:47:20 -08002913 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid);
2914
Shuzhen Wang695044d2020-03-06 09:02:23 -08002915 // Notify listeners of camera open/close status
2916 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
2917
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002918 return OK;
2919}
2920
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002921void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002922 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002923 if (mAppOpsManager == nullptr) {
2924 return;
2925 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002926 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002927 if (op != AppOpsManager::OP_CAMERA) {
2928 ALOGW("Unexpected app ops notification received: %d", op);
2929 return;
2930 }
2931
2932 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002933 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002934 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002935 ALOGV("checkOp returns: %d, %s ", res,
2936 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
2937 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
2938 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
2939 "UNKNOWN");
2940
Shuzhen Wang64900852021-02-05 09:03:29 -08002941 if (res == AppOpsManager::MODE_ERRORED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002942 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002943 String8(mClientPackageName).string());
Svet Ganova453d0d2018-01-11 15:37:58 -08002944 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08002945 } else if (res == AppOpsManager::MODE_IGNORED) {
2946 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
2947 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d",
2948 mCameraIdStr.string(), String8(mClientPackageName).string(),
2949 mUidIsTrusted, isUidActive);
2950 // If the calling Uid is trusted (a native service), or the client Uid is active (WAR for
2951 // b/175320666), the AppOpsManager could return MODE_IGNORED. Do not treat such cases as
2952 // error.
2953 if (!mUidIsTrusted && !isUidActive) {
2954 block();
2955 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002956 }
2957}
2958
Svet Ganova453d0d2018-01-11 15:37:58 -08002959void CameraService::BasicClient::block() {
2960 ATRACE_CALL();
2961
2962 // Reset the client PID to allow server-initiated disconnect,
2963 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07002964 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08002965 CaptureResultExtras resultExtras; // a dummy result (invalid)
2966 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
2967 disconnect();
2968}
2969
Mathias Agopian65ab4712010-07-14 17:59:35 -07002970// ----------------------------------------------------------------------------
2971
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002972void CameraService::Client::notifyError(int32_t errorCode,
Jianing Weicb0652e2014-03-12 18:29:36 -07002973 const CaptureResultExtras& resultExtras) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002974 (void) resultExtras;
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07002975 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07002976 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
2977 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
2978 api1ErrorCode = CAMERA_ERROR_DISABLED;
2979 }
2980 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07002981 } else {
2982 ALOGE("mRemoteCallback is NULL!!");
2983 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002984}
2985
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002986// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002987binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002988 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002989 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08002990}
2991
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002992bool CameraService::Client::canCastToApiClient(apiLevel level) const {
2993 return level == API_1;
2994}
2995
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002996CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
2997 mClient(client) {
2998}
2999
3000void CameraService::Client::OpsCallback::opChanged(int32_t op,
3001 const String16& packageName) {
3002 sp<BasicClient> client = mClient.promote();
3003 if (client != NULL) {
3004 client->opChanged(op, packageName);
3005 }
3006}
3007
Mathias Agopian65ab4712010-07-14 17:59:35 -07003008// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08003009// UidPolicy
3010// ----------------------------------------------------------------------------
3011
3012void CameraService::UidPolicy::registerSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003013 Mutex::Autolock _l(mUidLock);
3014
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003015 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07003016 status_t res = mAm.linkToDeath(this);
3017 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08003018 | ActivityManager::UID_OBSERVER_IDLE
Emilian Peev53722fa2019-02-22 17:47:20 -08003019 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganova453d0d2018-01-11 15:37:58 -08003020 ActivityManager::PROCESS_STATE_UNKNOWN,
3021 String16("cameraserver"));
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003022 if (res == OK) {
3023 mRegistered = true;
3024 ALOGV("UidPolicy: Registered with ActivityManager");
3025 }
Svet Ganova453d0d2018-01-11 15:37:58 -08003026}
3027
3028void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003029 Mutex::Autolock _l(mUidLock);
3030
Steven Moreland2f348142019-07-02 15:59:07 -07003031 mAm.unregisterUidObserver(this);
3032 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003033 mRegistered = false;
3034 mActiveUids.clear();
3035 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08003036}
3037
3038void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
3039 onUidIdle(uid, disabled);
3040}
3041
3042void CameraService::UidPolicy::onUidActive(uid_t uid) {
3043 Mutex::Autolock _l(mUidLock);
3044 mActiveUids.insert(uid);
3045}
3046
3047void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
3048 bool deleted = false;
3049 {
3050 Mutex::Autolock _l(mUidLock);
3051 if (mActiveUids.erase(uid) > 0) {
3052 deleted = true;
3053 }
3054 }
3055 if (deleted) {
3056 sp<CameraService> service = mService.promote();
3057 if (service != nullptr) {
3058 service->blockClientsForUid(uid);
3059 }
3060 }
3061}
3062
Emilian Peev53722fa2019-02-22 17:47:20 -08003063void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07003064 int64_t procStateSeq __unused, int32_t capability __unused) {
Emilian Peev53722fa2019-02-22 17:47:20 -08003065 bool procStateChange = false;
3066 {
3067 Mutex::Autolock _l(mUidLock);
3068 if ((mMonitoredUids.find(uid) != mMonitoredUids.end()) &&
3069 (mMonitoredUids[uid].first != procState)) {
3070 mMonitoredUids[uid].first = procState;
3071 procStateChange = true;
3072 }
3073 }
3074
3075 if (procStateChange) {
3076 sp<CameraService> service = mService.promote();
3077 if (service != nullptr) {
3078 service->notifyMonitoredUids();
3079 }
3080 }
3081}
3082
3083void CameraService::UidPolicy::registerMonitorUid(uid_t uid) {
3084 Mutex::Autolock _l(mUidLock);
3085 auto it = mMonitoredUids.find(uid);
3086 if (it != mMonitoredUids.end()) {
3087 it->second.second++;
3088 } else {
3089 mMonitoredUids.emplace(
3090 std::pair<uid_t, std::pair<int32_t, size_t>> (uid,
3091 std::pair<int32_t, size_t> (ActivityManager::PROCESS_STATE_NONEXISTENT, 1)));
3092 }
3093}
3094
3095void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid) {
3096 Mutex::Autolock _l(mUidLock);
3097 auto it = mMonitoredUids.find(uid);
3098 if (it != mMonitoredUids.end()) {
3099 it->second.second--;
3100 if (it->second.second == 0) {
3101 mMonitoredUids.erase(it);
3102 }
3103 } else {
3104 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
3105 }
3106}
3107
Svet Ganov7b4ab782018-03-25 12:48:10 -07003108bool CameraService::UidPolicy::isUidActive(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003109 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003110 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003111}
3112
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003113static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
3114static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003115
Svet Ganov7b4ab782018-03-25 12:48:10 -07003116bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003117 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003118 // If activity manager is unreachable, assume everything is active
3119 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003120 return true;
3121 }
3122 auto it = mOverrideUids.find(uid);
3123 if (it != mOverrideUids.end()) {
3124 return it->second;
3125 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003126 bool active = mActiveUids.find(uid) != mActiveUids.end();
3127 if (!active) {
3128 // We want active UIDs to always access camera with their first attempt since
3129 // there is no guarantee the app is robustly written and would retry getting
3130 // the camera on failure. The inverse case is not a problem as we would take
3131 // camera away soon once we get the callback that the uid is no longer active.
3132 ActivityManager am;
3133 // Okay to access with a lock held as UID changes are dispatched without
3134 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07003135 int64_t startTimeMillis = 0;
3136 do {
3137 // TODO: Fix this b/109950150!
3138 // Okay this is a hack. There is a race between the UID turning active and
3139 // activity being resumed. The proper fix is very risky, so we temporary add
3140 // some polling which should happen pretty rarely anyway as the race is hard
3141 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003142 active = mActiveUids.find(uid) != mActiveUids.end();
Hui Yu12c7ec72020-05-04 17:40:52 +00003143 if (!active) active = am.isUidActive(uid, callingPackage);
Svet Ganov94ec46f2018-06-08 15:03:46 -07003144 if (active) {
3145 break;
3146 }
3147 if (startTimeMillis <= 0) {
3148 startTimeMillis = uptimeMillis();
3149 }
3150 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003151 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003152 if (remainingTimeMillis <= 0) {
3153 break;
3154 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003155 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
3156
3157 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003158 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003159 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003160 } while (true);
3161
Svet Ganov7b4ab782018-03-25 12:48:10 -07003162 if (active) {
3163 // Now that we found out the UID is actually active, cache that
3164 mActiveUids.insert(uid);
3165 }
3166 }
3167 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08003168}
3169
Varun Shahb42f1eb2019-04-16 14:45:13 -07003170int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
3171 Mutex::Autolock _l(mUidLock);
3172 return getProcStateLocked(uid);
3173}
3174
3175int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
3176 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
3177 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
3178 procState = mMonitoredUids[uid].first;
3179 }
3180 return procState;
3181}
3182
Svet Ganov7b4ab782018-03-25 12:48:10 -07003183void CameraService::UidPolicy::UidPolicy::addOverrideUid(uid_t uid,
3184 String16 callingPackage, bool active) {
3185 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08003186}
3187
Svet Ganov7b4ab782018-03-25 12:48:10 -07003188void CameraService::UidPolicy::removeOverrideUid(uid_t uid, String16 callingPackage) {
3189 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08003190}
3191
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003192void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
3193 Mutex::Autolock _l(mUidLock);
3194 ALOGV("UidPolicy: ActivityManager has died");
3195 mRegistered = false;
3196 mActiveUids.clear();
3197}
3198
Svet Ganov7b4ab782018-03-25 12:48:10 -07003199void CameraService::UidPolicy::updateOverrideUid(uid_t uid, String16 callingPackage,
3200 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003201 bool wasActive = false;
3202 bool isActive = false;
3203 {
3204 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003205 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003206 mOverrideUids.erase(uid);
3207 if (insert) {
3208 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
3209 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003210 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003211 }
3212 if (wasActive != isActive && !isActive) {
3213 sp<CameraService> service = mService.promote();
3214 if (service != nullptr) {
3215 service->blockClientsForUid(uid);
3216 }
3217 }
3218}
3219
3220// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08003221// SensorPrivacyPolicy
3222// ----------------------------------------------------------------------------
3223void CameraService::SensorPrivacyPolicy::registerSelf() {
3224 Mutex::Autolock _l(mSensorPrivacyLock);
3225 if (mRegistered) {
3226 return;
3227 }
Steven Moreland3cf67172020-01-29 11:44:22 -08003228 mSpm.addSensorPrivacyListener(this);
3229 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
3230 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003231 if (res == OK) {
3232 mRegistered = true;
3233 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
3234 }
3235}
3236
Evan Severson190ad252021-01-07 20:37:15 -08003237status_t CameraService::SensorPrivacyPolicy::registerSelfForIndividual(int userId) {
3238 Mutex::Autolock _l(mSensorPrivacyLock);
3239 if (mRegistered) {
3240 return OK;
3241 }
3242
3243 status_t res = mSpm.addIndividualSensorPrivacyListener(userId,
3244 SensorPrivacyManager::INDIVIDUAL_SENSOR_CAMERA, this);
3245 if (res != OK) {
3246 ALOGE("Unable to register camera privacy listener: %s (%d)", strerror(-res), res);
3247 return res;
3248 }
3249
3250 res = mSpm.isIndividualSensorPrivacyEnabled(userId,
3251 SensorPrivacyManager::INDIVIDUAL_SENSOR_CAMERA, mSensorPrivacyEnabled);
3252 if (res != OK) {
3253 ALOGE("Unable to check camera privacy: %s (%d)", strerror(-res), res);
3254 return res;
3255 }
3256
3257 res = mSpm.linkToDeath(this);
3258 if (res != OK) {
3259 ALOGE("Register link to death failed for sensor privacy: %s (%d)", strerror(-res), res);
3260 return res;
3261 }
3262
3263 mRegistered = true;
Evan Seversondd51a012021-02-03 09:15:21 -08003264 mIsIndividual = true;
3265 mUserId = userId;
Evan Severson190ad252021-01-07 20:37:15 -08003266 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
3267 return OK;
3268}
3269
Michael Grooverd1d435a2018-12-18 17:39:42 -08003270void CameraService::SensorPrivacyPolicy::unregisterSelf() {
3271 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08003272 mSpm.removeSensorPrivacyListener(this);
3273 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003274 mRegistered = false;
3275 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
3276}
3277
3278bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
3279 Mutex::Autolock _l(mSensorPrivacyLock);
3280 return mSensorPrivacyEnabled;
3281}
3282
3283binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
3284 {
3285 Mutex::Autolock _l(mSensorPrivacyLock);
3286 mSensorPrivacyEnabled = enabled;
3287 }
3288 // if sensor privacy is enabled then block all clients from accessing the camera
Evan Severson190ad252021-01-07 20:37:15 -08003289 sp<CameraService> service = mService.promote();
3290 if (service != nullptr) {
Evan Seversondd51a012021-02-03 09:15:21 -08003291 if (mIsIndividual) {
3292 service->setMuteForAllClients(mUserId, enabled);
Evan Severson190ad252021-01-07 20:37:15 -08003293 } else {
3294 if (enabled) {
3295 service->blockAllClients();
3296 }
Michael Grooverd1d435a2018-12-18 17:39:42 -08003297 }
3298 }
3299 return binder::Status::ok();
3300}
3301
3302void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
3303 Mutex::Autolock _l(mSensorPrivacyLock);
3304 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
3305 mRegistered = false;
3306}
3307
3308// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003309// CameraState
3310// ----------------------------------------------------------------------------
3311
3312CameraService::CameraState::CameraState(const String8& id, int cost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003313 const std::set<String8>& conflicting, SystemCameraKind systemCameraKind) : mId(id),
3314 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
3315 mSystemCameraKind(systemCameraKind) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08003316
3317CameraService::CameraState::~CameraState() {}
3318
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003319CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003320 Mutex::Autolock lock(mStatusLock);
3321 return mStatus;
3322}
3323
Shuzhen Wang43858162020-01-10 13:42:15 -08003324std::vector<String8> CameraService::CameraState::getUnavailablePhysicalIds() const {
3325 Mutex::Autolock lock(mStatusLock);
3326 std::vector<String8> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
3327 return res;
3328}
3329
Ruben Brunkcc776712015-02-17 20:18:47 -08003330CameraParameters CameraService::CameraState::getShimParams() const {
3331 return mShimParams;
3332}
3333
3334void CameraService::CameraState::setShimParams(const CameraParameters& params) {
3335 mShimParams = params;
3336}
3337
3338int CameraService::CameraState::getCost() const {
3339 return mCost;
3340}
3341
3342std::set<String8> CameraService::CameraState::getConflicting() const {
3343 return mConflicting;
3344}
3345
3346String8 CameraService::CameraState::getId() const {
3347 return mId;
3348}
3349
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003350SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
3351 return mSystemCameraKind;
3352}
3353
Shuzhen Wang43858162020-01-10 13:42:15 -08003354bool CameraService::CameraState::addUnavailablePhysicalId(const String8& physicalId) {
3355 Mutex::Autolock lock(mStatusLock);
3356 auto result = mUnavailablePhysicalIds.insert(physicalId);
3357 return result.second;
3358}
3359
3360bool CameraService::CameraState::removeUnavailablePhysicalId(const String8& physicalId) {
3361 Mutex::Autolock lock(mStatusLock);
3362 auto count = mUnavailablePhysicalIds.erase(physicalId);
3363 return count > 0;
3364}
3365
Ruben Brunkcc776712015-02-17 20:18:47 -08003366// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07003367// ClientEventListener
3368// ----------------------------------------------------------------------------
3369
3370void CameraService::ClientEventListener::onClientAdded(
3371 const resource_policy::ClientDescriptor<String8,
3372 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003373 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003374 if (basicClient.get() != nullptr) {
3375 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3376 notifier.noteStartCamera(descriptor.getKey(),
3377 static_cast<int>(basicClient->getClientUid()));
3378 }
3379}
3380
3381void CameraService::ClientEventListener::onClientRemoved(
3382 const resource_policy::ClientDescriptor<String8,
3383 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003384 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003385 if (basicClient.get() != nullptr) {
3386 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3387 notifier.noteStopCamera(descriptor.getKey(),
3388 static_cast<int>(basicClient->getClientUid()));
3389 }
3390}
3391
3392
3393// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003394// CameraClientManager
3395// ----------------------------------------------------------------------------
3396
Ruben Brunk99e69712015-05-26 17:25:07 -07003397CameraService::CameraClientManager::CameraClientManager() {
3398 setListener(std::make_shared<ClientEventListener>());
3399}
3400
Ruben Brunkcc776712015-02-17 20:18:47 -08003401CameraService::CameraClientManager::~CameraClientManager() {}
3402
3403sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
3404 const String8& id) const {
3405 auto descriptor = get(id);
3406 if (descriptor == nullptr) {
3407 return sp<BasicClient>{nullptr};
3408 }
3409 return descriptor->getValue();
3410}
3411
3412String8 CameraService::CameraClientManager::toString() const {
3413 auto all = getAll();
3414 String8 ret("[");
3415 bool hasAny = false;
3416 for (auto& i : all) {
3417 hasAny = true;
3418 String8 key = i->getKey();
3419 int32_t cost = i->getCost();
3420 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00003421 int32_t score = i->getPriority().getScore();
3422 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08003423 auto conflicting = i->getConflicting();
3424 auto clientSp = i->getValue();
3425 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07003426 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08003427 if (clientSp.get() != nullptr) {
3428 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07003429 uid_t clientUid = clientSp->getClientUid();
3430 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003431 }
Emilian Peev8131a262017-02-01 12:33:43 +00003432 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
3433 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08003434
Ruben Brunk6267b532015-04-30 17:44:07 -07003435 if (clientSp.get() != nullptr) {
3436 ret.appendFormat("User Id: %d, ", clientUserId);
3437 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003438 if (packageName.size() != 0) {
3439 ret.appendFormat("Client Package Name: %s", packageName.string());
3440 }
3441
3442 ret.append(", Conflicting Client Devices: {");
3443 for (auto& j : conflicting) {
3444 ret.appendFormat("%s, ", j.string());
3445 }
3446 ret.append("})");
3447 }
3448 if (hasAny) ret.append("\n");
3449 ret.append("]\n");
3450 return ret;
3451}
3452
3453CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3454 const String8& key, const sp<BasicClient>& value, int32_t cost,
Emilian Peev8131a262017-02-01 12:33:43 +00003455 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
3456 int32_t state) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003457
Steven Moreland89a2c5c2020-01-31 15:02:25 -08003458 bool isVendorClient = getCurrentServingCall() == BinderCallType::HWBINDER;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003459 int32_t score_adj = isVendorClient ? kVendorClientScore : score;
3460 int32_t state_adj = isVendorClient ? kVendorClientState: state;
3461
Ruben Brunkcc776712015-02-17 20:18:47 -08003462 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003463 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj, isVendorClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08003464}
3465
3466CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3467 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
3468 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00003469 partial->getConflicting(), partial->getPriority().getScore(),
3470 partial->getOwnerId(), partial->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08003471}
3472
3473// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07003474
3475static const int kDumpLockRetries = 50;
3476static const int kDumpLockSleep = 60000;
3477
3478static bool tryLock(Mutex& mutex)
3479{
3480 bool locked = false;
3481 for (int i = 0; i < kDumpLockRetries; ++i) {
3482 if (mutex.tryLock() == NO_ERROR) {
3483 locked = true;
3484 break;
3485 }
3486 usleep(kDumpLockSleep);
3487 }
3488 return locked;
3489}
3490
3491status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003492 ATRACE_CALL();
3493
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003494 if (checkCallingPermission(sDumpPermission) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003495 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07003496 CameraThreadState::getCallingPid(),
3497 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003498 return NO_ERROR;
3499 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003500 bool locked = tryLock(mServiceLock);
3501 // failed to lock - CameraService is probably deadlocked
3502 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003503 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003504 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003505
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003506 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003507 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07003508
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003509 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003510 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08003511
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003512 if (locked) mServiceLock.unlock();
3513 return NO_ERROR;
3514 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003515 dprintf(fd, "\n== Service global info: ==\n\n");
3516 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003517 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07003518 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
3519 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003520 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
3521 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
3522 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003523 String8 activeClientString = mActiveClientManager.toString();
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003524 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
3525 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003526
3527 dumpEventLog(fd);
3528
3529 bool stateLocked = tryLock(mCameraStatesLock);
3530 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003531 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003532 }
3533
Emilian Peevbd8c5032018-02-14 23:05:40 +00003534 int argSize = args.size();
3535 for (int i = 0; i < argSize; i++) {
3536 if (args[i] == TagMonitor::kMonitorOption) {
3537 if (i + 1 < argSize) {
3538 mMonitorTags = String8(args[i + 1]);
3539 }
3540 break;
3541 }
3542 }
3543
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003544 for (auto& state : mCameraStates) {
3545 String8 cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003546
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003547 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003548
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003549 CameraParameters p = state.second->getShimParams();
3550 if (!p.isEmpty()) {
3551 dprintf(fd, " Camera1 API shim is using parameters:\n ");
3552 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003553 }
3554
3555 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08003556 if (clientDescriptor != nullptr) {
3557 dprintf(fd, " Device %s is open. Client instance dump:\n",
3558 cameraId.string());
3559 dprintf(fd, " Client priority score: %d state: %d\n",
3560 clientDescriptor->getPriority().getScore(),
3561 clientDescriptor->getPriority().getState());
3562 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
3563
3564 auto client = clientDescriptor->getValue();
3565 dprintf(fd, " Client package: %s\n",
3566 String8(client->getPackageName()).string());
3567
3568 client->dumpClient(fd, args);
3569 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003570 dprintf(fd, " Device %s is closed, no client instance\n",
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003571 cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003572 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003573
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003574 }
3575
3576 if (stateLocked) mCameraStatesLock.unlock();
3577
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003578 if (locked) mServiceLock.unlock();
3579
Emilian Peevf53f66e2017-04-11 14:29:43 +01003580 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003581
3582 dprintf(fd, "\n== Vendor tags: ==\n\n");
3583
3584 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
3585 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00003586 sp<VendorTagDescriptorCache> cache =
3587 VendorTagDescriptorCache::getGlobalVendorTagCache();
3588 if (cache == NULL) {
3589 dprintf(fd, "No vendor tags.\n");
3590 } else {
3591 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
3592 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003593 } else {
3594 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
3595 }
3596
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003597 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003598 dprintf(fd, "\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003599 camera3::CameraTraces::dump(fd, args);
3600
3601 // Process dump arguments, if any
3602 int n = args.size();
3603 String16 verboseOption("-v");
3604 String16 unreachableOption("--unreachable");
3605 for (int i = 0; i < n; i++) {
3606 if (args[i] == verboseOption) {
3607 // change logging level
3608 if (i + 1 >= n) continue;
3609 String8 levelStr(args[i+1]);
3610 int level = atoi(levelStr.string());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003611 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003612 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003613 } else if (args[i] == unreachableOption) {
3614 // Dump memory analysis
3615 // TODO - should limit be an argument parameter?
3616 UnreachableMemoryInfo info;
3617 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
3618 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003619 dprintf(fd, "\n== Unable to dump unreachable memory. "
3620 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003621 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003622 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003623 std::string s = info.ToString(/*log_contents*/ true);
3624 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003625 }
3626 }
3627 }
3628 return NO_ERROR;
3629}
3630
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003631void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003632 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003633
3634 Mutex::Autolock l(mLogLock);
3635 for (const auto& msg : mEventLog) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003636 dprintf(fd, " %s\n", msg.string());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003637 }
3638
3639 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003640 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003641 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003642 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003643 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003644 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003645}
3646
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003647void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003648 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003649 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
3650 if (mTorchClientMap[i] == who) {
3651 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003652 String8 cameraId = mTorchClientMap.keyAt(i);
3653 status_t res = mFlashlight->setTorchMode(cameraId, false);
3654 if (res) {
3655 ALOGE("%s: torch client died but couldn't turn off torch: "
3656 "%s (%d)", __FUNCTION__, strerror(-res), res);
3657 return;
3658 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003659 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003660 break;
3661 }
3662 }
3663}
3664
Ruben Brunkcc776712015-02-17 20:18:47 -08003665/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003666
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003667 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07003668 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
3669 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003670 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003671 // PID here is approximate and can be wrong.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003672 logClientDied(CameraThreadState::getCallingPid(), String8("Binder died unexpectedly"));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003673
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003674 // check torch client
3675 handleTorchClientBinderDied(who);
3676
3677 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08003678 if(!evictClientIdByRemote(who)) {
3679 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003680 return;
3681 }
3682
Ruben Brunkcc776712015-02-17 20:18:47 -08003683 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
3684 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003685}
3686
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003687void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003688 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08003689}
3690
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003691void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
3692 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003693 // Do not lock mServiceLock here or can get into a deadlock from
3694 // connect() -> disconnect -> updateStatus
3695
3696 auto state = getCameraState(cameraId);
3697
3698 if (state == nullptr) {
3699 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
3700 cameraId.string());
3701 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07003702 }
3703
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003704 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
3705 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3706 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3707 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
3708 return;
3709 }
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003710 bool supportsHAL3 = false;
3711 // supportsCameraApi also holds mInterfaceMutex, we can't call it in the
3712 // HIDL onStatusChanged wrapper call (we'll hold mStatusListenerLock and
3713 // mInterfaceMutex together, which can lead to deadlocks)
3714 binder::Status sRet =
3715 supportsCameraApi(String16(cameraId), hardware::ICameraService::API_VERSION_2,
3716 &supportsHAL3);
3717 if (!sRet.isOk()) {
3718 ALOGW("%s: Failed to determine if device supports HAL3 %s, supportsCameraApi call failed",
3719 __FUNCTION__, cameraId.string());
3720 return;
3721 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003722
3723 // Collect the logical cameras without holding mStatusLock in updateStatus
3724 // as that can lead to a deadlock(b/162192331).
3725 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08003726 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08003727 // of the listeners with both the mStatusLock and mStatusListenerLock held
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003728 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind, &supportsHAL3,
3729 &logicalCameraIds]
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003730 (const String8& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003731
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003732 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003733 // Update torch status if it has a flash unit.
3734 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003735 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003736 if (getTorchStatusLocked(cameraId, &torchStatus) !=
3737 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003738 TorchModeStatus newTorchStatus =
3739 status == StatusInternal::PRESENT ?
3740 TorchModeStatus::AVAILABLE_OFF :
3741 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003742 if (torchStatus != newTorchStatus) {
3743 onTorchStatusChangedLocked(cameraId, newTorchStatus);
3744 }
3745 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003746 }
3747
3748 Mutex::Autolock lock(mStatusListenerLock);
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003749 notifyPhysicalCameraStatusLocked(mapToInterface(status), String16(cameraId),
3750 logicalCameraIds, deviceKind);
Shuzhen Wang43858162020-01-10 13:42:15 -08003751
Ruben Brunkcc776712015-02-17 20:18:47 -08003752 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003753 bool isVendorListener = listener->isVendorListener();
3754 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
3755 listener->getListenerPid(), listener->getListenerUid()) ||
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07003756 (isVendorListener && !supportsHAL3)) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003757 ALOGV("Skipping discovery callback for system-only camera/HAL1 device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003758 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003759 continue;
3760 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003761 listener->getListener()->onStatusChanged(mapToInterface(status),
Emilian Peev53722fa2019-02-22 17:47:20 -08003762 String16(cameraId));
Ruben Brunkcc776712015-02-17 20:18:47 -08003763 }
3764 });
Igor Murashkincba2c162013-03-20 15:56:31 -07003765}
3766
Shuzhen Wang695044d2020-03-06 09:02:23 -08003767void CameraService::updateOpenCloseStatus(const String8& cameraId, bool open,
3768 const String16& clientPackageName) {
3769 Mutex::Autolock lock(mStatusListenerLock);
3770
3771 for (const auto& it : mListenerList) {
3772 if (!it->isOpenCloseCallbackAllowed()) {
3773 continue;
3774 }
3775
3776 binder::Status ret;
3777 String16 cameraId64(cameraId);
3778 if (open) {
3779 ret = it->getListener()->onCameraOpened(cameraId64, clientPackageName);
3780 } else {
3781 ret = it->getListener()->onCameraClosed(cameraId64);
3782 }
3783 if (!ret.isOk()) {
3784 ALOGE("%s: Failed to trigger onCameraOpened/onCameraClosed callback: %d", __FUNCTION__,
3785 ret.exceptionCode());
3786 }
3787 }
3788}
3789
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003790template<class Func>
3791void CameraService::CameraState::updateStatus(StatusInternal status,
3792 const String8& cameraId,
3793 std::initializer_list<StatusInternal> rejectSourceStates,
3794 Func onStatusUpdatedLocked) {
3795 Mutex::Autolock lock(mStatusLock);
3796 StatusInternal oldStatus = mStatus;
3797 mStatus = status;
3798
3799 if (oldStatus == status) {
3800 return;
3801 }
3802
3803 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
3804 cameraId.string(), oldStatus, status);
3805
3806 if (oldStatus == StatusInternal::NOT_PRESENT &&
3807 (status != StatusInternal::PRESENT &&
3808 status != StatusInternal::ENUMERATING)) {
3809
3810 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
3811 __FUNCTION__);
3812 mStatus = oldStatus;
3813 return;
3814 }
3815
3816 /**
3817 * Sometimes we want to conditionally do a transition.
3818 * For example if a client disconnects, we want to go to PRESENT
3819 * only if we weren't already in NOT_PRESENT or ENUMERATING.
3820 */
3821 for (auto& rejectStatus : rejectSourceStates) {
3822 if (oldStatus == rejectStatus) {
3823 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
3824 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
3825 mStatus = oldStatus;
3826 return;
3827 }
3828 }
3829
3830 onStatusUpdatedLocked(cameraId, status);
3831}
3832
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003833status_t CameraService::getTorchStatusLocked(
3834 const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003835 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003836 if (!status) {
3837 return BAD_VALUE;
3838 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003839 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3840 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003841 // invalid camera ID or the camera doesn't have a flash unit
3842 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003843 }
3844
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003845 *status = mTorchStatusMap.valueAt(index);
3846 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003847}
3848
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003849status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003850 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003851 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3852 if (index == NAME_NOT_FOUND) {
3853 return BAD_VALUE;
3854 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003855 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003856
3857 return OK;
3858}
3859
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003860std::list<String16> CameraService::getLogicalCameras(
3861 const String8& physicalCameraId) {
3862 std::list<String16> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08003863 Mutex::Autolock lock(mCameraStatesLock);
3864 for (const auto& state : mCameraStates) {
3865 std::vector<std::string> physicalCameraIds;
3866 if (!mCameraProviderManager->isLogicalCamera(state.first.c_str(), &physicalCameraIds)) {
3867 // This is not a logical multi-camera.
3868 continue;
3869 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003870 if (std::find(physicalCameraIds.begin(), physicalCameraIds.end(), physicalCameraId.c_str())
Shuzhen Wang43858162020-01-10 13:42:15 -08003871 == physicalCameraIds.end()) {
3872 // cameraId is not a physical camera of this logical multi-camera.
3873 continue;
3874 }
3875
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003876 retList.emplace_back(String16(state.first));
3877 }
3878 return retList;
3879}
3880
3881void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
3882 const String16& physicalCameraId, const std::list<String16>& logicalCameraIds,
3883 SystemCameraKind deviceKind) {
3884 // mStatusListenerLock is expected to be locked
3885 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08003886 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003887 // Note: we check only the deviceKind of the physical camera id
3888 // since, logical camera ids and their physical camera ids are
3889 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07003890 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
3891 listener->getListenerPid(), listener->getListenerUid())) {
3892 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003893 String8(physicalCameraId).c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07003894 continue;
3895 }
Shuzhen Wang43858162020-01-10 13:42:15 -08003896 listener->getListener()->onPhysicalCameraStatusChanged(status,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003897 logicalCameraId, physicalCameraId);
Shuzhen Wang43858162020-01-10 13:42:15 -08003898 }
3899 }
3900}
3901
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003902
Svet Ganova453d0d2018-01-11 15:37:58 -08003903void CameraService::blockClientsForUid(uid_t uid) {
3904 const auto clients = mActiveClientManager.getAll();
3905 for (auto& current : clients) {
3906 if (current != nullptr) {
3907 const auto basicClient = current->getValue();
3908 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
3909 basicClient->block();
3910 }
3911 }
3912 }
3913}
3914
Michael Grooverd1d435a2018-12-18 17:39:42 -08003915void CameraService::blockAllClients() {
3916 const auto clients = mActiveClientManager.getAll();
3917 for (auto& current : clients) {
3918 if (current != nullptr) {
3919 const auto basicClient = current->getValue();
3920 if (basicClient.get() != nullptr) {
3921 basicClient->block();
3922 }
3923 }
3924 }
3925}
3926
Evan Severson190ad252021-01-07 20:37:15 -08003927void CameraService::setMuteForAllClients(userid_t userId, bool enabled) {
3928 const auto clients = mActiveClientManager.getAll();
3929 for (auto& current : clients) {
3930 if (current != nullptr) {
3931 const auto basicClient = current->getValue();
3932 if (basicClient.get() != nullptr
3933 && multiuser_get_user_id(basicClient->getClientUid()) == userId) {
3934 basicClient->setCameraMute(enabled);
3935 }
3936 }
3937 }
3938}
3939
Svet Ganova453d0d2018-01-11 15:37:58 -08003940// NOTE: This is a remote API - make sure all args are validated
3941status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
3942 if (!checkCallingPermission(sManageCameraPermission, nullptr, nullptr)) {
3943 return PERMISSION_DENIED;
3944 }
3945 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
3946 return BAD_VALUE;
3947 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003948 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003949 return handleSetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07003950 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003951 return handleResetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07003952 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003953 return handleGetUidState(args, out, err);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003954 } else if (args.size() >= 2 && args[0] == String16("set-rotate-and-crop")) {
3955 return handleSetRotateAndCrop(args);
3956 } else if (args.size() >= 1 && args[0] == String16("get-rotate-and-crop")) {
3957 return handleGetRotateAndCrop(out);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08003958 } else if (args.size() >= 2 && args[0] == String16("set-image-dump-mask")) {
3959 return handleSetImageDumpMask(args);
3960 } else if (args.size() >= 1 && args[0] == String16("get-image-dump-mask")) {
3961 return handleGetImageDumpMask(out);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003962 } else if (args.size() >= 2 && args[0] == String16("set-camera-mute")) {
3963 return handleSetCameraMute(args);
Svet Ganova453d0d2018-01-11 15:37:58 -08003964 } else if (args.size() == 1 && args[0] == String16("help")) {
3965 printHelp(out);
3966 return NO_ERROR;
3967 }
3968 printHelp(err);
3969 return BAD_VALUE;
3970}
3971
3972status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07003973 String16 packageName = args[1];
3974
Svet Ganova453d0d2018-01-11 15:37:58 -08003975 bool active = false;
3976 if (args[2] == String16("active")) {
3977 active = true;
3978 } else if ((args[2] != String16("idle"))) {
3979 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
3980 return BAD_VALUE;
3981 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003982
3983 int userId = 0;
3984 if (args.size() >= 5 && args[3] == String16("--user")) {
3985 userId = atoi(String8(args[4]));
3986 }
3987
3988 uid_t uid;
3989 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
3990 return BAD_VALUE;
3991 }
3992
3993 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08003994 return NO_ERROR;
3995}
3996
3997status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07003998 String16 packageName = args[1];
3999
4000 int userId = 0;
4001 if (args.size() >= 4 && args[2] == String16("--user")) {
4002 userId = atoi(String8(args[3]));
4003 }
4004
4005 uid_t uid;
4006 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004007 return BAD_VALUE;
4008 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004009
4010 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08004011 return NO_ERROR;
4012}
4013
4014status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004015 String16 packageName = args[1];
4016
4017 int userId = 0;
4018 if (args.size() >= 4 && args[2] == String16("--user")) {
4019 userId = atoi(String8(args[3]));
4020 }
4021
4022 uid_t uid;
4023 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004024 return BAD_VALUE;
4025 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004026
4027 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004028 return dprintf(out, "active\n");
4029 } else {
4030 return dprintf(out, "idle\n");
4031 }
4032}
4033
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004034status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
4035 int rotateValue = atoi(String8(args[1]));
4036 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
4037 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
4038 Mutex::Autolock lock(mServiceLock);
4039
4040 mOverrideRotateAndCropMode = rotateValue;
4041
4042 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
4043
4044 const auto clients = mActiveClientManager.getAll();
4045 for (auto& current : clients) {
4046 if (current != nullptr) {
4047 const auto basicClient = current->getValue();
4048 if (basicClient.get() != nullptr) {
4049 basicClient->setRotateAndCropOverride(rotateValue);
4050 }
4051 }
4052 }
4053
4054 return OK;
4055}
4056
4057status_t CameraService::handleGetRotateAndCrop(int out) {
4058 Mutex::Autolock lock(mServiceLock);
4059
4060 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
4061}
4062
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004063status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
4064 char *endPtr;
4065 errno = 0;
4066 String8 maskString8 = String8(args[1]);
4067 long maskValue = strtol(maskString8.c_str(), &endPtr, 10);
4068
4069 if (errno != 0) return BAD_VALUE;
4070 if (endPtr != maskString8.c_str() + maskString8.size()) return BAD_VALUE;
4071 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
4072
4073 Mutex::Autolock lock(mServiceLock);
4074
4075 mImageDumpMask = maskValue;
4076
4077 return OK;
4078}
4079
4080status_t CameraService::handleGetImageDumpMask(int out) {
4081 Mutex::Autolock lock(mServiceLock);
4082
4083 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
4084}
4085
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004086status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
4087 int muteValue = strtol(String8(args[1]), nullptr, 10);
4088 if (errno != 0) return BAD_VALUE;
4089
4090 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
4091 Mutex::Autolock lock(mServiceLock);
4092
4093 mOverrideCameraMuteMode = (muteValue == 1);
4094
4095 const auto clients = mActiveClientManager.getAll();
4096 for (auto& current : clients) {
4097 if (current != nullptr) {
4098 const auto basicClient = current->getValue();
4099 if (basicClient.get() != nullptr) {
4100 if (basicClient->supportsCameraMute()) {
4101 basicClient->setCameraMute(mOverrideCameraMuteMode);
4102 }
4103 }
4104 }
4105 }
4106
4107 return OK;
4108}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004109
Svet Ganova453d0d2018-01-11 15:37:58 -08004110status_t CameraService::printHelp(int out) {
4111 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07004112 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
4113 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
4114 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004115 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
4116 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
4117 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004118 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
4119 " Valid values 0=OFF, 1=ON for JPEG\n"
4120 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004121 " set-camera-mute <0/1> enable or disable camera muting\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08004122 " help print this message\n");
4123}
4124
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004125int32_t CameraService::updateAudioRestriction() {
4126 Mutex::Autolock lock(mServiceLock);
4127 return updateAudioRestrictionLocked();
4128}
4129
4130int32_t CameraService::updateAudioRestrictionLocked() {
4131 int32_t mode = 0;
4132 // iterate through all active client
4133 for (const auto& i : mActiveClientManager.getAll()) {
4134 const auto clientSp = i->getValue();
4135 mode |= clientSp->getAudioRestriction();
4136 }
4137
4138 bool modeChanged = (mAudioRestriction != mode);
4139 mAudioRestriction = mode;
4140 if (modeChanged) {
4141 mAppOps.setCameraAudioRestriction(mode);
4142 }
4143 return mode;
4144}
4145
Evan Severson190ad252021-01-07 20:37:15 -08004146bool CameraService::isUserSensorPrivacyEnabledForUid(uid_t uid) {
4147 userid_t userId = multiuser_get_user_id(uid);
4148 if (mCameraSensorPrivacyPolicies.find(userId) == mCameraSensorPrivacyPolicies.end()) {
4149 sp<SensorPrivacyPolicy> userPolicy = new SensorPrivacyPolicy(this);
4150 if (userPolicy->registerSelfForIndividual(userId) != OK) {
4151 return false;
4152 }
4153 mCameraSensorPrivacyPolicies[userId] = userPolicy;
4154 }
4155 return mCameraSensorPrivacyPolicies[userId]->isSensorPrivacyEnabled();
4156}
4157
Mathias Agopian65ab4712010-07-14 17:59:35 -07004158}; // namespace android