blob: 6efb90be1804f419fb45c412d23d7def3b82261c [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
Evan Severson09ab4002021-02-10 14:15:19 -080032#include <android/content/pm/IPackageManagerNative.h>
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080033#include <android/hardware/ICamera.h>
34#include <android/hardware/ICameraClient.h>
35
Alex Deymo9c2a2c22016-08-25 11:59:14 -070036#include <android-base/macros.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080037#include <android-base/parseint.h>
Jayant Chowdharyb61526c2019-05-13 19:37:42 -070038#include <android-base/stringprintf.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080039#include <binder/ActivityManager.h>
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -080040#include <binder/AppOpsManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070041#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070042#include <binder/MemoryBase.h>
43#include <binder/MemoryHeapBase.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080044#include <binder/PermissionController.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>
Steven Moreland886d7322021-04-02 04:19:45 +000060#include <processinfo/ProcessInfoService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070061#include <utils/Errors.h>
62#include <utils/Log.h>
63#include <utils/String16.h>
Svet Ganov94ec46f2018-06-08 15:03:46 -070064#include <utils/SystemClock.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080065#include <utils/Trace.h>
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080066#include <utils/CallStack.h>
Chien-Yu Chen98a668f2015-12-18 14:10:33 -080067#include <private/android_filesystem_config.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080068#include <system/camera_vendor_tags.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070069#include <system/camera_metadata.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080070
Ruben Brunkb2119af2014-05-09 19:57:56 -070071#include <system/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070072
73#include "CameraService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070074#include "api1/Camera2Client.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070075#include "api2/CameraDeviceClient.h"
Igor Murashkinff3e31d2013-10-23 16:40:06 -070076#include "utils/CameraTraces.h"
Emilian Peevbd8c5032018-02-14 23:05:40 +000077#include "utils/TagMonitor.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070078#include "utils/CameraThreadState.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070079#include "utils/CameraServiceProxyWrapper.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070080
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080081namespace {
82 const char* kPermissionServiceName = "permission";
83}; // namespace anonymous
84
Mathias Agopian65ab4712010-07-14 17:59:35 -070085namespace android {
86
Jayant Chowdharyb61526c2019-05-13 19:37:42 -070087using base::StringPrintf;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080088using binder::Status;
Jayant Chowdharybe543d42018-08-15 13:16:14 -070089using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -080090using hardware::ICamera;
91using hardware::ICameraClient;
92using hardware::ICameraServiceListener;
93using hardware::camera::common::V1_0::CameraDeviceStatus;
94using hardware::camera::common::V1_0::TorchModeStatus;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080095using hardware::camera2::utils::CameraIdAndSessionConfiguration;
96using hardware::camera2::utils::ConcurrentCameraIdCombination;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080097
Mathias Agopian65ab4712010-07-14 17:59:35 -070098// ----------------------------------------------------------------------------
99// Logging support -- this is for debugging only
100// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700101volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700102
Steve Blockb8a80522011-12-20 16:23:08 +0000103#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
104#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700105
106static void setLogLevel(int level) {
107 android_atomic_write(level, &gLogLevel);
108}
109
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800110// Convenience methods for constructing binder::Status objects for error returns
111
112#define STATUS_ERROR(errorCode, errorString) \
113 binder::Status::fromServiceSpecificError(errorCode, \
114 String8::format("%s:%d: %s", __FUNCTION__, __LINE__, errorString))
115
116#define STATUS_ERROR_FMT(errorCode, errorString, ...) \
117 binder::Status::fromServiceSpecificError(errorCode, \
118 String8::format("%s:%d: " errorString, __FUNCTION__, __LINE__, \
119 __VA_ARGS__))
120
Mathias Agopian65ab4712010-07-14 17:59:35 -0700121// ----------------------------------------------------------------------------
122
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700123static const String16 sDumpPermission("android.permission.DUMP");
Svet Ganova453d0d2018-01-11 15:37:58 -0800124static const String16 sManageCameraPermission("android.permission.MANAGE_CAMERA");
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700125static const String16 sCameraPermission("android.permission.CAMERA");
126static const String16 sSystemCameraPermission("android.permission.SYSTEM_CAMERA");
127static const String16
128 sCameraSendSystemEventsPermission("android.permission.CAMERA_SEND_SYSTEM_EVENTS");
Shuzhen Wang695044d2020-03-06 09:02:23 -0800129static const String16 sCameraOpenCloseListenerPermission(
130 "android.permission.CAMERA_OPEN_CLOSE_LISTENER");
Svet Ganova453d0d2018-01-11 15:37:58 -0800131
Eino-Ville Talvala7c602c32021-03-20 17:00:18 -0700132static constexpr int32_t kVendorClientScore = resource_policy::PERCEPTIBLE_APP_ADJ;
133static constexpr int32_t kVendorClientState = ActivityManager::PROCESS_STATE_PERSISTENT_UI;
134
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800135const String8 CameraService::kOfflineDevice("offline-");
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700136
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800137CameraService::CameraService() :
138 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800139 mNumberOfCameras(0),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700140 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700141 mSoundRef(0), mInitialized(false),
142 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000143 ALOGI("CameraService started (pid=%d)", getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800144 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700145}
146
Iliyan Malchev8951a972011-04-14 16:55:59 -0700147void CameraService::onFirstRef()
148{
Ruben Brunkcc776712015-02-17 20:18:47 -0800149 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800150
Iliyan Malchev8951a972011-04-14 16:55:59 -0700151 BnCameraService::onFirstRef();
152
Ruben Brunk99e69712015-05-26 17:25:07 -0700153 // Update battery life tracking if service is restarting
154 BatteryNotifier& notifier(BatteryNotifier::getInstance());
155 notifier.noteResetCamera();
156 notifier.noteResetFlashlight();
157
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800158 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800159
Emilian Peevf53f66e2017-04-11 14:29:43 +0100160 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800161 if (res == OK) {
162 mInitialized = true;
163 }
164
Svet Ganova453d0d2018-01-11 15:37:58 -0800165 mUidPolicy = new UidPolicy(this);
166 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800167 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
168 mSensorPrivacyPolicy->registerSelf();
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700169 mAppOps.setCameraAudioRestriction(mAudioRestriction);
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700170 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
171 if (hcs->registerAsService() != android::OK) {
172 ALOGE("%s: Failed to register default android.frameworks.cameraservice.service@1.0",
173 __FUNCTION__);
174 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700175
176 // This needs to be last call in this function, so that it's as close to
177 // ServiceManager::addService() as possible.
Shuzhen Wang316781a2020-08-18 18:11:01 -0700178 CameraServiceProxyWrapper::pingCameraServiceProxy();
Shuzhen Wang24b44152019-09-20 10:38:11 -0700179 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800180}
181
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800182status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800183 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100184
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800185 std::vector<std::string> deviceIds;
186 {
187 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800188
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800189 if (nullptr == mCameraProviderManager.get()) {
190 mCameraProviderManager = new CameraProviderManager();
191 res = mCameraProviderManager->initialize(this);
192 if (res != OK) {
193 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
194 __FUNCTION__, strerror(-res), res);
195 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100196 }
197 }
198
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800199
200 // Setup vendor tags before we call get_camera_info the first time
201 // because HAL might need to setup static vendor keys in get_camera_info
202 // TODO: maybe put this into CameraProviderManager::initialize()?
203 mCameraProviderManager->setUpVendorTags();
204
205 if (nullptr == mFlashlight.get()) {
206 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700207 }
208
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800209 res = mFlashlight->findFlashUnits();
210 if (res != OK) {
211 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
212 }
213
214 deviceIds = mCameraProviderManager->getCameraDeviceIds();
215 }
216
217
218 for (auto& cameraId : deviceIds) {
219 String8 id8 = String8(cameraId.c_str());
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800220 if (getCameraState(id8) == nullptr) {
221 onDeviceStatusChanged(id8, CameraDeviceStatus::PRESENT);
222 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800223 }
224
225 return OK;
226}
227
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700228void CameraService::broadcastTorchModeStatus(const String8& cameraId, TorchModeStatus status,
229 SystemCameraKind systemCameraKind) {
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800230 Mutex::Autolock lock(mStatusListenerLock);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800231 for (auto& i : mListenerList) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700232 if (shouldSkipStatusUpdates(systemCameraKind, i->isVendorListener(), i->getListenerPid(),
233 i->getListenerUid())) {
234 ALOGV("Skipping torch callback for system-only camera device %s",
235 cameraId.c_str());
236 continue;
237 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700238 i->getListener()->onTorchStatusChanged(mapToInterface(status), String16{cameraId});
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800239 }
240}
241
Mathias Agopian65ab4712010-07-14 17:59:35 -0700242CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800243 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800244 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800245 mSensorPrivacyPolicy->unregisterSelf();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700246}
247
Emilian Peevaee727d2017-05-04 16:35:48 +0100248void CameraService::onNewProviderRegistered() {
249 enumerateProviders();
250}
251
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700252void CameraService::filterAPI1SystemCameraLocked(
253 const std::vector<std::string> &normalDeviceIds) {
254 mNormalDeviceIdsWithoutSystemCamera.clear();
255 for (auto &deviceId : normalDeviceIds) {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700256 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
257 if (getSystemCameraKind(String8(deviceId.c_str()), &deviceKind) != OK) {
258 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, deviceId.c_str());
259 continue;
260 }
261 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700262 // All system camera ids will necessarily come after public camera
263 // device ids as per the HAL interface contract.
264 break;
265 }
266 mNormalDeviceIdsWithoutSystemCamera.push_back(deviceId);
267 }
268 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
269 mNormalDeviceIdsWithoutSystemCamera.size());
270}
271
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700272status_t CameraService::getSystemCameraKind(const String8& cameraId, SystemCameraKind *kind) const {
273 auto state = getCameraState(cameraId);
274 if (state != nullptr) {
275 *kind = state->getSystemCameraKind();
276 return OK;
277 }
278 // Hidden physical camera ids won't have CameraState
279 return mCameraProviderManager->getSystemCameraKind(cameraId.c_str(), kind);
280}
281
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800282void CameraService::updateCameraNumAndIds() {
283 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700284 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
285 // Excludes hidden secure cameras
286 mNumberOfCameras =
287 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
288 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800289 mNormalDeviceIds =
290 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700291 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800292}
293
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100294void CameraService::addStates(const String8 id) {
295 std::string cameraId(id.c_str());
296 hardware::camera::common::V1_0::CameraResourceCost cost;
297 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700298 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100299 if (res != OK) {
300 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
301 return;
302 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700303 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
304 if (res != OK) {
305 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
306 return;
307 }
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100308 std::set<String8> conflicting;
309 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
310 conflicting.emplace(String8(cost.conflictingDevices[i].c_str()));
311 }
312
313 {
314 Mutex::Autolock lock(mCameraStatesLock);
315 mCameraStates.emplace(id, std::make_shared<CameraState>(id, cost.resourceCost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700316 conflicting, deviceKind));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100317 }
318
319 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100320 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100321 mTorchStatusMap.add(id, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800322
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700323 broadcastTorchModeStatus(id, TorchModeStatus::AVAILABLE_OFF, deviceKind);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100324 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800325
326 updateCameraNumAndIds();
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100327 logDeviceAdded(id, "Device added");
328}
329
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100330void CameraService::removeStates(const String8 id) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800331 updateCameraNumAndIds();
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100332 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100333 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100334 mTorchStatusMap.removeItem(id);
335 }
336
337 {
338 Mutex::Autolock lock(mCameraStatesLock);
339 mCameraStates.erase(id);
340 }
341}
342
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800343void CameraService::onDeviceStatusChanged(const String8& id,
344 CameraDeviceStatus newHalStatus) {
345 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
346 id.string(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700347
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800348 StatusInternal newStatus = mapToInternal(newHalStatus);
349
Ruben Brunkcc776712015-02-17 20:18:47 -0800350 std::shared_ptr<CameraState> state = getCameraState(id);
351
352 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700353 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100354 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700355 __FUNCTION__, id.string());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100356
357 // First add as absent to make sure clients are notified below
358 addStates(id);
359
360 updateStatus(newStatus, id);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700361 } else {
362 ALOGE("%s: Bad camera ID %s", __FUNCTION__, id.string());
363 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700364 return;
365 }
366
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800367 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800368
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800369 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800370 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700371 return;
372 }
373
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800374 if (newStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700375 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
376 newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800377
378 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
379 // to this device until the status changes
380 updateStatus(StatusInternal::NOT_PRESENT, id);
381
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800382 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700383 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800384 // Don't do this in updateStatus to avoid deadlock over mServiceLock
385 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700386
Ruben Brunkcc776712015-02-17 20:18:47 -0800387 // Remove cached shim parameters
388 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700389
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800390 // Remove online as well as offline client from the list of active clients,
391 // if they are present
392 clientToDisconnectOnline = removeClientLocked(id);
393 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + id);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700394 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800395
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800396 disconnectClient(id, clientToDisconnectOnline);
397 disconnectClient(kOfflineDevice + id, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700398
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100399 removeStates(id);
Ruben Brunkcc776712015-02-17 20:18:47 -0800400 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800401 if (oldStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700402 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
403 newStatus));
404 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800405 updateStatus(newStatus, id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700406 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800407}
Igor Murashkincba2c162013-03-20 15:56:31 -0700408
Shuzhen Wang43858162020-01-10 13:42:15 -0800409void CameraService::onDeviceStatusChanged(const String8& id,
410 const String8& physicalId,
411 CameraDeviceStatus newHalStatus) {
412 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
413 __FUNCTION__, id.string(), physicalId.string(), newHalStatus);
414
415 StatusInternal newStatus = mapToInternal(newHalStatus);
416
417 std::shared_ptr<CameraState> state = getCameraState(id);
418
419 if (state == nullptr) {
420 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
421 __FUNCTION__, id.string(), physicalId.string());
422 return;
423 }
424
425 StatusInternal logicalCameraStatus = state->getStatus();
426 if (logicalCameraStatus != StatusInternal::PRESENT &&
427 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
428 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
429 __FUNCTION__, physicalId.string(), newHalStatus, logicalCameraStatus);
430 return;
431 }
432
433 bool updated = false;
434 if (newStatus == StatusInternal::PRESENT) {
435 updated = state->removeUnavailablePhysicalId(physicalId);
436 } else {
437 updated = state->addUnavailablePhysicalId(physicalId);
438 }
439
440 if (updated) {
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800441 String8 idCombo = id + " : " + physicalId;
442 if (newStatus == StatusInternal::PRESENT) {
443 logDeviceAdded(idCombo,
444 String8::format("Device status changed to %d", newStatus));
445 } else {
446 logDeviceRemoved(idCombo,
447 String8::format("Device status changed to %d", newStatus));
448 }
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700449 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
450 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
451 if (getSystemCameraKind(id, &deviceKind) != OK) {
452 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.string());
453 return;
454 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800455 String16 id16(id), physicalId16(physicalId);
456 Mutex::Autolock lock(mStatusListenerLock);
457 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700458 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
459 listener->getListenerPid(), listener->getListenerUid())) {
460 ALOGV("Skipping discovery callback for system-only camera device %s",
461 id.c_str());
462 continue;
463 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800464 listener->getListener()->onPhysicalCameraStatusChanged(mapToInterface(newStatus),
465 id16, physicalId16);
466 }
467 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700468}
469
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800470void CameraService::disconnectClient(const String8& id, sp<BasicClient> clientToDisconnect) {
471 if (clientToDisconnect.get() != nullptr) {
472 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
473 __FUNCTION__, id.string());
474 // Notify the client of disconnection
475 clientToDisconnect->notifyError(
476 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
477 CaptureResultExtras{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800478 clientToDisconnect->disconnect();
479 }
480}
481
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800482void CameraService::onTorchStatusChanged(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800483 TorchModeStatus newStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700484 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
485 status_t res = getSystemCameraKind(cameraId, &systemCameraKind);
486 if (res != OK) {
487 ALOGE("%s: Could not get system camera kind for camera id %s", __FUNCTION__,
488 cameraId.string());
489 return;
490 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800491 Mutex::Autolock al(mTorchStatusMutex);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700492 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800493}
494
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800495void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700496 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800497 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
498 __FUNCTION__, cameraId.string(), newStatus);
499
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800500 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800501 status_t res = getTorchStatusLocked(cameraId, &status);
502 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700503 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
504 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800505 return;
506 }
507 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800508 return;
509 }
510
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800511 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800512 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800513 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
514 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800515 return;
516 }
517
Ruben Brunkcc776712015-02-17 20:18:47 -0800518 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700519 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700520 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700521 auto iter = mTorchUidMap.find(cameraId);
522 if (iter != mTorchUidMap.end()) {
523 int oldUid = iter->second.second;
524 int newUid = iter->second.first;
525 BatteryNotifier& notifier(BatteryNotifier::getInstance());
526 if (oldUid != newUid) {
527 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800528 if (status == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700529 notifier.noteFlashlightOff(cameraId, oldUid);
530 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800531 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700532 notifier.noteFlashlightOn(cameraId, newUid);
533 }
534 iter->second.second = newUid;
535 } else {
536 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800537 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700538 notifier.noteFlashlightOn(cameraId, oldUid);
539 } else {
540 notifier.noteFlashlightOff(cameraId, oldUid);
541 }
542 }
543 }
544 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700545 broadcastTorchModeStatus(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800546}
547
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700548static bool hasPermissionsForSystemCamera(int callingPid, int callingUid) {
549 return checkPermission(sSystemCameraPermission, callingPid, callingUid) &&
550 checkPermission(sCameraPermission, callingPid, callingUid);
551}
552
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800553Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700554 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100555 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700556 bool hasSystemCameraPermissions =
557 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
558 CameraThreadState::getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700559 switch (type) {
560 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700561 if (hasSystemCameraPermissions) {
562 *numCameras = static_cast<int>(mNormalDeviceIds.size());
563 } else {
564 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
565 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800566 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700567 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700568 if (hasSystemCameraPermissions) {
569 *numCameras = mNumberOfCameras;
570 } else {
571 *numCameras = mNumberOfCamerasWithoutSystemCamera;
572 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800573 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700574 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800575 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700576 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800577 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
578 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700579 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800580 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700581}
582
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800583Status CameraService::getCameraInfo(int cameraId,
584 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700585 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100586 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700587 std::string cameraIdStr = cameraIdIntToStrLocked(cameraId);
588 if (shouldRejectSystemCameraConnection(String8(cameraIdStr.c_str()))) {
589 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
590 "characteristics for system only device %s: ", cameraIdStr.c_str());
591 }
Emilian Peevaee727d2017-05-04 16:35:48 +0100592
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800593 if (!mInitialized) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800594 return STATUS_ERROR(ERROR_DISCONNECTED,
595 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -0700596 }
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700597 bool hasSystemCameraPermissions =
598 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
599 CameraThreadState::getCallingUid());
600 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
601 if (hasSystemCameraPermissions) {
602 cameraIdBound = mNumberOfCameras;
603 }
604 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800605 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
606 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700607 }
608
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800609 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800610 status_t err = mCameraProviderManager->getCameraInfo(
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700611 cameraIdStr.c_str(), cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100612 if (err != OK) {
613 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
614 "Error retrieving camera info from device %d: %s (%d)", cameraId,
615 strerror(-err), err);
Ruben Brunkcc776712015-02-17 20:18:47 -0800616 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100617
Ruben Brunkcc776712015-02-17 20:18:47 -0800618 return ret;
619}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700620
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800621std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700622 const std::vector<std::string> *deviceIds = &mNormalDeviceIdsWithoutSystemCamera;
623 auto callingPid = CameraThreadState::getCallingPid();
624 auto callingUid = CameraThreadState::getCallingUid();
625 if (checkPermission(sSystemCameraPermission, callingPid, callingUid) ||
626 getpid() == callingPid) {
627 deviceIds = &mNormalDeviceIds;
628 }
629 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(deviceIds->size())) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800630 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700631 __FUNCTION__, cameraIdInt, deviceIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800632 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800633 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800634
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700635 return (*deviceIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800636}
637
638String8 CameraService::cameraIdIntToStr(int cameraIdInt) {
639 Mutex::Autolock lock(mServiceLock);
640 return String8(cameraIdIntToStrLocked(cameraIdInt).c_str());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800641}
642
643Status CameraService::getCameraCharacteristics(const String16& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800644 CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700645 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700646 if (!cameraInfo) {
647 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800648 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -0700649 }
650
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800651 if (!mInitialized) {
652 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800653 return STATUS_ERROR(ERROR_DISCONNECTED,
654 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -0700655 }
656
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700657 if (shouldRejectSystemCameraConnection(String8(cameraId))) {
658 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
659 "characteristics for system only device %s: ", String8(cameraId).string());
660 }
661
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800662 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800663
Emilian Peevf53f66e2017-04-11 14:29:43 +0100664 status_t res = mCameraProviderManager->getCameraCharacteristics(
665 String8(cameraId).string(), cameraInfo);
666 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700667 if (res == NAME_NOT_FOUND) {
668 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
669 "characteristics for unknown device %s: %s (%d)", String8(cameraId).string(),
670 strerror(-res), res);
671 } else {
672 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
673 "characteristics for device %s: %s (%d)", String8(cameraId).string(),
674 strerror(-res), res);
675 }
Ruben Brunkb2119af2014-05-09 19:57:56 -0700676 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700677 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
678 if (getSystemCameraKind(String8(cameraId), &deviceKind) != OK) {
679 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, String8(cameraId).string());
680 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera kind "
681 "for device %s", String8(cameraId).string());
682 }
Jayant Chowdhary12361932018-08-27 14:46:13 -0700683 int callingPid = CameraThreadState::getCallingPid();
684 int callingUid = CameraThreadState::getCallingUid();
Emilian Peeve20c6372018-08-14 18:45:53 +0100685 std::vector<int32_t> tagsRemoved;
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700686 // If it's not calling from cameraserver, check the permission only if
687 // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
688 // it would've already been checked in shouldRejectSystemCameraConnection.
Emilian Peeve20c6372018-08-14 18:45:53 +0100689 if ((callingPid != getpid()) &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700690 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700691 !checkPermission(sCameraPermission, callingPid, callingUid)) {
Emilian Peeve20c6372018-08-14 18:45:53 +0100692 res = cameraInfo->removePermissionEntries(
693 mCameraProviderManager->getProviderTagIdLocked(String8(cameraId).string()),
694 &tagsRemoved);
695 if (res != OK) {
696 cameraInfo->clear();
697 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
698 " characteristics needing camera permission for device %s: %s (%d)",
699 String8(cameraId).string(), strerror(-res), res);
700 }
701 }
702
703 if (!tagsRemoved.empty()) {
704 res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
705 tagsRemoved.data(), tagsRemoved.size());
706 if (res != OK) {
707 cameraInfo->clear();
708 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
709 "keys needing permission for device %s: %s (%d)", String8(cameraId).string(),
710 strerror(-res), res);
711 }
712 }
713
Zhijun He2b59be82013-09-25 10:14:30 -0700714 return ret;
715}
716
Ruben Brunkcc776712015-02-17 20:18:47 -0800717String8 CameraService::getFormattedCurrentTime() {
718 time_t now = time(nullptr);
719 char formattedTime[64];
720 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
721 return String8(formattedTime);
722}
723
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800724Status CameraService::getCameraVendorTagDescriptor(
725 /*out*/
726 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700727 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800728 if (!mInitialized) {
729 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800730 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800731 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -0800732 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
733 if (globalDescriptor != nullptr) {
734 *desc = *(globalDescriptor.get());
735 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800736 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800737}
738
Emilian Peev71c73a22017-03-21 16:35:51 +0000739Status CameraService::getCameraVendorTagCache(
740 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
741 ATRACE_CALL();
742 if (!mInitialized) {
743 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
744 return STATUS_ERROR(ERROR_DISCONNECTED,
745 "Camera subsystem not available");
746 }
747 sp<VendorTagDescriptorCache> globalCache =
748 VendorTagDescriptorCache::getGlobalVendorTagCache();
749 if (globalCache != nullptr) {
750 *cache = *(globalCache.get());
751 }
752 return Status::ok();
753}
754
Emilian Peevb91f1802021-03-23 14:50:28 -0700755int CameraService::getDeviceVersion(const String8& cameraId, int* facing, int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700756 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800757
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800758 int deviceVersion = 0;
759
Emilian Peevf53f66e2017-04-11 14:29:43 +0100760 status_t res;
761 hardware::hidl_version maxVersion{0,0};
762 res = mCameraProviderManager->getHighestSupportedVersion(cameraId.string(),
763 &maxVersion);
764 if (res != OK) return -1;
765 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800766
Emilian Peevf53f66e2017-04-11 14:29:43 +0100767 hardware::CameraInfo info;
768 if (facing) {
769 res = mCameraProviderManager->getCameraInfo(cameraId.string(), &info);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -0800770 if (res != OK) return -1;
Emilian Peevf53f66e2017-04-11 14:29:43 +0100771 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -0700772 if (orientation) {
773 *orientation = info.orientation;
774 }
Igor Murashkin634a5152013-02-20 17:15:11 -0800775 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100776
Igor Murashkin634a5152013-02-20 17:15:11 -0800777 return deviceVersion;
778}
779
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800780Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700781 switch(err) {
782 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800783 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800784 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800785 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
786 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800787 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800788 return STATUS_ERROR(ERROR_DISCONNECTED,
789 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700790 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800791 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
792 "Camera HAL encountered error %d: %s",
793 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700794 }
Igor Murashkinbfc99152013-02-27 12:55:20 -0800795}
796
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800797Status CameraService::makeClient(const sp<CameraService>& cameraService,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800798 const sp<IInterface>& cameraCb, const String16& packageName,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700799 const std::optional<String16>& featureId, const String8& cameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -0700800 int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
801 int servicePid, int deviceVersion, apiLevel effectiveApiLevel,
Ruben Brunkcc776712015-02-17 20:18:47 -0800802 /*out*/sp<BasicClient>* client) {
803
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700804 // Create CameraClient based on device version reported by the HAL.
805 switch(deviceVersion) {
806 case CAMERA_DEVICE_API_VERSION_1_0:
807 ALOGE("Camera using old HAL version: %d", deviceVersion);
808 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
809 "Camera device \"%s\" HAL version %d no longer supported",
810 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800811 break;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700812 case CAMERA_DEVICE_API_VERSION_3_0:
813 case CAMERA_DEVICE_API_VERSION_3_1:
814 case CAMERA_DEVICE_API_VERSION_3_2:
815 case CAMERA_DEVICE_API_VERSION_3_3:
816 case CAMERA_DEVICE_API_VERSION_3_4:
817 case CAMERA_DEVICE_API_VERSION_3_5:
818 case CAMERA_DEVICE_API_VERSION_3_6:
Shuzhen Wang83bff122020-11-20 15:51:39 -0800819 case CAMERA_DEVICE_API_VERSION_3_7:
Ruben Brunkcc776712015-02-17 20:18:47 -0800820 if (effectiveApiLevel == API_1) { // Camera1 API route
821 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800822 *client = new Camera2Client(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800823 cameraId, api1CameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -0700824 facing, sensorOrientation, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700825 servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800826 } else { // Camera2 API route
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800827 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
828 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800829 *client = new CameraDeviceClient(cameraService, tmp, packageName, featureId,
Emilian Peev8b64f282021-03-25 16:49:57 -0700830 cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800831 }
832 break;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700833 default:
Ruben Brunkcc776712015-02-17 20:18:47 -0800834 // Should not be reachable
835 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800836 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800837 "Camera device \"%s\" has unknown HAL version %d",
838 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800839 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800840 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800841}
842
Ruben Brunk6267b532015-04-30 17:44:07 -0700843String8 CameraService::toString(std::set<userid_t> intSet) {
844 String8 s("");
845 bool first = true;
846 for (userid_t i : intSet) {
847 if (first) {
848 s.appendFormat("%d", i);
849 first = false;
850 } else {
851 s.appendFormat(", %d", i);
852 }
853 }
854 return s;
855}
856
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800857int32_t CameraService::mapToInterface(TorchModeStatus status) {
858 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
859 switch (status) {
860 case TorchModeStatus::NOT_AVAILABLE:
861 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
862 break;
863 case TorchModeStatus::AVAILABLE_OFF:
864 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
865 break;
866 case TorchModeStatus::AVAILABLE_ON:
867 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
868 break;
869 default:
870 ALOGW("Unknown new flash status: %d", status);
871 }
872 return serviceStatus;
873}
874
875CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
876 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
877 switch (status) {
878 case CameraDeviceStatus::NOT_PRESENT:
879 serviceStatus = StatusInternal::NOT_PRESENT;
880 break;
881 case CameraDeviceStatus::PRESENT:
882 serviceStatus = StatusInternal::PRESENT;
883 break;
884 case CameraDeviceStatus::ENUMERATING:
885 serviceStatus = StatusInternal::ENUMERATING;
886 break;
887 default:
888 ALOGW("Unknown new HAL device status: %d", status);
889 }
890 return serviceStatus;
891}
892
893int32_t CameraService::mapToInterface(StatusInternal status) {
894 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
895 switch (status) {
896 case StatusInternal::NOT_PRESENT:
897 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
898 break;
899 case StatusInternal::PRESENT:
900 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
901 break;
902 case StatusInternal::ENUMERATING:
903 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
904 break;
905 case StatusInternal::NOT_AVAILABLE:
906 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
907 break;
908 case StatusInternal::UNKNOWN:
909 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
910 break;
911 default:
912 ALOGW("Unknown new internal device status: %d", status);
913 }
914 return serviceStatus;
915}
916
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800917Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -0700918 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700919
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800920 String16 internalPackageName("cameraserver");
Ruben Brunkcc776712015-02-17 20:18:47 -0800921 String8 id = String8::format("%d", cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800922 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800923 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800924 if (!(ret = connectHelper<ICameraClient,Client>(
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800925 sp<ICameraClient>{nullptr}, id, cameraId,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +0900926 internalPackageName, {}, uid, USE_CALLING_PID,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700927 API_1, /*shimUpdateOnly*/ true, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800928 ).isOk()) {
929 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
Ruben Brunkb2119af2014-05-09 19:57:56 -0700930 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800931 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700932}
933
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800934Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -0700935 /*out*/
936 CameraParameters* parameters) {
937
938 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
939
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800940 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -0700941
942 if (parameters == NULL) {
943 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800944 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -0700945 }
946
Ruben Brunkcc776712015-02-17 20:18:47 -0800947 String8 id = String8::format("%d", cameraId);
948
949 // Check if we already have parameters
950 {
951 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -0700952 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -0800953 auto cameraState = getCameraState(id);
954 if (cameraState == nullptr) {
955 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800956 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
957 "Invalid camera ID: %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -0800958 }
959 CameraParameters p = cameraState->getShimParams();
960 if (!p.isEmpty()) {
961 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800962 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700963 }
964 }
965
Jayant Chowdhary12361932018-08-27 14:46:13 -0700966 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -0800967 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -0700968 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800969 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800970 // Error already logged by callee
971 return ret;
972 }
973
974 // Check for parameters again
975 {
976 // Scope for service lock
977 Mutex::Autolock lock(mServiceLock);
978 auto cameraState = getCameraState(id);
979 if (cameraState == nullptr) {
980 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800981 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
982 "Invalid camera ID: %s", id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -0700983 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800984 CameraParameters p = cameraState->getShimParams();
985 if (!p.isEmpty()) {
986 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800987 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700988 }
989 }
990
Ruben Brunkcc776712015-02-17 20:18:47 -0800991 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
992 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800993 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -0700994}
995
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800996// Can camera service trust the caller based on the calling UID?
997static bool isTrustedCallingUid(uid_t uid) {
998 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -0700999 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001000 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001001 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001002 return true;
1003 default:
1004 return false;
1005 }
1006}
1007
Nicholas Sauera3620332019-04-03 14:05:17 -07001008static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1009 PermissionController pc;
1010 uid = pc.getPackageUid(packageName, 0);
1011 if (uid <= 0) {
1012 ALOGE("Unknown package: '%s'", String8(packageName).string());
1013 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
1014 return BAD_VALUE;
1015 }
1016
1017 if (userId < 0) {
1018 ALOGE("Invalid user: %d", userId);
1019 dprintf(err, "Invalid user: %d\n", userId);
1020 return BAD_VALUE;
1021 }
1022
1023 uid = multiuser_get_uid(userId, uid);
1024 return NO_ERROR;
1025}
1026
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001027Status CameraService::validateConnectLocked(const String8& cameraId,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001028 const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
1029 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001030
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001031#ifdef __BRILLO__
1032 UNUSED(clientName8);
1033 UNUSED(clientUid);
1034 UNUSED(clientPid);
1035 UNUSED(originalClientPid);
1036#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001037 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1038 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001039 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001040 return allowed;
1041 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001042#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001043
Jayant Chowdhary12361932018-08-27 14:46:13 -07001044 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001045
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001046 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001047 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1048 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001049 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1050 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001051 }
1052
Ruben Brunkcc776712015-02-17 20:18:47 -08001053 if (getCameraState(cameraId) == nullptr) {
1054 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1055 cameraId.string());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001056 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1057 "No camera device with ID \"%s\" available", cameraId.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001058 }
1059
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001060 status_t err = checkIfDeviceIsUsable(cameraId);
1061 if (err != NO_ERROR) {
1062 switch(err) {
1063 case -ENODEV:
1064 case -EBUSY:
1065 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1066 "No camera device with ID \"%s\" currently available", cameraId.string());
1067 default:
1068 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1069 "Unknown error connecting to ID \"%s\"", cameraId.string());
1070 }
1071 }
1072 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001073}
1074
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001075Status CameraService::validateClientPermissionsLocked(const String8& cameraId,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001076 const String8& clientName8, int& clientUid, int& clientPid,
1077 /*out*/int& originalClientPid) const {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001078 int callingPid = CameraThreadState::getCallingPid();
1079 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001080
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001081 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001082 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001083 clientUid = callingUid;
1084 } else if (!isTrustedCallingUid(callingUid)) {
1085 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1086 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001087 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1088 "Untrusted caller (calling PID %d, UID %d) trying to "
1089 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1090 callingPid, callingUid, cameraId.string(),
1091 clientName8.string(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001092 }
1093
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001094 // Check if we can trust clientPid
1095 if (clientPid == USE_CALLING_PID) {
1096 clientPid = callingPid;
1097 } else if (!isTrustedCallingUid(callingUid)) {
1098 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1099 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001100 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1101 "Untrusted caller (calling PID %d, UID %d) trying to "
1102 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1103 callingPid, callingUid, cameraId.string(),
1104 clientName8.string(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001105 }
1106
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001107 if (shouldRejectSystemCameraConnection(cameraId)) {
1108 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1109 cameraId.c_str());
1110 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
1111 "available", cameraId.string());
1112 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001113 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1114 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1115 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
1116 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
1117 "found while trying to query device kind", cameraId.string());
1118
1119 }
1120
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001121 // If it's not calling from cameraserver, check the permission if the
1122 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1123 // android.permission.SYSTEM_CAMERA for system only camera devices).
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001124 if (callingPid != getpid() &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001125 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001126 !checkPermission(sCameraPermission, clientPid, clientUid)) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001127 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001128 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1129 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
1130 clientName8.string(), clientUid, clientPid, cameraId.string());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001131 }
1132
Svet Ganova453d0d2018-01-11 15:37:58 -08001133 // Make sure the UID is in an active state to use the camera
Svet Ganov7b4ab782018-03-25 12:48:10 -07001134 if (!mUidPolicy->isUidActive(callingUid, String16(clientName8))) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001135 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001136 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1137 clientPid, clientUid);
1138 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001139 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1140 "calling UID %d proc state %" PRId32 ")",
1141 clientName8.string(), clientUid, clientPid, cameraId.string(),
1142 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001143 }
1144
Michael Grooverd1d435a2018-12-18 17:39:42 -08001145 // If sensor privacy is enabled then prevent access to the camera
1146 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1147 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1148 return STATUS_ERROR_FMT(ERROR_DISABLED,
1149 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
1150 "is enabled", clientName8.string(), clientUid, clientPid, cameraId.string());
1151 }
1152
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001153 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1154 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001155 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001156 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001157
Ruben Brunk6267b532015-04-30 17:44:07 -07001158 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001159
Ruben Brunka8ca9152015-04-07 14:23:40 -07001160 // Only allow clients who are being used by the current foreground device user, unless calling
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001161 // from our own process OR the caller is using the cameraserver's HIDL interface.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001162 if (getCurrentServingCall() != BinderCallType::HWBINDER && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001163 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001164 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1165 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
1166 toString(mAllowedUsers).string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001167 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1168 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
1169 clientUserId, cameraId.string());
Ruben Brunk36597b22015-03-20 22:15:57 -07001170 }
1171
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001172 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001173}
1174
1175status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
1176 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001177 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001178 if (cameraState == nullptr) {
1179 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1180 cameraId.string());
1181 return -ENODEV;
1182 }
1183
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001184 StatusInternal currentStatus = cameraState->getStatus();
1185 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001186 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
1187 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001188 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001189 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001190 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
1191 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001192 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001193 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001194
Ruben Brunkcc776712015-02-17 20:18:47 -08001195 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001196}
1197
Ruben Brunkcc776712015-02-17 20:18:47 -08001198void CameraService::finishConnectLocked(const sp<BasicClient>& client,
1199 const CameraService::DescriptorPtr& desc) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001200
Ruben Brunkcc776712015-02-17 20:18:47 -08001201 // Make a descriptor for the incoming client
1202 auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
1203 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1204
1205 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
1206 String8(client->getPackageName()));
1207
1208 if (evicted.size() > 0) {
1209 // This should never happen - clients should already have been removed in disconnect
1210 for (auto& i : evicted) {
1211 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
1212 __FUNCTION__, i->getKey().string());
1213 }
1214
1215 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1216 __FUNCTION__);
1217 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001218
1219 // And register a death notification for the client callback. Do
1220 // this last to avoid Binder policy where a nested Binder
1221 // transaction might be pre-empted to service the client death
1222 // notification if the client process dies before linkToDeath is
1223 // invoked.
1224 sp<IBinder> remoteCallback = client->getRemote();
1225 if (remoteCallback != nullptr) {
1226 remoteCallback->linkToDeath(this);
1227 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001228}
1229
1230status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
1231 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
1232 /*out*/
1233 sp<BasicClient>* client,
1234 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001235 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001236 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001237 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001238 DescriptorPtr clientDescriptor;
1239 {
1240 if (effectiveApiLevel == API_1) {
1241 // If we are using API1, any existing client for this camera ID with the same remote
1242 // should be returned rather than evicted to allow MediaRecorder to work properly.
1243
1244 auto current = mActiveClientManager.get(cameraId);
1245 if (current != nullptr) {
1246 auto clientSp = current->getValue();
1247 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001248 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
1249 ALOGW("CameraService connect called from same client, but with a different"
1250 " API level, evicting prior client...");
1251 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001252 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001253 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001254 *client = clientSp;
1255 return NO_ERROR;
1256 }
1257 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001258 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001259 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001260
Ruben Brunkcc776712015-02-17 20:18:47 -08001261 // Get current active client PIDs
1262 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1263 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001264
Emilian Peev8131a262017-02-01 12:33:43 +00001265 std::vector<int> priorityScores(ownerPids.size());
1266 std::vector<int> states(ownerPids.size());
Igor Murashkine6800ce2013-03-04 17:25:57 -08001267
Emilian Peev8131a262017-02-01 12:33:43 +00001268 // Get priority scores of all active PIDs
1269 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1270 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1271 /*out*/&priorityScores[0]);
1272 if (err != OK) {
1273 ALOGE("%s: Priority score query failed: %d",
1274 __FUNCTION__, err);
1275 return err;
1276 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001277
Ruben Brunkcc776712015-02-17 20:18:47 -08001278 // Update all active clients' priorities
Emilian Peev8131a262017-02-01 12:33:43 +00001279 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
Ruben Brunkcc776712015-02-17 20:18:47 -08001280 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
Emilian Peev8131a262017-02-01 12:33:43 +00001281 pidToPriorityMap.emplace(ownerPids[i],
Jayant Chowdharyc578a502019-05-08 10:57:54 -07001282 resource_policy::ClientPriority(priorityScores[i], states[i],
1283 /* isVendorClient won't get copied over*/ false));
Ruben Brunkcc776712015-02-17 20:18:47 -08001284 }
1285 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001286
Ruben Brunkcc776712015-02-17 20:18:47 -08001287 // Get state for the given cameraId
1288 auto state = getCameraState(cameraId);
1289 if (state == nullptr) {
1290 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1291 clientPid, cameraId.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001292 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001293 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001294 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001295
1296 // Make descriptor for incoming client
Shuzhen Wang2db86ff2018-04-25 01:11:17 +00001297 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001298 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1299 state->getConflicting(),
Emilian Peev8131a262017-02-01 12:33:43 +00001300 priorityScores[priorityScores.size() - 1],
1301 clientPid,
1302 states[states.size() - 1]);
Ruben Brunkcc776712015-02-17 20:18:47 -08001303
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001304 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1305
Ruben Brunkcc776712015-02-17 20:18:47 -08001306 // Find clients that would be evicted
1307 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1308
1309 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1310 // background, so we cannot do evictions
1311 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1312 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1313 " priority).", clientPid);
1314
1315 sp<BasicClient> clientSp = clientDescriptor->getValue();
1316 String8 curTime = getFormattedCurrentTime();
1317 auto incompatibleClients =
1318 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1319
1320 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Emilian Peev8131a262017-02-01 12:33:43 +00001321 "(PID %d, score %d state %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001322 cameraId.string(), packageName.string(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001323 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001324
1325 for (auto& i : incompatibleClients) {
1326 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001327 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
1328 i->getKey().string(),
1329 String8{i->getValue()->getPackageName()}.string(),
1330 i->getOwnerId(), i->getPriority().getScore(),
1331 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001332 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00001333 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(),
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001334 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001335 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001336 }
1337
1338 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001339 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001340 mEventLog.add(msg);
1341
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001342 auto current = mActiveClientManager.get(cameraId);
1343 if (current != nullptr) {
1344 return -EBUSY; // CAMERA_IN_USE
1345 } else {
1346 return -EUSERS; // MAX_CAMERAS_IN_USE
1347 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001348 }
1349
1350 for (auto& i : evicted) {
1351 sp<BasicClient> clientSp = i->getValue();
1352 if (clientSp.get() == nullptr) {
1353 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1354
1355 // TODO: Remove this
1356 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1357 __FUNCTION__);
1358 mActiveClientManager.remove(i);
1359 continue;
1360 }
1361
1362 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1363 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001364 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001365
Ruben Brunkcc776712015-02-17 20:18:47 -08001366 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001367 logEvent(String8::format("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00001368 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1369 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001370 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
Emilian Peev8131a262017-02-01 12:33:43 +00001371 i->getOwnerId(), i->getPriority().getScore(),
1372 i->getPriority().getState(), cameraId.string(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001373 packageName.string(), clientPid, clientPriority.getScore(),
1374 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08001375
1376 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001377 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001378 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001379 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001380 }
1381
Ruben Brunkcc776712015-02-17 20:18:47 -08001382 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1383 // other clients from connecting in mServiceLockWrapper if held
1384 mServiceLock.unlock();
1385
1386 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07001387 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001388
1389 // Destroy evicted clients
1390 for (auto& i : evictedClients) {
1391 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001392 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001393 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001394
Jayant Chowdhary12361932018-08-27 14:46:13 -07001395 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08001396
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001397 for (const auto& i : evictedClients) {
1398 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1399 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1400 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1401 if (ret == TIMED_OUT) {
1402 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1403 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1404 mActiveClientManager.toString().string());
1405 return -EBUSY;
1406 }
1407 if (ret != NO_ERROR) {
1408 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1409 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1410 ret, mActiveClientManager.toString().string());
1411 return ret;
1412 }
1413 }
1414
1415 evictedClients.clear();
1416
Ruben Brunkcc776712015-02-17 20:18:47 -08001417 // Once clients have been disconnected, relock
1418 mServiceLock.lock();
1419
1420 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1421 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1422 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001423 }
1424
Ruben Brunkcc776712015-02-17 20:18:47 -08001425 *partial = clientDescriptor;
1426 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001427}
1428
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001429Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001430 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001431 int api1CameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001432 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001433 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001434 int clientPid,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001435 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001436 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001437
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001438 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001439 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001440
1441 String8 id = cameraIdIntToStr(api1CameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001442 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001443 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001444 clientPackageName, {}, clientUid, clientPid, API_1,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001445 /*shimUpdateOnly*/ false, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001446
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001447 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001448 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001449 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001450 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001451 }
1452
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001453 *device = client;
1454 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001455}
1456
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001457bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
1458 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001459 // If the client is not a vendor client, don't add listener if
1460 // a) the camera is a publicly hidden secure camera OR
1461 // b) the camera is a system only camera and the client doesn't
1462 // have android.permission.SYSTEM_CAMERA permissions.
1463 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
1464 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1465 !hasPermissionsForSystemCamera(clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001466 return true;
1467 }
1468 return false;
1469}
1470
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001471bool CameraService::shouldRejectSystemCameraConnection(const String8& cameraId) const {
1472 // Rules for rejection:
1473 // 1) If cameraserver tries to access this camera device, accept the
1474 // connection.
1475 // 2) The camera device is a publicly hidden secure camera device AND some
1476 // component is trying to access it on a non-hwbinder thread (generally a non HAL client),
1477 // reject it.
1478 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
1479 // and the serving thread is a non hwbinder thread, the client must have
1480 // android.permission.SYSTEM_CAMERA permissions to connect.
1481
1482 int cPid = CameraThreadState::getCallingPid();
1483 int cUid = CameraThreadState::getCallingUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001484 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
1485 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001486 // This isn't a known camera ID, so it's not a system camera
1487 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
1488 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001489 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001490
1491 // (1) Cameraserver trying to connect, accept.
1492 if (CameraThreadState::getCallingPid() == getpid()) {
1493 return false;
1494 }
1495 // (2)
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001496 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001497 systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
1498 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
1499 return true;
1500 }
1501 // (3) Here we only check for permissions if it is a system only camera device. This is since
1502 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
1503 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
1504 // same behavior for system camera devices.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001505 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001506 systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1507 !hasPermissionsForSystemCamera(cPid, cUid)) {
1508 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
1509 cameraId.c_str());
1510 return true;
1511 }
1512
1513 return false;
1514}
1515
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001516Status CameraService::connectDevice(
1517 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001518 const String16& cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001519 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001520 const std::optional<String16>& clientFeatureId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001521 int clientUid,
1522 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001523 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001524
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001525 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001526 Status ret = Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001527 String8 id = String8(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001528 sp<CameraDeviceClient> client = nullptr;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001529 String16 clientPackageNameAdj = clientPackageName;
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001530
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001531 if (getCurrentServingCall() == BinderCallType::HWBINDER) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001532 std::string vendorClient =
1533 StringPrintf("vendor.client.pid<%d>", CameraThreadState::getCallingPid());
1534 clientPackageNameAdj = String16(vendorClient.c_str());
1535 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001536 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001537 /*api1CameraId*/-1, clientPackageNameAdj, clientFeatureId,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001538 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08001539
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001540 if(!ret.isOk()) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001541 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageNameAdj),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001542 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001543 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001544 }
1545
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001546 *device = client;
1547 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001548}
1549
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001550template<class CALLBACK, class CLIENT>
1551Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001552 int api1CameraId, const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001553 const std::optional<String16>& clientFeatureId, int clientUid, int clientPid,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001554 apiLevel effectiveApiLevel, bool shimUpdateOnly,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001555 /*out*/sp<CLIENT>& device) {
1556 binder::Status ret = binder::Status::ok();
1557
1558 String8 clientName8(clientPackageName);
1559
1560 int originalClientPid = 0;
1561
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001562 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001563 "Camera API version %d", clientPid, clientName8.string(), cameraId.string(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001564 static_cast<int>(effectiveApiLevel));
1565
Shuzhen Wang316781a2020-08-18 18:11:01 -07001566 nsecs_t openTimeNs = systemTime();
1567
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001568 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001569 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07001570 int orientation = 0;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001571 bool isNdk = (clientPackageName.size() == 0);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001572 {
1573 // Acquire mServiceLock and prevent other clients from connecting
1574 std::unique_ptr<AutoConditionLock> lock =
1575 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1576
1577 if (lock == nullptr) {
1578 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
1579 , clientPid);
1580 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1581 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
1582 cameraId.string(), clientName8.string(), clientPid);
1583 }
1584
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07001585 // Enforce client permissions and do basic validity checks
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001586 if(!(ret = validateConnectLocked(cameraId, clientName8,
1587 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
1588 return ret;
1589 }
1590
1591 // Check the shim parameters after acquiring lock, if they have already been updated and
1592 // we were doing a shim update, return immediately
1593 if (shimUpdateOnly) {
1594 auto cameraState = getCameraState(cameraId);
1595 if (cameraState != nullptr) {
1596 if (!cameraState->getShimParams().isEmpty()) return ret;
1597 }
1598 }
1599
1600 status_t err;
1601
1602 sp<BasicClient> clientTmp = nullptr;
1603 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
1604 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
1605 IInterface::asBinder(cameraCb), clientName8, /*out*/&clientTmp,
1606 /*out*/&partial)) != NO_ERROR) {
1607 switch (err) {
1608 case -ENODEV:
1609 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1610 "No camera device with ID \"%s\" currently available",
1611 cameraId.string());
1612 case -EBUSY:
1613 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1614 "Higher-priority client using camera, ID \"%s\" currently unavailable",
1615 cameraId.string());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001616 case -EUSERS:
1617 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1618 "Too many cameras already open, cannot open camera \"%s\"",
1619 cameraId.string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001620 default:
1621 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1622 "Unexpected error %s (%d) opening camera \"%s\"",
1623 strerror(-err), err, cameraId.string());
1624 }
1625 }
1626
1627 if (clientTmp.get() != nullptr) {
1628 // Handle special case for API1 MediaRecorder where the existing client is returned
1629 device = static_cast<CLIENT*>(clientTmp.get());
1630 return ret;
1631 }
1632
1633 // give flashlight a chance to close devices if necessary.
1634 mFlashlight->prepareDeviceOpen(cameraId);
1635
Emilian Peevb91f1802021-03-23 14:50:28 -07001636 int deviceVersion = getDeviceVersion(cameraId, /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08001637 if (facing == -1) {
1638 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.string());
1639 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1640 "Unable to get camera device \"%s\" facing", cameraId.string());
1641 }
1642
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001643 sp<BasicClient> tmp = nullptr;
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001644 if(!(ret = makeClient(this, cameraCb, clientPackageName, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07001645 cameraId, api1CameraId, facing, orientation,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001646 clientPid, clientUid, getpid(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001647 deviceVersion, effectiveApiLevel,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001648 /*out*/&tmp)).isOk()) {
1649 return ret;
1650 }
1651 client = static_cast<CLIENT*>(tmp.get());
1652
1653 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
1654 __FUNCTION__);
1655
Emilian Peevbd8c5032018-02-14 23:05:40 +00001656 err = client->initialize(mCameraProviderManager, mMonitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001657 if (err != OK) {
1658 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001659 // Errors could be from the HAL module open call or from AppOpsManager
1660 switch(err) {
1661 case BAD_VALUE:
1662 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1663 "Illegal argument to HAL module for camera \"%s\"", cameraId.string());
1664 case -EBUSY:
1665 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1666 "Camera \"%s\" is already open", cameraId.string());
1667 case -EUSERS:
1668 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1669 "Too many cameras already open, cannot open camera \"%s\"",
1670 cameraId.string());
1671 case PERMISSION_DENIED:
1672 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1673 "No permission to open camera \"%s\"", cameraId.string());
1674 case -EACCES:
1675 return STATUS_ERROR_FMT(ERROR_DISABLED,
1676 "Camera \"%s\" disabled by policy", cameraId.string());
1677 case -ENODEV:
1678 default:
1679 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1680 "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
1681 strerror(-err), err);
1682 }
1683 }
1684
1685 // Update shim paremeters for legacy clients
1686 if (effectiveApiLevel == API_1) {
1687 // Assume we have always received a Client subclass for API1
1688 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
1689 String8 rawParams = shimClient->getParameters();
1690 CameraParameters params(rawParams);
1691
1692 auto cameraState = getCameraState(cameraId);
1693 if (cameraState != nullptr) {
1694 cameraState->setShimParams(params);
1695 } else {
1696 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
1697 __FUNCTION__, cameraId.string());
1698 }
1699 }
1700
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001701 // Set rotate-and-crop override behavior
1702 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
1703 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
Emilian Peevb91f1802021-03-23 14:50:28 -07001704 } else if (CameraServiceProxyWrapper::isRotateAndCropOverrideNeeded(clientPackageName,
1705 orientation, facing)) {
1706 client->setRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_90);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001707 }
1708
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08001709 // Set camera muting behavior
1710 if (client->supportsCameraMute()) {
Evan Severson09ab4002021-02-10 14:15:19 -08001711 bool isCameraPrivacyEnabled =
1712 mSensorPrivacyPolicy->isCameraPrivacyEnabled(multiuser_get_user_id(clientUid));
1713 client->setCameraMute(mOverrideCameraMuteMode || isCameraPrivacyEnabled);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08001714 }
1715
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001716 if (shimUpdateOnly) {
1717 // If only updating legacy shim parameters, immediately disconnect client
1718 mServiceLock.unlock();
1719 client->disconnect();
1720 mServiceLock.lock();
1721 } else {
1722 // Otherwise, add client to active clients list
1723 finishConnectLocked(client, partial);
1724 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001725
1726 client->setImageDumpMask(mImageDumpMask);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001727 } // lock is destroyed, allow further connect calls
1728
1729 // Important: release the mutex here so the client can call back into the service from its
1730 // destructor (can be at the end of the call)
1731 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001732
1733 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
1734 CameraServiceProxyWrapper::logOpen(cameraId, facing, clientPackageName,
1735 effectiveApiLevel, isNdk, openLatencyMs);
1736
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001737 return ret;
1738}
1739
Emilian Peevb2bc5a42019-11-20 16:02:14 -08001740status_t CameraService::addOfflineClient(String8 cameraId, sp<BasicClient> offlineClient) {
1741 if (offlineClient.get() == nullptr) {
1742 return BAD_VALUE;
1743 }
1744
1745 {
1746 // Acquire mServiceLock and prevent other clients from connecting
1747 std::unique_ptr<AutoConditionLock> lock =
1748 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1749
1750 if (lock == nullptr) {
1751 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
1752 , __FUNCTION__, offlineClient->getClientPid());
1753 return TIMED_OUT;
1754 }
1755
1756 auto onlineClientDesc = mActiveClientManager.get(cameraId);
1757 if (onlineClientDesc.get() == nullptr) {
1758 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
1759 cameraId.c_str());
1760 return BAD_VALUE;
1761 }
1762
1763 // Offline clients do not evict or conflict with other online devices. Resource sharing
1764 // conflicts are handled by the camera provider which will either succeed or fail before
1765 // reaching this method.
1766 const auto& onlinePriority = onlineClientDesc->getPriority();
1767 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
1768 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
1769 /*conflictingKeys*/ std::set<String8>(), onlinePriority.getScore(),
1770 onlineClientDesc->getOwnerId(), onlinePriority.getState());
1771
1772 // Allow only one offline device per camera
1773 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
1774 if (!incompatibleClients.empty()) {
1775 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
1776 return BAD_VALUE;
1777 }
1778
1779 auto err = offlineClient->initialize(mCameraProviderManager, mMonitorTags);
1780 if (err != OK) {
1781 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
1782 return err;
1783 }
1784
1785 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
1786 if (evicted.size() > 0) {
1787 for (auto& i : evicted) {
1788 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
1789 __FUNCTION__, i->getKey().string());
1790 }
1791
1792 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
1793 "properly", __FUNCTION__);
1794
1795 return BAD_VALUE;
1796 }
1797
1798 logConnectedOffline(offlineClientDesc->getKey(),
1799 static_cast<int>(offlineClientDesc->getOwnerId()),
1800 String8(offlineClient->getPackageName()));
1801
1802 sp<IBinder> remoteCallback = offlineClient->getRemote();
1803 if (remoteCallback != nullptr) {
1804 remoteCallback->linkToDeath(this);
1805 }
1806 } // lock is destroyed, allow further connect calls
1807
1808 return OK;
1809}
1810
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001811Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001812 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001813 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001814
1815 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07001816 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001817 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001818 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1819 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001820 }
1821
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001822 String8 id = String8(cameraId.string());
Jayant Chowdhary12361932018-08-27 14:46:13 -07001823 int uid = CameraThreadState::getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001824
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07001825 if (shouldRejectSystemCameraConnection(id)) {
1826 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
1827 " for system only device %s: ", id.string());
1828 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001829 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08001830 auto state = getCameraState(id);
1831 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001832 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001833 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1834 "Camera ID \"%s\" is a not valid camera ID", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001835 }
1836
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001837 StatusInternal cameraStatus = state->getStatus();
1838 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001839 cameraStatus != StatusInternal::NOT_AVAILABLE) {
1840 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001841 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1842 "Camera ID \"%s\" is a not valid camera ID", id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001843 }
1844
1845 {
1846 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001847 TorchModeStatus status;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001848 status_t err = getTorchStatusLocked(id, &status);
1849 if (err != OK) {
1850 if (err == NAME_NOT_FOUND) {
1851 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1852 "Camera \"%s\" does not have a flash unit", id.string());
1853 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001854 ALOGE("%s: getting current torch status failed for camera %s",
1855 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001856 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1857 "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
1858 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001859 }
1860
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001861 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001862 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001863 ALOGE("%s: torch mode of camera %s is not available because "
1864 "camera is in use", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001865 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1866 "Torch for camera \"%s\" is not available due to an existing camera user",
1867 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001868 } else {
1869 ALOGE("%s: torch mode of camera %s is not available due to "
1870 "insufficient resources", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001871 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1872 "Torch for camera \"%s\" is not available due to insufficient resources",
1873 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001874 }
1875 }
1876 }
1877
Ruben Brunk99e69712015-05-26 17:25:07 -07001878 {
1879 // Update UID map - this is used in the torch status changed callbacks, so must be done
1880 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07001881 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -07001882 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
1883 mTorchUidMap[id].first = uid;
1884 mTorchUidMap[id].second = uid;
1885 } else {
1886 // Set the pending UID
1887 mTorchUidMap[id].first = uid;
1888 }
1889 }
1890
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001891 status_t err = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07001892
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001893 if (err != OK) {
1894 int32_t errorCode;
1895 String8 msg;
1896 switch (err) {
1897 case -ENOSYS:
1898 msg = String8::format("Camera \"%s\" has no flashlight",
1899 id.string());
1900 errorCode = ERROR_ILLEGAL_ARGUMENT;
1901 break;
1902 default:
1903 msg = String8::format(
1904 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
1905 id.string(), enabled, strerror(-err), err);
1906 errorCode = ERROR_INVALID_OPERATION;
1907 }
1908 ALOGE("%s: %s", __FUNCTION__, msg.string());
1909 return STATUS_ERROR(errorCode, msg.string());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001910 }
1911
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001912 {
1913 // update the link to client's death
1914 Mutex::Autolock al(mTorchClientMapMutex);
1915 ssize_t index = mTorchClientMap.indexOfKey(id);
1916 if (enabled) {
1917 if (index == NAME_NOT_FOUND) {
1918 mTorchClientMap.add(id, clientBinder);
1919 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07001920 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001921 mTorchClientMap.replaceValueAt(index, clientBinder);
1922 }
1923 clientBinder->linkToDeath(this);
1924 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07001925 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001926 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001927 }
1928
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07001929 int clientPid = CameraThreadState::getCallingPid();
1930 const char *id_cstr = id.c_str();
1931 const char *torchState = enabled ? "on" : "off";
1932 ALOGI("Torch for camera id %s turned %s for client PID %d", id_cstr, torchState, clientPid);
1933 logTorchEvent(id_cstr, torchState , clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001934 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001935}
1936
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001937Status CameraService::notifySystemEvent(int32_t eventId,
1938 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001939 const int pid = CameraThreadState::getCallingPid();
1940 const int selfPid = getpid();
1941
1942 // Permission checks
1943 if (pid != selfPid) {
1944 // Ensure we're being called by system_server, or similar process with
1945 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001946 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001947 const int uid = CameraThreadState::getCallingUid();
1948 ALOGE("Permission Denial: cannot send updates to camera service about system"
1949 " events from pid=%d, uid=%d", pid, uid);
1950 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09001951 "No permission to send updates to camera service about system events"
1952 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001953 }
1954 }
1955
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001956 ATRACE_CALL();
1957
Ruben Brunk36597b22015-03-20 22:15:57 -07001958 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001959 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001960 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07001961 // from a system server crash
1962 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08001963 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001964 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07001965 break;
1966 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001967 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07001968 default: {
1969 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
1970 eventId);
1971 break;
1972 }
1973 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001974 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07001975}
1976
Emilian Peev53722fa2019-02-22 17:47:20 -08001977void CameraService::notifyMonitoredUids() {
1978 Mutex::Autolock lock(mStatusListenerLock);
1979
1980 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001981 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Emilian Peev53722fa2019-02-22 17:47:20 -08001982 if (!ret.isOk()) {
1983 ALOGE("%s: Failed to trigger permission callback: %d", __FUNCTION__,
1984 ret.exceptionCode());
1985 }
1986 }
1987}
1988
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08001989Status CameraService::notifyDeviceStateChange(int64_t newState) {
1990 const int pid = CameraThreadState::getCallingPid();
1991 const int selfPid = getpid();
1992
1993 // Permission checks
1994 if (pid != selfPid) {
1995 // Ensure we're being called by system_server, or similar process with
1996 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001997 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08001998 const int uid = CameraThreadState::getCallingUid();
1999 ALOGE("Permission Denial: cannot send updates to camera service about device"
2000 " state changes from pid=%d, uid=%d", pid, uid);
2001 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2002 "No permission to send updates to camera service about device state"
2003 " changes from pid=%d, uid=%d", pid, uid);
2004 }
2005 }
2006
2007 ATRACE_CALL();
2008
2009 using hardware::camera::provider::V2_5::DeviceState;
2010 hardware::hidl_bitfield<DeviceState> newDeviceState{};
2011 if (newState & ICameraService::DEVICE_STATE_BACK_COVERED) {
2012 newDeviceState |= DeviceState::BACK_COVERED;
2013 }
2014 if (newState & ICameraService::DEVICE_STATE_FRONT_COVERED) {
2015 newDeviceState |= DeviceState::FRONT_COVERED;
2016 }
2017 if (newState & ICameraService::DEVICE_STATE_FOLDED) {
2018 newDeviceState |= DeviceState::FOLDED;
2019 }
2020 // Only map vendor bits directly
2021 uint64_t vendorBits = static_cast<uint64_t>(newState) & 0xFFFFFFFF00000000l;
2022 newDeviceState |= vendorBits;
2023
2024 ALOGV("%s: New device state 0x%" PRIx64, __FUNCTION__, newDeviceState);
2025 Mutex::Autolock l(mServiceLock);
2026 mCameraProviderManager->notifyDeviceStateChange(newDeviceState);
2027
2028 return Status::ok();
2029}
2030
Emilian Peev8b64f282021-03-25 16:49:57 -07002031Status CameraService::notifyDisplayConfigurationChange() {
2032 ATRACE_CALL();
2033 const int callingPid = CameraThreadState::getCallingPid();
2034 const int selfPid = getpid();
2035
2036 // Permission checks
2037 if (callingPid != selfPid) {
2038 // Ensure we're being called by system_server, or similar process with
2039 // permissions to notify the camera service about system events
2040 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
2041 const int uid = CameraThreadState::getCallingUid();
2042 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
2043 " changes from pid=%d, uid=%d", callingPid, uid);
2044 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2045 "No permission to send updates to camera service about orientation"
2046 " changes from pid=%d, uid=%d", callingPid, uid);
2047 }
2048 }
2049
2050 Mutex::Autolock lock(mServiceLock);
2051
2052 // Don't do anything if rotate-and-crop override via cmd is active
2053 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
2054
2055 const auto clients = mActiveClientManager.getAll();
2056 for (auto& current : clients) {
2057 if (current != nullptr) {
2058 const auto basicClient = current->getValue();
2059 if (basicClient.get() != nullptr) {
2060 if (CameraServiceProxyWrapper::isRotateAndCropOverrideNeeded(
2061 basicClient->getPackageName(), basicClient->getCameraOrientation(),
2062 basicClient->getCameraFacing())) {
2063 basicClient->setRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_90);
2064 } else {
2065 basicClient->setRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE);
2066 }
2067 }
2068 }
2069 }
2070
2071 return Status::ok();
2072}
2073
2074Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002075 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
2076 ATRACE_CALL();
2077 if (!concurrentCameraIds) {
2078 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
2079 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
2080 }
2081
2082 if (!mInitialized) {
2083 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2084 return STATUS_ERROR(ERROR_DISCONNECTED,
2085 "Camera subsystem is not available");
2086 }
2087 // First call into the provider and get the set of concurrent camera
2088 // combinations
2089 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07002090 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002091 for (auto &combination : concurrentCameraCombinations) {
2092 std::vector<std::string> validCombination;
2093 for (auto &cameraId : combination) {
2094 // if the camera state is not present, skip
2095 String8 cameraIdStr(cameraId.c_str());
2096 auto state = getCameraState(cameraIdStr);
2097 if (state == nullptr) {
2098 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
2099 continue;
2100 }
2101 StatusInternal status = state->getStatus();
2102 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
2103 continue;
2104 }
2105 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
2106 continue;
2107 }
2108 validCombination.push_back(cameraId);
2109 }
2110 if (validCombination.size() != 0) {
2111 concurrentCameraIds->push_back(std::move(validCombination));
2112 }
2113 }
2114 return Status::ok();
2115}
2116
2117Status CameraService::isConcurrentSessionConfigurationSupported(
2118 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
2119 /*out*/bool* isSupported) {
2120 if (!isSupported) {
2121 ALOGE("%s: isSupported is NULL", __FUNCTION__);
2122 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
2123 }
2124
2125 if (!mInitialized) {
2126 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2127 return STATUS_ERROR(ERROR_DISCONNECTED,
2128 "Camera subsystem is not available");
2129 }
2130
2131 // Check for camera permissions
2132 int callingPid = CameraThreadState::getCallingPid();
2133 int callingUid = CameraThreadState::getCallingUid();
2134 if ((callingPid != getpid()) && !checkPermission(sCameraPermission, callingPid, callingUid)) {
2135 ALOGE("%s: pid %d doesn't have camera permissions", __FUNCTION__, callingPid);
2136 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2137 "android.permission.CAMERA needed to call"
2138 "isConcurrentSessionConfigurationSupported");
2139 }
2140
2141 status_t res =
2142 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
2143 cameraIdsAndSessionConfigurations, isSupported);
2144 if (res != OK) {
2145 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
2146 "support %s (%d)", strerror(-res), res);
2147 }
2148 return Status::ok();
2149}
2150
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002151Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
2152 /*out*/
2153 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002154 return addListenerHelper(listener, cameraStatuses);
2155}
2156
2157Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
2158 /*out*/
2159 std::vector<hardware::CameraStatus> *cameraStatuses,
2160 bool isVendorListener) {
2161
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002162 ATRACE_CALL();
2163
Igor Murashkinbfc99152013-02-27 12:55:20 -08002164 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08002165
Ruben Brunk3450ba72015-06-16 11:00:37 -07002166 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002167 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002168 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002169 }
2170
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002171 auto clientUid = CameraThreadState::getCallingUid();
2172 auto clientPid = CameraThreadState::getCallingPid();
Shuzhen Wang695044d2020-03-06 09:02:23 -08002173 bool openCloseCallbackAllowed = checkPermission(sCameraOpenCloseListenerPermission,
2174 clientPid, clientUid);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002175
Igor Murashkinbfc99152013-02-27 12:55:20 -08002176 Mutex::Autolock lock(mServiceLock);
2177
Ruben Brunkcc776712015-02-17 20:18:47 -08002178 {
2179 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08002180 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002181 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002182 ALOGW("%s: Tried to add listener %p which was already subscribed",
2183 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002184 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08002185 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002186 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002187
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002188 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08002189 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
2190 openCloseCallbackAllowed);
Emilian Peev53722fa2019-02-22 17:47:20 -08002191 auto ret = serviceListener->initialize();
2192 if (ret != NO_ERROR) {
2193 String8 msg = String8::format("Failed to initialize service listener: %s (%d)",
2194 strerror(-ret), ret);
2195 ALOGE("%s: %s", __FUNCTION__, msg.string());
2196 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
2197 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002198 // The listener still needs to be added to the list of listeners, regardless of what
2199 // permissions the listener process has / whether it is a vendor listener. Since it might be
2200 // eligible to listen to other camera ids.
2201 mListenerList.emplace_back(serviceListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08002202 mUidPolicy->registerMonitorUid(clientUid);
Igor Murashkinbfc99152013-02-27 12:55:20 -08002203 }
2204
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002205 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07002206 {
Ruben Brunkcc776712015-02-17 20:18:47 -08002207 Mutex::Autolock lock(mCameraStatesLock);
2208 for (auto& i : mCameraStates) {
Shuzhen Wang43858162020-01-10 13:42:15 -08002209 cameraStatuses->emplace_back(i.first,
2210 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds());
Igor Murashkincba2c162013-03-20 15:56:31 -07002211 }
2212 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002213 // Remove the camera statuses that should be hidden from the client, we do
2214 // this after collecting the states in order to avoid holding
2215 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
2216 // the same time.
2217 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
2218 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
2219 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
2220 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
2221 ALOGE("%s: Invalid camera id %s, skipping status update",
2222 __FUNCTION__, s.cameraId.c_str());
2223 return true;
2224 }
2225 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
2226 clientUid);}), cameraStatuses->end());
2227
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002228 //cameraStatuses will have non-eligible camera ids removed.
2229 std::set<String16> idsChosenForCallback;
2230 for (const auto &s : *cameraStatuses) {
2231 idsChosenForCallback.insert(String16(s.cameraId));
2232 }
Igor Murashkincba2c162013-03-20 15:56:31 -07002233
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002234 /*
2235 * Immediately signal current torch status to this listener only
2236 * This may be a subset of all the devices, so don't include it in the response directly
2237 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002238 {
2239 Mutex::Autolock al(mTorchStatusMutex);
2240 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002241 String16 id = String16(mTorchStatusMap.keyAt(i).string());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002242 // The camera id is visible to the client. Fine to send torch
2243 // callback.
2244 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
2245 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
2246 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002247 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002248 }
2249
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002250 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08002251}
Ruben Brunkcc776712015-02-17 20:18:47 -08002252
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002253Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002254 ATRACE_CALL();
2255
Igor Murashkinbfc99152013-02-27 12:55:20 -08002256 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
2257
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002258 if (listener == 0) {
2259 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002260 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002261 }
2262
Igor Murashkinbfc99152013-02-27 12:55:20 -08002263 Mutex::Autolock lock(mServiceLock);
2264
Ruben Brunkcc776712015-02-17 20:18:47 -08002265 {
2266 Mutex::Autolock lock(mStatusListenerLock);
2267 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002268 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
2269 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid());
2270 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08002271 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002272 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002273 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002274 }
2275 }
2276
2277 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
2278 __FUNCTION__, listener.get());
2279
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002280 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08002281}
2282
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002283Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002284
2285 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002286 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
2287
2288 if (parameters == NULL) {
2289 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002290 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07002291 }
2292
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002293 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002294
2295 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002296 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07002297 // Error logged by caller
2298 return ret;
2299 }
2300
2301 String8 shimParamsString8 = shimParams.flatten();
2302 String16 shimParamsString16 = String16(shimParamsString8);
2303
2304 *parameters = shimParamsString16;
2305
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002306 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07002307}
2308
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002309Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
2310 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002311 ATRACE_CALL();
2312
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002313 const String8 id = String8(cameraId);
2314
2315 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002316
2317 switch (apiVersion) {
2318 case API_VERSION_1:
2319 case API_VERSION_2:
2320 break;
2321 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002322 String8 msg = String8::format("Unknown API version %d", apiVersion);
2323 ALOGE("%s: %s", __FUNCTION__, msg.string());
2324 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002325 }
2326
Emilian Peev28ad2ea2017-02-07 16:14:32 +00002327 int deviceVersion = getDeviceVersion(id);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002328 switch (deviceVersion) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002329 case CAMERA_DEVICE_API_VERSION_1_0:
2330 case CAMERA_DEVICE_API_VERSION_3_0:
2331 case CAMERA_DEVICE_API_VERSION_3_1:
2332 if (apiVersion == API_VERSION_2) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002333 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without shim",
2334 __FUNCTION__, id.string(), deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002335 *isSupported = false;
2336 } else { // if (apiVersion == API_VERSION_1) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002337 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always supported",
2338 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002339 *isSupported = true;
2340 }
2341 break;
2342 case CAMERA_DEVICE_API_VERSION_3_2:
2343 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -07002344 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002345 case CAMERA_DEVICE_API_VERSION_3_5:
Yin-Chia Yeh56d98ba2020-01-16 16:57:14 -08002346 case CAMERA_DEVICE_API_VERSION_3_6:
Shuzhen Wang83bff122020-11-20 15:51:39 -08002347 case CAMERA_DEVICE_API_VERSION_3_7:
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002348 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
2349 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002350 *isSupported = true;
2351 break;
2352 case -1: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002353 String8 msg = String8::format("Unknown camera ID %s", id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002354 ALOGE("%s: %s", __FUNCTION__, msg.string());
2355 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002356 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002357 default: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002358 String8 msg = String8::format("Unknown device version %x for device %s",
2359 deviceVersion, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002360 ALOGE("%s: %s", __FUNCTION__, msg.string());
2361 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
2362 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07002363 }
2364
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002365 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002366}
2367
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002368Status CameraService::isHiddenPhysicalCamera(const String16& cameraId,
2369 /*out*/ bool *isSupported) {
2370 ATRACE_CALL();
2371
2372 const String8 id = String8(cameraId);
2373
2374 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
2375 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(id.string());
2376
2377 return Status::ok();
2378}
2379
Ruben Brunkcc776712015-02-17 20:18:47 -08002380void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002381 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002382 for (auto& i : mActiveClientManager.getAll()) {
2383 auto clientSp = i->getValue();
2384 if (clientSp.get() == client) {
2385 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08002386 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07002387 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002388 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08002389}
2390
Ruben Brunkcc776712015-02-17 20:18:47 -08002391bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002392 bool ret = false;
2393 {
2394 // Acquire mServiceLock and prevent other clients from connecting
2395 std::unique_ptr<AutoConditionLock> lock =
2396 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08002397
Igor Murashkin634a5152013-02-20 17:15:11 -08002398
Ruben Brunkcc776712015-02-17 20:18:47 -08002399 std::vector<sp<BasicClient>> evicted;
2400 for (auto& i : mActiveClientManager.getAll()) {
2401 auto clientSp = i->getValue();
2402 if (clientSp.get() == nullptr) {
2403 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2404 mActiveClientManager.remove(i);
2405 continue;
2406 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08002407 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002408 mActiveClientManager.remove(i);
2409 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08002410
Ruben Brunkcc776712015-02-17 20:18:47 -08002411 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002412 clientSp->notifyError(
2413 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002414 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08002415 }
2416 }
2417
Ruben Brunkcc776712015-02-17 20:18:47 -08002418 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2419 // other clients from connecting in mServiceLockWrapper if held
2420 mServiceLock.unlock();
2421
Ruben Brunk36597b22015-03-20 22:15:57 -07002422 // Do not clear caller identity, remote caller should be client proccess
2423
Ruben Brunkcc776712015-02-17 20:18:47 -08002424 for (auto& i : evicted) {
2425 if (i.get() != nullptr) {
2426 i->disconnect();
2427 ret = true;
2428 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002429 }
2430
Ruben Brunkcc776712015-02-17 20:18:47 -08002431 // Reacquire mServiceLock
2432 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08002433
Ruben Brunkcc776712015-02-17 20:18:47 -08002434 } // lock is destroyed, allow further connect calls
2435
2436 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07002437}
2438
Ruben Brunkcc776712015-02-17 20:18:47 -08002439std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
2440 const String8& cameraId) const {
2441 std::shared_ptr<CameraState> state;
2442 {
2443 Mutex::Autolock lock(mCameraStatesLock);
2444 auto iter = mCameraStates.find(cameraId);
2445 if (iter != mCameraStates.end()) {
2446 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002447 }
2448 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002449 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002450}
2451
Ruben Brunkcc776712015-02-17 20:18:47 -08002452sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
2453 // Remove from active clients list
2454 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
2455 if (clientDescriptorPtr == nullptr) {
2456 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
2457 cameraId.string());
2458 return sp<BasicClient>{nullptr};
2459 }
2460
2461 return clientDescriptorPtr->getValue();
Keun young Parkd8973a72012-03-28 14:13:09 -07002462}
2463
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002464void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07002465 // Acquire mServiceLock and prevent other clients from connecting
2466 std::unique_ptr<AutoConditionLock> lock =
2467 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
2468
Ruben Brunk6267b532015-04-30 17:44:07 -07002469 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002470 for (size_t i = 0; i < newUserIds.size(); i++) {
2471 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07002472 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002473 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07002474 return;
2475 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002476 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07002477 }
2478
Ruben Brunka8ca9152015-04-07 14:23:40 -07002479
Ruben Brunk6267b532015-04-30 17:44:07 -07002480 if (newAllowedUsers == mAllowedUsers) {
2481 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
2482 return;
2483 }
2484
2485 logUserSwitch(mAllowedUsers, newAllowedUsers);
2486
2487 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07002488
2489 // Current user has switched, evict all current clients.
2490 std::vector<sp<BasicClient>> evicted;
2491 for (auto& i : mActiveClientManager.getAll()) {
2492 auto clientSp = i->getValue();
2493
2494 if (clientSp.get() == nullptr) {
2495 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2496 continue;
2497 }
2498
Ruben Brunk6267b532015-04-30 17:44:07 -07002499 // Don't evict clients that are still allowed.
2500 uid_t clientUid = clientSp->getClientUid();
2501 userid_t clientUserId = multiuser_get_user_id(clientUid);
2502 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
2503 continue;
2504 }
2505
Ruben Brunk36597b22015-03-20 22:15:57 -07002506 evicted.push_back(clientSp);
2507
2508 String8 curTime = getFormattedCurrentTime();
2509
2510 ALOGE("Evicting conflicting client for camera ID %s due to user change",
2511 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07002512
Ruben Brunk36597b22015-03-20 22:15:57 -07002513 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002514 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00002515 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
2516 " to user switch.", i->getKey().string(),
2517 String8{clientSp->getPackageName()}.string(),
2518 i->getOwnerId(), i->getPriority().getScore(),
2519 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07002520
2521 }
2522
2523 // Do not hold mServiceLock while disconnecting clients, but retain the condition
2524 // blocking other clients from connecting in mServiceLockWrapper if held.
2525 mServiceLock.unlock();
2526
2527 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07002528 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07002529
2530 for (auto& i : evicted) {
2531 i->disconnect();
2532 }
2533
Jayant Chowdhary12361932018-08-27 14:46:13 -07002534 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07002535
2536 // Reacquire mServiceLock
2537 mServiceLock.lock();
2538}
Ruben Brunkcc776712015-02-17 20:18:47 -08002539
Ruben Brunka8ca9152015-04-07 14:23:40 -07002540void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002541 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07002542 Mutex::Autolock l(mLogLock);
2543 mEventLog.add(String8::format("%s : %s", curTime.string(), event));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002544}
2545
Ruben Brunka8ca9152015-04-07 14:23:40 -07002546void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002547 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002548 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002549 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002550 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002551}
2552
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002553void CameraService::logDisconnectedOffline(const char* cameraId, int clientPid,
2554 const char* clientPackage) {
2555 // Log the clients evicted
2556 logEvent(String8::format("DISCONNECT offline device %s client for package %s (PID %d)",
2557 cameraId, clientPackage, clientPid));
2558}
2559
Ruben Brunka8ca9152015-04-07 14:23:40 -07002560void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002561 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002562 // Log the clients evicted
2563 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002564 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002565}
2566
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002567void CameraService::logConnectedOffline(const char* cameraId, int clientPid,
2568 const char* clientPackage) {
2569 // Log the clients evicted
2570 logEvent(String8::format("CONNECT offline device %s client for package %s (PID %d)", cameraId,
2571 clientPackage, clientPid));
2572}
2573
Ruben Brunka8ca9152015-04-07 14:23:40 -07002574void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002575 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002576 // Log the client rejected
2577 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002578 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002579}
2580
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002581void CameraService::logTorchEvent(const char* cameraId, const char *torchState, int clientPid) {
2582 // Log torch event
2583 logEvent(String8::format("Torch for camera id %s turned %s for client PID %d", cameraId,
2584 torchState, clientPid));
2585}
2586
Ruben Brunk6267b532015-04-30 17:44:07 -07002587void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
2588 const std::set<userid_t>& newUserIds) {
2589 String8 newUsers = toString(newUserIds);
2590 String8 oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002591 if (oldUsers.size() == 0) {
2592 oldUsers = "<None>";
2593 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07002594 // Log the new and old users
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002595 logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
Ruben Brunk6267b532015-04-30 17:44:07 -07002596 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002597}
2598
2599void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
2600 // Log the device removal
2601 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
2602}
2603
2604void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
2605 // Log the device removal
2606 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
2607}
2608
2609void CameraService::logClientDied(int clientPid, const char* reason) {
2610 // Log the device removal
2611 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07002612}
2613
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002614void CameraService::logServiceError(const char* msg, int errorCode) {
2615 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002616 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002617}
2618
Ruben Brunk36597b22015-03-20 22:15:57 -07002619status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
2620 uint32_t flags) {
2621
Mathias Agopian65ab4712010-07-14 17:59:35 -07002622 // Permission checks
2623 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002624 case SHELL_COMMAND_TRANSACTION: {
2625 int in = data.readFileDescriptor();
2626 int out = data.readFileDescriptor();
2627 int err = data.readFileDescriptor();
2628 int argc = data.readInt32();
2629 Vector<String16> args;
2630 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
2631 args.add(data.readString16());
2632 }
2633 sp<IBinder> unusedCallback;
2634 sp<IResultReceiver> resultReceiver;
2635 status_t status;
2636 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
2637 return status;
2638 }
2639 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
2640 return status;
2641 }
2642 status = shellCommand(in, out, err, args);
2643 if (resultReceiver != nullptr) {
2644 resultReceiver->send(status);
2645 }
2646 return NO_ERROR;
2647 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002648 }
2649
2650 return BnCameraService::onTransact(code, data, reply, flags);
2651}
2652
Mathias Agopian65ab4712010-07-14 17:59:35 -07002653// We share the media players for shutter and recording sound for all clients.
2654// A reference count is kept to determine when we will actually release the
2655// media players.
2656
Jaekyun Seokef498052018-03-23 13:09:44 +09002657sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
2658 sp<MediaPlayer> mp = new MediaPlayer();
2659 status_t error;
2660 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08002661 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09002662 error = mp->prepare();
2663 }
2664 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00002665 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09002666 mp->disconnect();
2667 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002668 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002669 }
2670 return mp;
2671}
2672
username5755fea2018-12-27 09:48:08 +08002673void CameraService::increaseSoundRef() {
2674 Mutex::Autolock lock(mSoundLock);
2675 mSoundRef++;
2676}
2677
2678void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002679 ATRACE_CALL();
2680
username5755fea2018-12-27 09:48:08 +08002681 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
2682 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
2683 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
2684 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
2685 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
2686 }
2687 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
2688 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
2689 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
2690 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002691 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08002692 }
2693 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
2694 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
2695 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
2696 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
2697 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002698 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002699}
2700
username5755fea2018-12-27 09:48:08 +08002701void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002702 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002703 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002704 if (--mSoundRef) return;
2705
2706 for (int i = 0; i < NUM_SOUNDS; i++) {
2707 if (mSoundPlayer[i] != 0) {
2708 mSoundPlayer[i]->disconnect();
2709 mSoundPlayer[i].clear();
2710 }
2711 }
2712}
2713
2714void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002715 ATRACE_CALL();
2716
Mathias Agopian65ab4712010-07-14 17:59:35 -07002717 LOG1("playSound(%d)", kind);
2718 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002719 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002720 sp<MediaPlayer> player = mSoundPlayer[kind];
2721 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08002722 player->seekTo(0);
2723 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002724 }
2725}
2726
2727// ----------------------------------------------------------------------------
2728
2729CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07002730 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002731 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09002732 const std::optional<String16>& clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002733 const String8& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07002734 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002735 int clientPid, uid_t clientUid,
2736 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002737 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08002738 IInterface::asBinder(cameraClient),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002739 clientPackageName, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07002740 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002741 clientPid, clientUid,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002742 servicePid),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002743 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08002744{
Jayant Chowdhary12361932018-08-27 14:46:13 -07002745 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002746 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002747
Igor Murashkin44cfcf02013-03-01 16:22:28 -08002748 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002749
username5755fea2018-12-27 09:48:08 +08002750 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002751
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002752 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002753}
2754
Mathias Agopian65ab4712010-07-14 17:59:35 -07002755// tear down the client
2756CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002757 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08002758 mDestructionStarted = true;
2759
username5755fea2018-12-27 09:48:08 +08002760 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002761 // unconditionally disconnect. function is idempotent
2762 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002763}
2764
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002765sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
2766
Igor Murashkin634a5152013-02-20 17:15:11 -08002767CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002768 const sp<IBinder>& remoteCallback,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09002769 const String16& clientPackageName, const std::optional<String16>& clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07002770 const String8& cameraIdStr, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002771 int clientPid, uid_t clientUid,
2772 int servicePid):
Emilian Peev8b64f282021-03-25 16:49:57 -07002773 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09002774 mClientPackageName(clientPackageName), mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002775 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002776 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07002777 mDisconnected(false), mUidIsTrusted(false),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002778 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002779 mRemoteBinder(remoteCallback)
Igor Murashkin634a5152013-02-20 17:15:11 -08002780{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002781 if (sCameraService == nullptr) {
2782 sCameraService = cameraService;
2783 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002784 mOpsActive = false;
Igor Murashkin634a5152013-02-20 17:15:11 -08002785 mDestructionStarted = false;
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08002786
2787 // In some cases the calling code has no access to the package it runs under.
2788 // For example, NDK camera API.
2789 // In this case we will get the packages for the calling UID and pick the first one
2790 // for attributing the app op. This will work correctly for runtime permissions
2791 // as for legacy apps we will toggle the app op for all packages in the UID.
2792 // The caveat is that the operation may be attributed to the wrong package and
2793 // stats based on app ops may be slightly off.
2794 if (mClientPackageName.size() <= 0) {
2795 sp<IServiceManager> sm = defaultServiceManager();
2796 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
2797 if (binder == 0) {
2798 ALOGE("Cannot get permission service");
2799 // Leave mClientPackageName unchanged (empty) and the further interaction
2800 // with camera will fail in BasicClient::startCameraOps
2801 return;
2802 }
2803
2804 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
2805 Vector<String16> packages;
2806
2807 permCtrl->getPackagesForUid(mClientUid, packages);
2808
2809 if (packages.isEmpty()) {
2810 ALOGE("No packages for calling UID");
2811 // Leave mClientPackageName unchanged (empty) and the further interaction
2812 // with camera will fail in BasicClient::startCameraOps
2813 return;
2814 }
2815 mClientPackageName = packages[0];
2816 }
Steven Moreland89a2c5c2020-01-31 15:02:25 -08002817 if (getCurrentServingCall() != BinderCallType::HWBINDER) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002818 mAppOpsManager = std::make_unique<AppOpsManager>();
2819 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07002820
2821 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08002822}
2823
2824CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002825 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08002826 mDestructionStarted = true;
2827}
2828
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002829binder::Status CameraService::BasicClient::disconnect() {
2830 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002831 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002832 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07002833 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07002834 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002835
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002836 sCameraService->removeByClient(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002837 sCameraService->logDisconnected(mCameraIdStr, mClientPid, String8(mClientPackageName));
Peter Kalauskasa29c1352018-10-10 12:05:42 -07002838 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
2839 mCameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002840
2841 sp<IBinder> remote = getRemote();
2842 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002843 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08002844 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002845
2846 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07002847 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002848 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
2849 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
2850 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002851
Igor Murashkincba2c162013-03-20 15:56:31 -07002852 // client shouldn't be able to call into us anymore
2853 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002854
2855 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08002856}
2857
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002858status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
2859 // No dumping of clients directly over Binder,
2860 // must go through CameraService::dump
2861 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07002862 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002863 return OK;
2864}
2865
Ruben Brunkcc776712015-02-17 20:18:47 -08002866String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002867 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08002868}
2869
Emilian Peev8b64f282021-03-25 16:49:57 -07002870int CameraService::BasicClient::getCameraFacing() const {
2871 return mCameraFacing;
2872}
2873
2874int CameraService::BasicClient::getCameraOrientation() const {
2875 return mOrientation;
2876}
Ruben Brunkcc776712015-02-17 20:18:47 -08002877
2878int CameraService::BasicClient::getClientPid() const {
2879 return mClientPid;
2880}
2881
Ruben Brunk6267b532015-04-30 17:44:07 -07002882uid_t CameraService::BasicClient::getClientUid() const {
2883 return mClientUid;
2884}
2885
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002886bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
2887 // Defaults to API2.
2888 return level == API_2;
2889}
2890
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002891status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002892 {
2893 Mutex::Autolock l(mAudioRestrictionLock);
2894 mAudioRestriction = mode;
2895 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002896 sCameraService->updateAudioRestriction();
2897 return OK;
2898}
2899
2900int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002901 return sCameraService->updateAudioRestriction();
2902}
2903
2904int32_t CameraService::BasicClient::getAudioRestriction() const {
2905 Mutex::Autolock l(mAudioRestrictionLock);
2906 return mAudioRestriction;
2907}
2908
2909bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
2910 switch (mode) {
2911 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
2912 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
2913 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
2914 return true;
2915 default:
2916 return false;
2917 }
2918}
2919
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002920status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002921 ATRACE_CALL();
2922
Igor Murashkine6800ce2013-03-04 17:25:57 -08002923 {
2924 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002925 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08002926 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002927 if (mAppOpsManager != nullptr) {
2928 // Notify app ops that the camera is not available
2929 mOpsCallback = new OpsCallback(this);
2930 int32_t res;
2931 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
2932 mClientPackageName, mOpsCallback);
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002933 res = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
2934 mClientPackageName, /*startIfModeDefault*/ false, mClientFeatureId,
2935 String16("start camera ") + String16(mCameraIdStr));
Igor Murashkine6800ce2013-03-04 17:25:57 -08002936
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002937 if (res == AppOpsManager::MODE_ERRORED) {
2938 ALOGI("Camera %s: Access for \"%s\" has been revoked",
2939 mCameraIdStr.string(), String8(mClientPackageName).string());
2940 return PERMISSION_DENIED;
2941 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002942
Shuzhen Wang2c656792020-04-13 17:36:49 -07002943 // If the calling Uid is trusted (a native service), the AppOpsManager could
2944 // return MODE_IGNORED. Do not treat such case as error.
2945 if (!mUidIsTrusted && res == AppOpsManager::MODE_IGNORED) {
Evan Severson09ab4002021-02-10 14:15:19 -08002946 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
2947 mClientPackageName);
2948 bool isCameraPrivacyEnabled =
2949 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled(
2950 multiuser_get_user_id(mClientUid));
2951 if (!isUidActive || !isCameraPrivacyEnabled) {
2952 ALOGI("Camera %s: Access for \"%s\" has been restricted",
2953 mCameraIdStr.string(), String8(mClientPackageName).string());
2954 // Return the same error as for device policy manager rejection
2955 return -EACCES;
2956 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002957 }
Svetoslav28e8ef72015-05-11 19:21:31 -07002958 }
2959
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002960 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002961
2962 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002963 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002964
Emilian Peev53722fa2019-02-22 17:47:20 -08002965 sCameraService->mUidPolicy->registerMonitorUid(mClientUid);
2966
Shuzhen Wang695044d2020-03-06 09:02:23 -08002967 // Notify listeners of camera open/close status
2968 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
2969
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002970 return OK;
2971}
2972
2973status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002974 ATRACE_CALL();
2975
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002976 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002977 if (mOpsActive) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002978 // Notify app ops that the camera is available again
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002979 if (mAppOpsManager != nullptr) {
2980 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002981 mClientPackageName, mClientFeatureId);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002982 mOpsActive = false;
2983 }
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002984 // This function is called when a client disconnects. This should
2985 // release the camera, but actually only if it was in a proper
2986 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002987 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002988 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002989
Ruben Brunkcc776712015-02-17 20:18:47 -08002990 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002991 sCameraService->updateStatus(StatusInternal::PRESENT,
2992 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002993 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002994 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002995 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
2996 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002997 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002998 mOpsCallback.clear();
2999
Emilian Peev53722fa2019-02-22 17:47:20 -08003000 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid);
3001
Shuzhen Wang695044d2020-03-06 09:02:23 -08003002 // Notify listeners of camera open/close status
3003 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
3004
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003005 return OK;
3006}
3007
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003008void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003009 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003010 if (mAppOpsManager == nullptr) {
3011 return;
3012 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003013 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003014 if (op != AppOpsManager::OP_CAMERA) {
3015 ALOGW("Unexpected app ops notification received: %d", op);
3016 return;
3017 }
3018
3019 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003020 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003021 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003022 ALOGV("checkOp returns: %d, %s ", res,
3023 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
3024 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
3025 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
3026 "UNKNOWN");
3027
Shuzhen Wang64900852021-02-05 09:03:29 -08003028 if (res == AppOpsManager::MODE_ERRORED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003029 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003030 String8(mClientPackageName).string());
Svet Ganova453d0d2018-01-11 15:37:58 -08003031 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08003032 } else if (res == AppOpsManager::MODE_IGNORED) {
3033 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Evan Severson09ab4002021-02-10 14:15:19 -08003034 bool isCameraPrivacyEnabled =
3035 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled(
3036 multiuser_get_user_id(mClientUid));
Shuzhen Wang64900852021-02-05 09:03:29 -08003037 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d",
3038 mCameraIdStr.string(), String8(mClientPackageName).string(),
3039 mUidIsTrusted, isUidActive);
3040 // If the calling Uid is trusted (a native service), or the client Uid is active (WAR for
3041 // b/175320666), the AppOpsManager could return MODE_IGNORED. Do not treat such cases as
3042 // error.
Evan Severson09ab4002021-02-10 14:15:19 -08003043 if (!mUidIsTrusted && isUidActive && isCameraPrivacyEnabled) {
3044 setCameraMute(true);
3045 } else if (!mUidIsTrusted && !isUidActive) {
Shuzhen Wang64900852021-02-05 09:03:29 -08003046 block();
3047 }
Evan Severson09ab4002021-02-10 14:15:19 -08003048 } else if (res == AppOpsManager::MODE_ALLOWED) {
3049 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003050 }
3051}
3052
Svet Ganova453d0d2018-01-11 15:37:58 -08003053void CameraService::BasicClient::block() {
3054 ATRACE_CALL();
3055
3056 // Reset the client PID to allow server-initiated disconnect,
3057 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003058 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08003059 CaptureResultExtras resultExtras; // a dummy result (invalid)
3060 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
3061 disconnect();
3062}
3063
Mathias Agopian65ab4712010-07-14 17:59:35 -07003064// ----------------------------------------------------------------------------
3065
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003066void CameraService::Client::notifyError(int32_t errorCode,
Jianing Weicb0652e2014-03-12 18:29:36 -07003067 const CaptureResultExtras& resultExtras) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08003068 (void) resultExtras;
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003069 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07003070 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
3071 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
3072 api1ErrorCode = CAMERA_ERROR_DISABLED;
3073 }
3074 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003075 } else {
3076 ALOGE("mRemoteCallback is NULL!!");
3077 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003078}
3079
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003080// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003081binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003082 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003083 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08003084}
3085
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003086bool CameraService::Client::canCastToApiClient(apiLevel level) const {
3087 return level == API_1;
3088}
3089
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003090CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
3091 mClient(client) {
3092}
3093
3094void CameraService::Client::OpsCallback::opChanged(int32_t op,
3095 const String16& packageName) {
3096 sp<BasicClient> client = mClient.promote();
3097 if (client != NULL) {
3098 client->opChanged(op, packageName);
3099 }
3100}
3101
Mathias Agopian65ab4712010-07-14 17:59:35 -07003102// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08003103// UidPolicy
3104// ----------------------------------------------------------------------------
3105
3106void CameraService::UidPolicy::registerSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003107 Mutex::Autolock _l(mUidLock);
3108
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003109 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07003110 status_t res = mAm.linkToDeath(this);
3111 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08003112 | ActivityManager::UID_OBSERVER_IDLE
Emilian Peev53722fa2019-02-22 17:47:20 -08003113 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganova453d0d2018-01-11 15:37:58 -08003114 ActivityManager::PROCESS_STATE_UNKNOWN,
3115 String16("cameraserver"));
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003116 if (res == OK) {
3117 mRegistered = true;
3118 ALOGV("UidPolicy: Registered with ActivityManager");
3119 }
Svet Ganova453d0d2018-01-11 15:37:58 -08003120}
3121
3122void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003123 Mutex::Autolock _l(mUidLock);
3124
Steven Moreland2f348142019-07-02 15:59:07 -07003125 mAm.unregisterUidObserver(this);
3126 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003127 mRegistered = false;
3128 mActiveUids.clear();
3129 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08003130}
3131
3132void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
3133 onUidIdle(uid, disabled);
3134}
3135
3136void CameraService::UidPolicy::onUidActive(uid_t uid) {
3137 Mutex::Autolock _l(mUidLock);
3138 mActiveUids.insert(uid);
3139}
3140
3141void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
3142 bool deleted = false;
3143 {
3144 Mutex::Autolock _l(mUidLock);
3145 if (mActiveUids.erase(uid) > 0) {
3146 deleted = true;
3147 }
3148 }
3149 if (deleted) {
3150 sp<CameraService> service = mService.promote();
3151 if (service != nullptr) {
3152 service->blockClientsForUid(uid);
3153 }
3154 }
3155}
3156
Emilian Peev53722fa2019-02-22 17:47:20 -08003157void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07003158 int64_t procStateSeq __unused, int32_t capability __unused) {
Emilian Peev53722fa2019-02-22 17:47:20 -08003159 bool procStateChange = false;
3160 {
3161 Mutex::Autolock _l(mUidLock);
3162 if ((mMonitoredUids.find(uid) != mMonitoredUids.end()) &&
3163 (mMonitoredUids[uid].first != procState)) {
3164 mMonitoredUids[uid].first = procState;
3165 procStateChange = true;
3166 }
3167 }
3168
3169 if (procStateChange) {
3170 sp<CameraService> service = mService.promote();
3171 if (service != nullptr) {
3172 service->notifyMonitoredUids();
3173 }
3174 }
3175}
3176
3177void CameraService::UidPolicy::registerMonitorUid(uid_t uid) {
3178 Mutex::Autolock _l(mUidLock);
3179 auto it = mMonitoredUids.find(uid);
3180 if (it != mMonitoredUids.end()) {
3181 it->second.second++;
3182 } else {
3183 mMonitoredUids.emplace(
3184 std::pair<uid_t, std::pair<int32_t, size_t>> (uid,
3185 std::pair<int32_t, size_t> (ActivityManager::PROCESS_STATE_NONEXISTENT, 1)));
3186 }
3187}
3188
3189void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid) {
3190 Mutex::Autolock _l(mUidLock);
3191 auto it = mMonitoredUids.find(uid);
3192 if (it != mMonitoredUids.end()) {
3193 it->second.second--;
3194 if (it->second.second == 0) {
3195 mMonitoredUids.erase(it);
3196 }
3197 } else {
3198 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
3199 }
3200}
3201
Svet Ganov7b4ab782018-03-25 12:48:10 -07003202bool CameraService::UidPolicy::isUidActive(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003203 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003204 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003205}
3206
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003207static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
3208static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003209
Svet Ganov7b4ab782018-03-25 12:48:10 -07003210bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003211 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003212 // If activity manager is unreachable, assume everything is active
3213 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003214 return true;
3215 }
3216 auto it = mOverrideUids.find(uid);
3217 if (it != mOverrideUids.end()) {
3218 return it->second;
3219 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003220 bool active = mActiveUids.find(uid) != mActiveUids.end();
3221 if (!active) {
3222 // We want active UIDs to always access camera with their first attempt since
3223 // there is no guarantee the app is robustly written and would retry getting
3224 // the camera on failure. The inverse case is not a problem as we would take
3225 // camera away soon once we get the callback that the uid is no longer active.
3226 ActivityManager am;
3227 // Okay to access with a lock held as UID changes are dispatched without
3228 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07003229 int64_t startTimeMillis = 0;
3230 do {
3231 // TODO: Fix this b/109950150!
3232 // Okay this is a hack. There is a race between the UID turning active and
3233 // activity being resumed. The proper fix is very risky, so we temporary add
3234 // some polling which should happen pretty rarely anyway as the race is hard
3235 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003236 active = mActiveUids.find(uid) != mActiveUids.end();
Hui Yu12c7ec72020-05-04 17:40:52 +00003237 if (!active) active = am.isUidActive(uid, callingPackage);
Svet Ganov94ec46f2018-06-08 15:03:46 -07003238 if (active) {
3239 break;
3240 }
3241 if (startTimeMillis <= 0) {
3242 startTimeMillis = uptimeMillis();
3243 }
3244 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003245 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003246 if (remainingTimeMillis <= 0) {
3247 break;
3248 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003249 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
3250
3251 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003252 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003253 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003254 } while (true);
3255
Svet Ganov7b4ab782018-03-25 12:48:10 -07003256 if (active) {
3257 // Now that we found out the UID is actually active, cache that
3258 mActiveUids.insert(uid);
3259 }
3260 }
3261 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08003262}
3263
Varun Shahb42f1eb2019-04-16 14:45:13 -07003264int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
3265 Mutex::Autolock _l(mUidLock);
3266 return getProcStateLocked(uid);
3267}
3268
3269int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
3270 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
3271 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
3272 procState = mMonitoredUids[uid].first;
3273 }
3274 return procState;
3275}
3276
Svet Ganov7b4ab782018-03-25 12:48:10 -07003277void CameraService::UidPolicy::UidPolicy::addOverrideUid(uid_t uid,
3278 String16 callingPackage, bool active) {
3279 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08003280}
3281
Svet Ganov7b4ab782018-03-25 12:48:10 -07003282void CameraService::UidPolicy::removeOverrideUid(uid_t uid, String16 callingPackage) {
3283 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08003284}
3285
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003286void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
3287 Mutex::Autolock _l(mUidLock);
3288 ALOGV("UidPolicy: ActivityManager has died");
3289 mRegistered = false;
3290 mActiveUids.clear();
3291}
3292
Svet Ganov7b4ab782018-03-25 12:48:10 -07003293void CameraService::UidPolicy::updateOverrideUid(uid_t uid, String16 callingPackage,
3294 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003295 bool wasActive = false;
3296 bool isActive = false;
3297 {
3298 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003299 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003300 mOverrideUids.erase(uid);
3301 if (insert) {
3302 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
3303 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003304 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003305 }
3306 if (wasActive != isActive && !isActive) {
3307 sp<CameraService> service = mService.promote();
3308 if (service != nullptr) {
3309 service->blockClientsForUid(uid);
3310 }
3311 }
3312}
3313
3314// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08003315// SensorPrivacyPolicy
3316// ----------------------------------------------------------------------------
3317void CameraService::SensorPrivacyPolicy::registerSelf() {
3318 Mutex::Autolock _l(mSensorPrivacyLock);
3319 if (mRegistered) {
3320 return;
3321 }
Evan Severson09ab4002021-02-10 14:15:19 -08003322 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08003323 mSpm.addSensorPrivacyListener(this);
3324 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
3325 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003326 if (res == OK) {
3327 mRegistered = true;
3328 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
3329 }
3330}
3331
3332void CameraService::SensorPrivacyPolicy::unregisterSelf() {
3333 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08003334 mSpm.removeSensorPrivacyListener(this);
3335 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003336 mRegistered = false;
3337 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
3338}
3339
3340bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
3341 Mutex::Autolock _l(mSensorPrivacyLock);
3342 return mSensorPrivacyEnabled;
3343}
3344
Evan Severson09ab4002021-02-10 14:15:19 -08003345bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled(userid_t userId) {
3346 if (!hasCameraPrivacyFeature()) {
3347 return false;
3348 }
3349 return mSpm.isIndividualSensorPrivacyEnabled(userId,
3350 SensorPrivacyManager::INDIVIDUAL_SENSOR_CAMERA);
3351}
3352
Michael Grooverd1d435a2018-12-18 17:39:42 -08003353binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
3354 {
3355 Mutex::Autolock _l(mSensorPrivacyLock);
3356 mSensorPrivacyEnabled = enabled;
3357 }
3358 // if sensor privacy is enabled then block all clients from accessing the camera
Evan Severson09ab4002021-02-10 14:15:19 -08003359 if (enabled) {
3360 sp<CameraService> service = mService.promote();
3361 if (service != nullptr) {
3362 service->blockAllClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08003363 }
3364 }
3365 return binder::Status::ok();
3366}
3367
3368void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
3369 Mutex::Autolock _l(mSensorPrivacyLock);
3370 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
3371 mRegistered = false;
3372}
3373
Evan Severson09ab4002021-02-10 14:15:19 -08003374bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
3375 if (!mNeedToCheckCameraPrivacyFeature) {
3376 return mHasCameraPrivacyFeature;
3377 }
3378 bool hasCameraPrivacyFeature = false;
3379 sp<IBinder> binder = defaultServiceManager()->getService(String16("package_native"));
3380 if (binder != nullptr) {
3381 sp<content::pm::IPackageManagerNative> packageManager =
3382 interface_cast<content::pm::IPackageManagerNative>(binder);
3383 if (packageManager != nullptr) {
3384 binder::Status status = packageManager->hasSystemFeature(
3385 String16("android.hardware.camera.toggle"), 0, &hasCameraPrivacyFeature);
3386
3387 if (status.isOk()) {
3388 mNeedToCheckCameraPrivacyFeature = false;
3389 mHasCameraPrivacyFeature = hasCameraPrivacyFeature;
3390 } else {
3391 ALOGE("Unable to check if camera privacy feature is supported");
3392 }
3393 }
3394 }
3395
3396 return hasCameraPrivacyFeature;
3397}
3398
Michael Grooverd1d435a2018-12-18 17:39:42 -08003399// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003400// CameraState
3401// ----------------------------------------------------------------------------
3402
3403CameraService::CameraState::CameraState(const String8& id, int cost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003404 const std::set<String8>& conflicting, SystemCameraKind systemCameraKind) : mId(id),
3405 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
3406 mSystemCameraKind(systemCameraKind) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08003407
3408CameraService::CameraState::~CameraState() {}
3409
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003410CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003411 Mutex::Autolock lock(mStatusLock);
3412 return mStatus;
3413}
3414
Shuzhen Wang43858162020-01-10 13:42:15 -08003415std::vector<String8> CameraService::CameraState::getUnavailablePhysicalIds() const {
3416 Mutex::Autolock lock(mStatusLock);
3417 std::vector<String8> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
3418 return res;
3419}
3420
Ruben Brunkcc776712015-02-17 20:18:47 -08003421CameraParameters CameraService::CameraState::getShimParams() const {
3422 return mShimParams;
3423}
3424
3425void CameraService::CameraState::setShimParams(const CameraParameters& params) {
3426 mShimParams = params;
3427}
3428
3429int CameraService::CameraState::getCost() const {
3430 return mCost;
3431}
3432
3433std::set<String8> CameraService::CameraState::getConflicting() const {
3434 return mConflicting;
3435}
3436
3437String8 CameraService::CameraState::getId() const {
3438 return mId;
3439}
3440
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003441SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
3442 return mSystemCameraKind;
3443}
3444
Shuzhen Wang43858162020-01-10 13:42:15 -08003445bool CameraService::CameraState::addUnavailablePhysicalId(const String8& physicalId) {
3446 Mutex::Autolock lock(mStatusLock);
3447 auto result = mUnavailablePhysicalIds.insert(physicalId);
3448 return result.second;
3449}
3450
3451bool CameraService::CameraState::removeUnavailablePhysicalId(const String8& physicalId) {
3452 Mutex::Autolock lock(mStatusLock);
3453 auto count = mUnavailablePhysicalIds.erase(physicalId);
3454 return count > 0;
3455}
3456
Ruben Brunkcc776712015-02-17 20:18:47 -08003457// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07003458// ClientEventListener
3459// ----------------------------------------------------------------------------
3460
3461void CameraService::ClientEventListener::onClientAdded(
3462 const resource_policy::ClientDescriptor<String8,
3463 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003464 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003465 if (basicClient.get() != nullptr) {
3466 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3467 notifier.noteStartCamera(descriptor.getKey(),
3468 static_cast<int>(basicClient->getClientUid()));
3469 }
3470}
3471
3472void CameraService::ClientEventListener::onClientRemoved(
3473 const resource_policy::ClientDescriptor<String8,
3474 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003475 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003476 if (basicClient.get() != nullptr) {
3477 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3478 notifier.noteStopCamera(descriptor.getKey(),
3479 static_cast<int>(basicClient->getClientUid()));
3480 }
3481}
3482
3483
3484// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003485// CameraClientManager
3486// ----------------------------------------------------------------------------
3487
Ruben Brunk99e69712015-05-26 17:25:07 -07003488CameraService::CameraClientManager::CameraClientManager() {
3489 setListener(std::make_shared<ClientEventListener>());
3490}
3491
Ruben Brunkcc776712015-02-17 20:18:47 -08003492CameraService::CameraClientManager::~CameraClientManager() {}
3493
3494sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
3495 const String8& id) const {
3496 auto descriptor = get(id);
3497 if (descriptor == nullptr) {
3498 return sp<BasicClient>{nullptr};
3499 }
3500 return descriptor->getValue();
3501}
3502
3503String8 CameraService::CameraClientManager::toString() const {
3504 auto all = getAll();
3505 String8 ret("[");
3506 bool hasAny = false;
3507 for (auto& i : all) {
3508 hasAny = true;
3509 String8 key = i->getKey();
3510 int32_t cost = i->getCost();
3511 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00003512 int32_t score = i->getPriority().getScore();
3513 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08003514 auto conflicting = i->getConflicting();
3515 auto clientSp = i->getValue();
3516 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07003517 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08003518 if (clientSp.get() != nullptr) {
3519 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07003520 uid_t clientUid = clientSp->getClientUid();
3521 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003522 }
Emilian Peev8131a262017-02-01 12:33:43 +00003523 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
3524 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08003525
Ruben Brunk6267b532015-04-30 17:44:07 -07003526 if (clientSp.get() != nullptr) {
3527 ret.appendFormat("User Id: %d, ", clientUserId);
3528 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003529 if (packageName.size() != 0) {
3530 ret.appendFormat("Client Package Name: %s", packageName.string());
3531 }
3532
3533 ret.append(", Conflicting Client Devices: {");
3534 for (auto& j : conflicting) {
3535 ret.appendFormat("%s, ", j.string());
3536 }
3537 ret.append("})");
3538 }
3539 if (hasAny) ret.append("\n");
3540 ret.append("]\n");
3541 return ret;
3542}
3543
3544CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3545 const String8& key, const sp<BasicClient>& value, int32_t cost,
Emilian Peev8131a262017-02-01 12:33:43 +00003546 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
3547 int32_t state) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003548
Steven Moreland89a2c5c2020-01-31 15:02:25 -08003549 bool isVendorClient = getCurrentServingCall() == BinderCallType::HWBINDER;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003550 int32_t score_adj = isVendorClient ? kVendorClientScore : score;
3551 int32_t state_adj = isVendorClient ? kVendorClientState: state;
3552
Ruben Brunkcc776712015-02-17 20:18:47 -08003553 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003554 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj, isVendorClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08003555}
3556
3557CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3558 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
3559 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00003560 partial->getConflicting(), partial->getPriority().getScore(),
3561 partial->getOwnerId(), partial->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08003562}
3563
3564// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07003565
3566static const int kDumpLockRetries = 50;
3567static const int kDumpLockSleep = 60000;
3568
3569static bool tryLock(Mutex& mutex)
3570{
3571 bool locked = false;
3572 for (int i = 0; i < kDumpLockRetries; ++i) {
3573 if (mutex.tryLock() == NO_ERROR) {
3574 locked = true;
3575 break;
3576 }
3577 usleep(kDumpLockSleep);
3578 }
3579 return locked;
3580}
3581
3582status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003583 ATRACE_CALL();
3584
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003585 if (checkCallingPermission(sDumpPermission) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003586 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07003587 CameraThreadState::getCallingPid(),
3588 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003589 return NO_ERROR;
3590 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003591 bool locked = tryLock(mServiceLock);
3592 // failed to lock - CameraService is probably deadlocked
3593 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003594 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003595 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003596
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003597 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003598 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07003599
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003600 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003601 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08003602
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003603 if (locked) mServiceLock.unlock();
3604 return NO_ERROR;
3605 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003606 dprintf(fd, "\n== Service global info: ==\n\n");
3607 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003608 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07003609 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
3610 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003611 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
3612 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
3613 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003614 String8 activeClientString = mActiveClientManager.toString();
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003615 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
3616 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003617
3618 dumpEventLog(fd);
3619
3620 bool stateLocked = tryLock(mCameraStatesLock);
3621 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003622 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003623 }
3624
Emilian Peevbd8c5032018-02-14 23:05:40 +00003625 int argSize = args.size();
3626 for (int i = 0; i < argSize; i++) {
3627 if (args[i] == TagMonitor::kMonitorOption) {
3628 if (i + 1 < argSize) {
3629 mMonitorTags = String8(args[i + 1]);
3630 }
3631 break;
3632 }
3633 }
3634
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003635 for (auto& state : mCameraStates) {
3636 String8 cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003637
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003638 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003639
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003640 CameraParameters p = state.second->getShimParams();
3641 if (!p.isEmpty()) {
3642 dprintf(fd, " Camera1 API shim is using parameters:\n ");
3643 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003644 }
3645
3646 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08003647 if (clientDescriptor != nullptr) {
3648 dprintf(fd, " Device %s is open. Client instance dump:\n",
3649 cameraId.string());
3650 dprintf(fd, " Client priority score: %d state: %d\n",
3651 clientDescriptor->getPriority().getScore(),
3652 clientDescriptor->getPriority().getState());
3653 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
3654
3655 auto client = clientDescriptor->getValue();
3656 dprintf(fd, " Client package: %s\n",
3657 String8(client->getPackageName()).string());
3658
3659 client->dumpClient(fd, args);
3660 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003661 dprintf(fd, " Device %s is closed, no client instance\n",
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003662 cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003663 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003664
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003665 }
3666
3667 if (stateLocked) mCameraStatesLock.unlock();
3668
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003669 if (locked) mServiceLock.unlock();
3670
Emilian Peevf53f66e2017-04-11 14:29:43 +01003671 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003672
3673 dprintf(fd, "\n== Vendor tags: ==\n\n");
3674
3675 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
3676 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00003677 sp<VendorTagDescriptorCache> cache =
3678 VendorTagDescriptorCache::getGlobalVendorTagCache();
3679 if (cache == NULL) {
3680 dprintf(fd, "No vendor tags.\n");
3681 } else {
3682 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
3683 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003684 } else {
3685 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
3686 }
3687
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003688 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003689 dprintf(fd, "\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003690 camera3::CameraTraces::dump(fd, args);
3691
3692 // Process dump arguments, if any
3693 int n = args.size();
3694 String16 verboseOption("-v");
3695 String16 unreachableOption("--unreachable");
3696 for (int i = 0; i < n; i++) {
3697 if (args[i] == verboseOption) {
3698 // change logging level
3699 if (i + 1 >= n) continue;
3700 String8 levelStr(args[i+1]);
3701 int level = atoi(levelStr.string());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003702 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003703 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003704 } else if (args[i] == unreachableOption) {
3705 // Dump memory analysis
3706 // TODO - should limit be an argument parameter?
3707 UnreachableMemoryInfo info;
3708 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
3709 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003710 dprintf(fd, "\n== Unable to dump unreachable memory. "
3711 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003712 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003713 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003714 std::string s = info.ToString(/*log_contents*/ true);
3715 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003716 }
3717 }
3718 }
3719 return NO_ERROR;
3720}
3721
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003722void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003723 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003724
3725 Mutex::Autolock l(mLogLock);
3726 for (const auto& msg : mEventLog) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003727 dprintf(fd, " %s\n", msg.string());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003728 }
3729
3730 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003731 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003732 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003733 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003734 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003735 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003736}
3737
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003738void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003739 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003740 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
3741 if (mTorchClientMap[i] == who) {
3742 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003743 String8 cameraId = mTorchClientMap.keyAt(i);
3744 status_t res = mFlashlight->setTorchMode(cameraId, false);
3745 if (res) {
3746 ALOGE("%s: torch client died but couldn't turn off torch: "
3747 "%s (%d)", __FUNCTION__, strerror(-res), res);
3748 return;
3749 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003750 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003751 break;
3752 }
3753 }
3754}
3755
Ruben Brunkcc776712015-02-17 20:18:47 -08003756/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003757
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003758 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07003759 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
3760 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003761 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003762 // PID here is approximate and can be wrong.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003763 logClientDied(CameraThreadState::getCallingPid(), String8("Binder died unexpectedly"));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003764
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003765 // check torch client
3766 handleTorchClientBinderDied(who);
3767
3768 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08003769 if(!evictClientIdByRemote(who)) {
3770 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003771 return;
3772 }
3773
Ruben Brunkcc776712015-02-17 20:18:47 -08003774 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
3775 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003776}
3777
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003778void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003779 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08003780}
3781
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003782void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
3783 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003784 // Do not lock mServiceLock here or can get into a deadlock from
3785 // connect() -> disconnect -> updateStatus
3786
3787 auto state = getCameraState(cameraId);
3788
3789 if (state == nullptr) {
3790 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
3791 cameraId.string());
3792 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07003793 }
3794
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003795 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
3796 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3797 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3798 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
3799 return;
3800 }
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003801 bool supportsHAL3 = false;
3802 // supportsCameraApi also holds mInterfaceMutex, we can't call it in the
3803 // HIDL onStatusChanged wrapper call (we'll hold mStatusListenerLock and
3804 // mInterfaceMutex together, which can lead to deadlocks)
3805 binder::Status sRet =
3806 supportsCameraApi(String16(cameraId), hardware::ICameraService::API_VERSION_2,
3807 &supportsHAL3);
3808 if (!sRet.isOk()) {
3809 ALOGW("%s: Failed to determine if device supports HAL3 %s, supportsCameraApi call failed",
3810 __FUNCTION__, cameraId.string());
3811 return;
3812 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003813
3814 // Collect the logical cameras without holding mStatusLock in updateStatus
3815 // as that can lead to a deadlock(b/162192331).
3816 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08003817 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08003818 // of the listeners with both the mStatusLock and mStatusListenerLock held
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003819 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind, &supportsHAL3,
3820 &logicalCameraIds]
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003821 (const String8& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003822
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003823 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003824 // Update torch status if it has a flash unit.
3825 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003826 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003827 if (getTorchStatusLocked(cameraId, &torchStatus) !=
3828 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003829 TorchModeStatus newTorchStatus =
3830 status == StatusInternal::PRESENT ?
3831 TorchModeStatus::AVAILABLE_OFF :
3832 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003833 if (torchStatus != newTorchStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003834 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003835 }
3836 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003837 }
3838
3839 Mutex::Autolock lock(mStatusListenerLock);
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003840 notifyPhysicalCameraStatusLocked(mapToInterface(status), String16(cameraId),
3841 logicalCameraIds, deviceKind);
Shuzhen Wang43858162020-01-10 13:42:15 -08003842
Ruben Brunkcc776712015-02-17 20:18:47 -08003843 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003844 bool isVendorListener = listener->isVendorListener();
3845 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
3846 listener->getListenerPid(), listener->getListenerUid()) ||
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07003847 (isVendorListener && !supportsHAL3)) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003848 ALOGV("Skipping discovery callback for system-only camera/HAL1 device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003849 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003850 continue;
3851 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003852 listener->getListener()->onStatusChanged(mapToInterface(status),
Emilian Peev53722fa2019-02-22 17:47:20 -08003853 String16(cameraId));
Ruben Brunkcc776712015-02-17 20:18:47 -08003854 }
3855 });
Igor Murashkincba2c162013-03-20 15:56:31 -07003856}
3857
Shuzhen Wang695044d2020-03-06 09:02:23 -08003858void CameraService::updateOpenCloseStatus(const String8& cameraId, bool open,
3859 const String16& clientPackageName) {
3860 Mutex::Autolock lock(mStatusListenerLock);
3861
3862 for (const auto& it : mListenerList) {
3863 if (!it->isOpenCloseCallbackAllowed()) {
3864 continue;
3865 }
3866
3867 binder::Status ret;
3868 String16 cameraId64(cameraId);
3869 if (open) {
3870 ret = it->getListener()->onCameraOpened(cameraId64, clientPackageName);
3871 } else {
3872 ret = it->getListener()->onCameraClosed(cameraId64);
3873 }
3874 if (!ret.isOk()) {
3875 ALOGE("%s: Failed to trigger onCameraOpened/onCameraClosed callback: %d", __FUNCTION__,
3876 ret.exceptionCode());
3877 }
3878 }
3879}
3880
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003881template<class Func>
3882void CameraService::CameraState::updateStatus(StatusInternal status,
3883 const String8& cameraId,
3884 std::initializer_list<StatusInternal> rejectSourceStates,
3885 Func onStatusUpdatedLocked) {
3886 Mutex::Autolock lock(mStatusLock);
3887 StatusInternal oldStatus = mStatus;
3888 mStatus = status;
3889
3890 if (oldStatus == status) {
3891 return;
3892 }
3893
3894 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
3895 cameraId.string(), oldStatus, status);
3896
3897 if (oldStatus == StatusInternal::NOT_PRESENT &&
3898 (status != StatusInternal::PRESENT &&
3899 status != StatusInternal::ENUMERATING)) {
3900
3901 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
3902 __FUNCTION__);
3903 mStatus = oldStatus;
3904 return;
3905 }
3906
3907 /**
3908 * Sometimes we want to conditionally do a transition.
3909 * For example if a client disconnects, we want to go to PRESENT
3910 * only if we weren't already in NOT_PRESENT or ENUMERATING.
3911 */
3912 for (auto& rejectStatus : rejectSourceStates) {
3913 if (oldStatus == rejectStatus) {
3914 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
3915 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
3916 mStatus = oldStatus;
3917 return;
3918 }
3919 }
3920
3921 onStatusUpdatedLocked(cameraId, status);
3922}
3923
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003924status_t CameraService::getTorchStatusLocked(
3925 const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003926 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003927 if (!status) {
3928 return BAD_VALUE;
3929 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003930 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3931 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003932 // invalid camera ID or the camera doesn't have a flash unit
3933 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003934 }
3935
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003936 *status = mTorchStatusMap.valueAt(index);
3937 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003938}
3939
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003940status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003941 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003942 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3943 if (index == NAME_NOT_FOUND) {
3944 return BAD_VALUE;
3945 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003946 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003947
3948 return OK;
3949}
3950
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003951std::list<String16> CameraService::getLogicalCameras(
3952 const String8& physicalCameraId) {
3953 std::list<String16> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08003954 Mutex::Autolock lock(mCameraStatesLock);
3955 for (const auto& state : mCameraStates) {
3956 std::vector<std::string> physicalCameraIds;
3957 if (!mCameraProviderManager->isLogicalCamera(state.first.c_str(), &physicalCameraIds)) {
3958 // This is not a logical multi-camera.
3959 continue;
3960 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003961 if (std::find(physicalCameraIds.begin(), physicalCameraIds.end(), physicalCameraId.c_str())
Shuzhen Wang43858162020-01-10 13:42:15 -08003962 == physicalCameraIds.end()) {
3963 // cameraId is not a physical camera of this logical multi-camera.
3964 continue;
3965 }
3966
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003967 retList.emplace_back(String16(state.first));
3968 }
3969 return retList;
3970}
3971
3972void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
3973 const String16& physicalCameraId, const std::list<String16>& logicalCameraIds,
3974 SystemCameraKind deviceKind) {
3975 // mStatusListenerLock is expected to be locked
3976 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08003977 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003978 // Note: we check only the deviceKind of the physical camera id
3979 // since, logical camera ids and their physical camera ids are
3980 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07003981 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
3982 listener->getListenerPid(), listener->getListenerUid())) {
3983 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003984 String8(physicalCameraId).c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07003985 continue;
3986 }
Shuzhen Wang43858162020-01-10 13:42:15 -08003987 listener->getListener()->onPhysicalCameraStatusChanged(status,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003988 logicalCameraId, physicalCameraId);
Shuzhen Wang43858162020-01-10 13:42:15 -08003989 }
3990 }
3991}
3992
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003993
Svet Ganova453d0d2018-01-11 15:37:58 -08003994void CameraService::blockClientsForUid(uid_t uid) {
3995 const auto clients = mActiveClientManager.getAll();
3996 for (auto& current : clients) {
3997 if (current != nullptr) {
3998 const auto basicClient = current->getValue();
3999 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
4000 basicClient->block();
4001 }
4002 }
4003 }
4004}
4005
Michael Grooverd1d435a2018-12-18 17:39:42 -08004006void CameraService::blockAllClients() {
4007 const auto clients = mActiveClientManager.getAll();
4008 for (auto& current : clients) {
4009 if (current != nullptr) {
4010 const auto basicClient = current->getValue();
4011 if (basicClient.get() != nullptr) {
4012 basicClient->block();
4013 }
4014 }
4015 }
4016}
4017
Svet Ganova453d0d2018-01-11 15:37:58 -08004018// NOTE: This is a remote API - make sure all args are validated
4019status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
4020 if (!checkCallingPermission(sManageCameraPermission, nullptr, nullptr)) {
4021 return PERMISSION_DENIED;
4022 }
4023 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
4024 return BAD_VALUE;
4025 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004026 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004027 return handleSetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07004028 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004029 return handleResetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07004030 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004031 return handleGetUidState(args, out, err);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004032 } else if (args.size() >= 2 && args[0] == String16("set-rotate-and-crop")) {
4033 return handleSetRotateAndCrop(args);
4034 } else if (args.size() >= 1 && args[0] == String16("get-rotate-and-crop")) {
4035 return handleGetRotateAndCrop(out);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004036 } else if (args.size() >= 2 && args[0] == String16("set-image-dump-mask")) {
4037 return handleSetImageDumpMask(args);
4038 } else if (args.size() >= 1 && args[0] == String16("get-image-dump-mask")) {
4039 return handleGetImageDumpMask(out);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004040 } else if (args.size() >= 2 && args[0] == String16("set-camera-mute")) {
4041 return handleSetCameraMute(args);
Svet Ganova453d0d2018-01-11 15:37:58 -08004042 } else if (args.size() == 1 && args[0] == String16("help")) {
4043 printHelp(out);
4044 return NO_ERROR;
4045 }
4046 printHelp(err);
4047 return BAD_VALUE;
4048}
4049
4050status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004051 String16 packageName = args[1];
4052
Svet Ganova453d0d2018-01-11 15:37:58 -08004053 bool active = false;
4054 if (args[2] == String16("active")) {
4055 active = true;
4056 } else if ((args[2] != String16("idle"))) {
4057 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
4058 return BAD_VALUE;
4059 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004060
4061 int userId = 0;
4062 if (args.size() >= 5 && args[3] == String16("--user")) {
4063 userId = atoi(String8(args[4]));
4064 }
4065
4066 uid_t uid;
4067 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
4068 return BAD_VALUE;
4069 }
4070
4071 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08004072 return NO_ERROR;
4073}
4074
4075status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004076 String16 packageName = args[1];
4077
4078 int userId = 0;
4079 if (args.size() >= 4 && args[2] == String16("--user")) {
4080 userId = atoi(String8(args[3]));
4081 }
4082
4083 uid_t uid;
4084 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004085 return BAD_VALUE;
4086 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004087
4088 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08004089 return NO_ERROR;
4090}
4091
4092status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004093 String16 packageName = args[1];
4094
4095 int userId = 0;
4096 if (args.size() >= 4 && args[2] == String16("--user")) {
4097 userId = atoi(String8(args[3]));
4098 }
4099
4100 uid_t uid;
4101 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004102 return BAD_VALUE;
4103 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004104
4105 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004106 return dprintf(out, "active\n");
4107 } else {
4108 return dprintf(out, "idle\n");
4109 }
4110}
4111
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004112status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
4113 int rotateValue = atoi(String8(args[1]));
4114 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
4115 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
4116 Mutex::Autolock lock(mServiceLock);
4117
4118 mOverrideRotateAndCropMode = rotateValue;
4119
4120 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
4121
4122 const auto clients = mActiveClientManager.getAll();
4123 for (auto& current : clients) {
4124 if (current != nullptr) {
4125 const auto basicClient = current->getValue();
4126 if (basicClient.get() != nullptr) {
4127 basicClient->setRotateAndCropOverride(rotateValue);
4128 }
4129 }
4130 }
4131
4132 return OK;
4133}
4134
4135status_t CameraService::handleGetRotateAndCrop(int out) {
4136 Mutex::Autolock lock(mServiceLock);
4137
4138 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
4139}
4140
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004141status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
4142 char *endPtr;
4143 errno = 0;
4144 String8 maskString8 = String8(args[1]);
4145 long maskValue = strtol(maskString8.c_str(), &endPtr, 10);
4146
4147 if (errno != 0) return BAD_VALUE;
4148 if (endPtr != maskString8.c_str() + maskString8.size()) return BAD_VALUE;
4149 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
4150
4151 Mutex::Autolock lock(mServiceLock);
4152
4153 mImageDumpMask = maskValue;
4154
4155 return OK;
4156}
4157
4158status_t CameraService::handleGetImageDumpMask(int out) {
4159 Mutex::Autolock lock(mServiceLock);
4160
4161 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
4162}
4163
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004164status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
4165 int muteValue = strtol(String8(args[1]), nullptr, 10);
4166 if (errno != 0) return BAD_VALUE;
4167
4168 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
4169 Mutex::Autolock lock(mServiceLock);
4170
4171 mOverrideCameraMuteMode = (muteValue == 1);
4172
4173 const auto clients = mActiveClientManager.getAll();
4174 for (auto& current : clients) {
4175 if (current != nullptr) {
4176 const auto basicClient = current->getValue();
4177 if (basicClient.get() != nullptr) {
4178 if (basicClient->supportsCameraMute()) {
4179 basicClient->setCameraMute(mOverrideCameraMuteMode);
4180 }
4181 }
4182 }
4183 }
4184
4185 return OK;
4186}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004187
Svet Ganova453d0d2018-01-11 15:37:58 -08004188status_t CameraService::printHelp(int out) {
4189 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07004190 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
4191 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
4192 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004193 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
4194 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
4195 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004196 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
4197 " Valid values 0=OFF, 1=ON for JPEG\n"
4198 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004199 " set-camera-mute <0/1> enable or disable camera muting\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08004200 " help print this message\n");
4201}
4202
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004203int32_t CameraService::updateAudioRestriction() {
4204 Mutex::Autolock lock(mServiceLock);
4205 return updateAudioRestrictionLocked();
4206}
4207
4208int32_t CameraService::updateAudioRestrictionLocked() {
4209 int32_t mode = 0;
4210 // iterate through all active client
4211 for (const auto& i : mActiveClientManager.getAll()) {
4212 const auto clientSp = i->getValue();
4213 mode |= clientSp->getAudioRestriction();
4214 }
4215
4216 bool modeChanged = (mAudioRestriction != mode);
4217 mAudioRestriction = mode;
4218 if (modeChanged) {
4219 mAppOps.setCameraAudioRestriction(mode);
4220 }
4221 return mode;
4222}
4223
Mathias Agopian65ab4712010-07-14 17:59:35 -07004224}; // namespace android