blob: c6172f12569ab0e5c465a531b3b824138881dfd9 [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):
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002773 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07002774 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09002775 mClientPackageName(clientPackageName), mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002776 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002777 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07002778 mDisconnected(false), mUidIsTrusted(false),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002779 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002780 mRemoteBinder(remoteCallback),
2781 mOpsActive(false),
2782 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08002783{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002784 if (sCameraService == nullptr) {
2785 sCameraService = cameraService;
2786 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08002787
2788 // In some cases the calling code has no access to the package it runs under.
2789 // For example, NDK camera API.
2790 // In this case we will get the packages for the calling UID and pick the first one
2791 // for attributing the app op. This will work correctly for runtime permissions
2792 // as for legacy apps we will toggle the app op for all packages in the UID.
2793 // The caveat is that the operation may be attributed to the wrong package and
2794 // stats based on app ops may be slightly off.
2795 if (mClientPackageName.size() <= 0) {
2796 sp<IServiceManager> sm = defaultServiceManager();
2797 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
2798 if (binder == 0) {
2799 ALOGE("Cannot get permission service");
2800 // Leave mClientPackageName unchanged (empty) and the further interaction
2801 // with camera will fail in BasicClient::startCameraOps
2802 return;
2803 }
2804
2805 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
2806 Vector<String16> packages;
2807
2808 permCtrl->getPackagesForUid(mClientUid, packages);
2809
2810 if (packages.isEmpty()) {
2811 ALOGE("No packages for calling UID");
2812 // Leave mClientPackageName unchanged (empty) and the further interaction
2813 // with camera will fail in BasicClient::startCameraOps
2814 return;
2815 }
2816 mClientPackageName = packages[0];
2817 }
Steven Moreland89a2c5c2020-01-31 15:02:25 -08002818 if (getCurrentServingCall() != BinderCallType::HWBINDER) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002819 mAppOpsManager = std::make_unique<AppOpsManager>();
2820 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07002821
2822 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08002823}
2824
2825CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002826 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08002827 mDestructionStarted = true;
2828}
2829
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002830binder::Status CameraService::BasicClient::disconnect() {
2831 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002832 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002833 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07002834 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07002835 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002836
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002837 sCameraService->removeByClient(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002838 sCameraService->logDisconnected(mCameraIdStr, mClientPid, String8(mClientPackageName));
Peter Kalauskasa29c1352018-10-10 12:05:42 -07002839 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
2840 mCameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002841
2842 sp<IBinder> remote = getRemote();
2843 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002844 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08002845 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002846
2847 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07002848 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002849 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
2850 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
2851 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002852
Igor Murashkincba2c162013-03-20 15:56:31 -07002853 // client shouldn't be able to call into us anymore
2854 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002855
2856 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08002857}
2858
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002859status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
2860 // No dumping of clients directly over Binder,
2861 // must go through CameraService::dump
2862 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07002863 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002864 return OK;
2865}
2866
Ruben Brunkcc776712015-02-17 20:18:47 -08002867String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002868 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08002869}
2870
Emilian Peev8b64f282021-03-25 16:49:57 -07002871int CameraService::BasicClient::getCameraFacing() const {
2872 return mCameraFacing;
2873}
2874
2875int CameraService::BasicClient::getCameraOrientation() const {
2876 return mOrientation;
2877}
Ruben Brunkcc776712015-02-17 20:18:47 -08002878
2879int CameraService::BasicClient::getClientPid() const {
2880 return mClientPid;
2881}
2882
Ruben Brunk6267b532015-04-30 17:44:07 -07002883uid_t CameraService::BasicClient::getClientUid() const {
2884 return mClientUid;
2885}
2886
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002887bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
2888 // Defaults to API2.
2889 return level == API_2;
2890}
2891
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002892status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002893 {
2894 Mutex::Autolock l(mAudioRestrictionLock);
2895 mAudioRestriction = mode;
2896 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002897 sCameraService->updateAudioRestriction();
2898 return OK;
2899}
2900
2901int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002902 return sCameraService->updateAudioRestriction();
2903}
2904
2905int32_t CameraService::BasicClient::getAudioRestriction() const {
2906 Mutex::Autolock l(mAudioRestrictionLock);
2907 return mAudioRestriction;
2908}
2909
2910bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
2911 switch (mode) {
2912 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
2913 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
2914 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
2915 return true;
2916 default:
2917 return false;
2918 }
2919}
2920
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002921status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
2922 if (mode == AppOpsManager::MODE_ERRORED) {
2923 ALOGI("Camera %s: Access for \"%s\" has been revoked",
2924 mCameraIdStr.string(), String8(mClientPackageName).string());
2925 return PERMISSION_DENIED;
2926 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
2927 // If the calling Uid is trusted (a native service), the AppOpsManager could
2928 // return MODE_IGNORED. Do not treat such case as error.
2929 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
2930 mClientPackageName);
2931 bool isCameraPrivacyEnabled =
2932 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled(
2933 multiuser_get_user_id(mClientUid));
2934 if (!isUidActive || !isCameraPrivacyEnabled) {
2935 ALOGI("Camera %s: Access for \"%s\" has been restricted",
2936 mCameraIdStr.string(), String8(mClientPackageName).string());
2937 // Return the same error as for device policy manager rejection
2938 return -EACCES;
2939 }
2940 }
2941 return OK;
2942}
2943
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002944status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002945 ATRACE_CALL();
2946
Igor Murashkine6800ce2013-03-04 17:25:57 -08002947 {
2948 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002949 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08002950 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002951 if (mAppOpsManager != nullptr) {
2952 // Notify app ops that the camera is not available
2953 mOpsCallback = new OpsCallback(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002954 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
2955 mClientPackageName, mOpsCallback);
Igor Murashkine6800ce2013-03-04 17:25:57 -08002956
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002957 // Just check for camera acccess here on open - delay startOp until
2958 // camera frames start streaming in startCameraStreamingOps
2959 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
2960 mClientPackageName);
2961 status_t res = handleAppOpMode(mode);
2962 if (res != OK) {
2963 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002964 }
Svetoslav28e8ef72015-05-11 19:21:31 -07002965 }
2966
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002967 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002968
2969 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002970 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002971
Emilian Peev53722fa2019-02-22 17:47:20 -08002972 sCameraService->mUidPolicy->registerMonitorUid(mClientUid);
2973
Shuzhen Wang695044d2020-03-06 09:02:23 -08002974 // Notify listeners of camera open/close status
2975 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
2976
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002977 return OK;
2978}
2979
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002980status_t CameraService::BasicClient::startCameraStreamingOps() {
2981 ATRACE_CALL();
2982
2983 if (!mOpsActive) {
2984 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
2985 return INVALID_OPERATION;
2986 }
2987 if (mOpsStreaming) {
2988 ALOGV("%s: Streaming already active!", __FUNCTION__);
2989 return OK;
2990 }
2991
2992 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
2993 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
2994
2995 if (mAppOpsManager != nullptr) {
2996 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
2997 mClientPackageName, /*startIfModeDefault*/ false, mClientFeatureId,
2998 String16("start camera ") + String16(mCameraIdStr));
2999 status_t res = handleAppOpMode(mode);
3000 if (res != OK) {
3001 return res;
3002 }
3003 }
3004
3005 mOpsStreaming = true;
3006
3007 return OK;
3008}
3009
3010status_t CameraService::BasicClient::finishCameraStreamingOps() {
3011 ATRACE_CALL();
3012
3013 if (!mOpsActive) {
3014 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
3015 return INVALID_OPERATION;
3016 }
3017 if (!mOpsStreaming) {
3018 ALOGV("%s: Streaming not active!", __FUNCTION__);
3019 return OK;
3020 }
3021
3022 if (mAppOpsManager != nullptr) {
3023 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
3024 mClientPackageName, mClientFeatureId);
3025 mOpsStreaming = false;
3026 }
3027
3028 return OK;
3029}
3030
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003031status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003032 ATRACE_CALL();
3033
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003034 if (mOpsStreaming) {
3035 // Make sure we've notified everyone about camera stopping
3036 finishCameraStreamingOps();
3037 }
3038
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003039 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003040 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003041 mOpsActive = false;
3042
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01003043 // This function is called when a client disconnects. This should
3044 // release the camera, but actually only if it was in a proper
3045 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003046 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01003047 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003048
Ruben Brunkcc776712015-02-17 20:18:47 -08003049 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003050 sCameraService->updateStatus(StatusInternal::PRESENT,
3051 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003052 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003053 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003054 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
3055 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08003056 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003057 mOpsCallback.clear();
3058
Emilian Peev53722fa2019-02-22 17:47:20 -08003059 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid);
3060
Shuzhen Wang695044d2020-03-06 09:02:23 -08003061 // Notify listeners of camera open/close status
3062 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
3063
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003064 return OK;
3065}
3066
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003067void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003068 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003069 if (mAppOpsManager == nullptr) {
3070 return;
3071 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003072 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003073 if (op != AppOpsManager::OP_CAMERA) {
3074 ALOGW("Unexpected app ops notification received: %d", op);
3075 return;
3076 }
3077
3078 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003079 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003080 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003081 ALOGV("checkOp returns: %d, %s ", res,
3082 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
3083 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
3084 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
3085 "UNKNOWN");
3086
Shuzhen Wang64900852021-02-05 09:03:29 -08003087 if (res == AppOpsManager::MODE_ERRORED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003088 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003089 String8(mClientPackageName).string());
Svet Ganova453d0d2018-01-11 15:37:58 -08003090 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08003091 } else if (res == AppOpsManager::MODE_IGNORED) {
3092 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Evan Severson09ab4002021-02-10 14:15:19 -08003093 bool isCameraPrivacyEnabled =
3094 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled(
3095 multiuser_get_user_id(mClientUid));
Shuzhen Wang64900852021-02-05 09:03:29 -08003096 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d",
3097 mCameraIdStr.string(), String8(mClientPackageName).string(),
3098 mUidIsTrusted, isUidActive);
3099 // If the calling Uid is trusted (a native service), or the client Uid is active (WAR for
3100 // b/175320666), the AppOpsManager could return MODE_IGNORED. Do not treat such cases as
3101 // error.
Evan Severson09ab4002021-02-10 14:15:19 -08003102 if (!mUidIsTrusted && isUidActive && isCameraPrivacyEnabled) {
3103 setCameraMute(true);
3104 } else if (!mUidIsTrusted && !isUidActive) {
Shuzhen Wang64900852021-02-05 09:03:29 -08003105 block();
3106 }
Evan Severson09ab4002021-02-10 14:15:19 -08003107 } else if (res == AppOpsManager::MODE_ALLOWED) {
3108 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003109 }
3110}
3111
Svet Ganova453d0d2018-01-11 15:37:58 -08003112void CameraService::BasicClient::block() {
3113 ATRACE_CALL();
3114
3115 // Reset the client PID to allow server-initiated disconnect,
3116 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003117 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08003118 CaptureResultExtras resultExtras; // a dummy result (invalid)
3119 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
3120 disconnect();
3121}
3122
Mathias Agopian65ab4712010-07-14 17:59:35 -07003123// ----------------------------------------------------------------------------
3124
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003125void CameraService::Client::notifyError(int32_t errorCode,
Jianing Weicb0652e2014-03-12 18:29:36 -07003126 const CaptureResultExtras& resultExtras) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08003127 (void) resultExtras;
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003128 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07003129 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
3130 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
3131 api1ErrorCode = CAMERA_ERROR_DISABLED;
3132 }
3133 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003134 } else {
3135 ALOGE("mRemoteCallback is NULL!!");
3136 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003137}
3138
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003139// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003140binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003141 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003142 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08003143}
3144
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003145bool CameraService::Client::canCastToApiClient(apiLevel level) const {
3146 return level == API_1;
3147}
3148
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003149CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
3150 mClient(client) {
3151}
3152
3153void CameraService::Client::OpsCallback::opChanged(int32_t op,
3154 const String16& packageName) {
3155 sp<BasicClient> client = mClient.promote();
3156 if (client != NULL) {
3157 client->opChanged(op, packageName);
3158 }
3159}
3160
Mathias Agopian65ab4712010-07-14 17:59:35 -07003161// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08003162// UidPolicy
3163// ----------------------------------------------------------------------------
3164
3165void CameraService::UidPolicy::registerSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003166 Mutex::Autolock _l(mUidLock);
3167
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003168 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07003169 status_t res = mAm.linkToDeath(this);
3170 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08003171 | ActivityManager::UID_OBSERVER_IDLE
Emilian Peev53722fa2019-02-22 17:47:20 -08003172 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganova453d0d2018-01-11 15:37:58 -08003173 ActivityManager::PROCESS_STATE_UNKNOWN,
3174 String16("cameraserver"));
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003175 if (res == OK) {
3176 mRegistered = true;
3177 ALOGV("UidPolicy: Registered with ActivityManager");
3178 }
Svet Ganova453d0d2018-01-11 15:37:58 -08003179}
3180
3181void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003182 Mutex::Autolock _l(mUidLock);
3183
Steven Moreland2f348142019-07-02 15:59:07 -07003184 mAm.unregisterUidObserver(this);
3185 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003186 mRegistered = false;
3187 mActiveUids.clear();
3188 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08003189}
3190
3191void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
3192 onUidIdle(uid, disabled);
3193}
3194
3195void CameraService::UidPolicy::onUidActive(uid_t uid) {
3196 Mutex::Autolock _l(mUidLock);
3197 mActiveUids.insert(uid);
3198}
3199
3200void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
3201 bool deleted = false;
3202 {
3203 Mutex::Autolock _l(mUidLock);
3204 if (mActiveUids.erase(uid) > 0) {
3205 deleted = true;
3206 }
3207 }
3208 if (deleted) {
3209 sp<CameraService> service = mService.promote();
3210 if (service != nullptr) {
3211 service->blockClientsForUid(uid);
3212 }
3213 }
3214}
3215
Emilian Peev53722fa2019-02-22 17:47:20 -08003216void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07003217 int64_t procStateSeq __unused, int32_t capability __unused) {
Emilian Peev53722fa2019-02-22 17:47:20 -08003218 bool procStateChange = false;
3219 {
3220 Mutex::Autolock _l(mUidLock);
3221 if ((mMonitoredUids.find(uid) != mMonitoredUids.end()) &&
3222 (mMonitoredUids[uid].first != procState)) {
3223 mMonitoredUids[uid].first = procState;
3224 procStateChange = true;
3225 }
3226 }
3227
3228 if (procStateChange) {
3229 sp<CameraService> service = mService.promote();
3230 if (service != nullptr) {
3231 service->notifyMonitoredUids();
3232 }
3233 }
3234}
3235
3236void CameraService::UidPolicy::registerMonitorUid(uid_t uid) {
3237 Mutex::Autolock _l(mUidLock);
3238 auto it = mMonitoredUids.find(uid);
3239 if (it != mMonitoredUids.end()) {
3240 it->second.second++;
3241 } else {
3242 mMonitoredUids.emplace(
3243 std::pair<uid_t, std::pair<int32_t, size_t>> (uid,
3244 std::pair<int32_t, size_t> (ActivityManager::PROCESS_STATE_NONEXISTENT, 1)));
3245 }
3246}
3247
3248void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid) {
3249 Mutex::Autolock _l(mUidLock);
3250 auto it = mMonitoredUids.find(uid);
3251 if (it != mMonitoredUids.end()) {
3252 it->second.second--;
3253 if (it->second.second == 0) {
3254 mMonitoredUids.erase(it);
3255 }
3256 } else {
3257 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
3258 }
3259}
3260
Svet Ganov7b4ab782018-03-25 12:48:10 -07003261bool CameraService::UidPolicy::isUidActive(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003262 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003263 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003264}
3265
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003266static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
3267static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003268
Svet Ganov7b4ab782018-03-25 12:48:10 -07003269bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003270 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003271 // If activity manager is unreachable, assume everything is active
3272 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003273 return true;
3274 }
3275 auto it = mOverrideUids.find(uid);
3276 if (it != mOverrideUids.end()) {
3277 return it->second;
3278 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003279 bool active = mActiveUids.find(uid) != mActiveUids.end();
3280 if (!active) {
3281 // We want active UIDs to always access camera with their first attempt since
3282 // there is no guarantee the app is robustly written and would retry getting
3283 // the camera on failure. The inverse case is not a problem as we would take
3284 // camera away soon once we get the callback that the uid is no longer active.
3285 ActivityManager am;
3286 // Okay to access with a lock held as UID changes are dispatched without
3287 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07003288 int64_t startTimeMillis = 0;
3289 do {
3290 // TODO: Fix this b/109950150!
3291 // Okay this is a hack. There is a race between the UID turning active and
3292 // activity being resumed. The proper fix is very risky, so we temporary add
3293 // some polling which should happen pretty rarely anyway as the race is hard
3294 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003295 active = mActiveUids.find(uid) != mActiveUids.end();
Hui Yu12c7ec72020-05-04 17:40:52 +00003296 if (!active) active = am.isUidActive(uid, callingPackage);
Svet Ganov94ec46f2018-06-08 15:03:46 -07003297 if (active) {
3298 break;
3299 }
3300 if (startTimeMillis <= 0) {
3301 startTimeMillis = uptimeMillis();
3302 }
3303 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003304 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003305 if (remainingTimeMillis <= 0) {
3306 break;
3307 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003308 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
3309
3310 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003311 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003312 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003313 } while (true);
3314
Svet Ganov7b4ab782018-03-25 12:48:10 -07003315 if (active) {
3316 // Now that we found out the UID is actually active, cache that
3317 mActiveUids.insert(uid);
3318 }
3319 }
3320 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08003321}
3322
Varun Shahb42f1eb2019-04-16 14:45:13 -07003323int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
3324 Mutex::Autolock _l(mUidLock);
3325 return getProcStateLocked(uid);
3326}
3327
3328int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
3329 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
3330 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
3331 procState = mMonitoredUids[uid].first;
3332 }
3333 return procState;
3334}
3335
Svet Ganov7b4ab782018-03-25 12:48:10 -07003336void CameraService::UidPolicy::UidPolicy::addOverrideUid(uid_t uid,
3337 String16 callingPackage, bool active) {
3338 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08003339}
3340
Svet Ganov7b4ab782018-03-25 12:48:10 -07003341void CameraService::UidPolicy::removeOverrideUid(uid_t uid, String16 callingPackage) {
3342 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08003343}
3344
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003345void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
3346 Mutex::Autolock _l(mUidLock);
3347 ALOGV("UidPolicy: ActivityManager has died");
3348 mRegistered = false;
3349 mActiveUids.clear();
3350}
3351
Svet Ganov7b4ab782018-03-25 12:48:10 -07003352void CameraService::UidPolicy::updateOverrideUid(uid_t uid, String16 callingPackage,
3353 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003354 bool wasActive = false;
3355 bool isActive = false;
3356 {
3357 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003358 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003359 mOverrideUids.erase(uid);
3360 if (insert) {
3361 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
3362 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003363 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003364 }
3365 if (wasActive != isActive && !isActive) {
3366 sp<CameraService> service = mService.promote();
3367 if (service != nullptr) {
3368 service->blockClientsForUid(uid);
3369 }
3370 }
3371}
3372
3373// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08003374// SensorPrivacyPolicy
3375// ----------------------------------------------------------------------------
3376void CameraService::SensorPrivacyPolicy::registerSelf() {
3377 Mutex::Autolock _l(mSensorPrivacyLock);
3378 if (mRegistered) {
3379 return;
3380 }
Evan Severson09ab4002021-02-10 14:15:19 -08003381 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08003382 mSpm.addSensorPrivacyListener(this);
3383 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
3384 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003385 if (res == OK) {
3386 mRegistered = true;
3387 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
3388 }
3389}
3390
3391void CameraService::SensorPrivacyPolicy::unregisterSelf() {
3392 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08003393 mSpm.removeSensorPrivacyListener(this);
3394 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003395 mRegistered = false;
3396 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
3397}
3398
3399bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
3400 Mutex::Autolock _l(mSensorPrivacyLock);
3401 return mSensorPrivacyEnabled;
3402}
3403
Evan Severson09ab4002021-02-10 14:15:19 -08003404bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled(userid_t userId) {
3405 if (!hasCameraPrivacyFeature()) {
3406 return false;
3407 }
3408 return mSpm.isIndividualSensorPrivacyEnabled(userId,
3409 SensorPrivacyManager::INDIVIDUAL_SENSOR_CAMERA);
3410}
3411
Michael Grooverd1d435a2018-12-18 17:39:42 -08003412binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
3413 {
3414 Mutex::Autolock _l(mSensorPrivacyLock);
3415 mSensorPrivacyEnabled = enabled;
3416 }
3417 // if sensor privacy is enabled then block all clients from accessing the camera
Evan Severson09ab4002021-02-10 14:15:19 -08003418 if (enabled) {
3419 sp<CameraService> service = mService.promote();
3420 if (service != nullptr) {
3421 service->blockAllClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08003422 }
3423 }
3424 return binder::Status::ok();
3425}
3426
3427void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
3428 Mutex::Autolock _l(mSensorPrivacyLock);
3429 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
3430 mRegistered = false;
3431}
3432
Evan Severson09ab4002021-02-10 14:15:19 -08003433bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
3434 if (!mNeedToCheckCameraPrivacyFeature) {
3435 return mHasCameraPrivacyFeature;
3436 }
3437 bool hasCameraPrivacyFeature = false;
3438 sp<IBinder> binder = defaultServiceManager()->getService(String16("package_native"));
3439 if (binder != nullptr) {
3440 sp<content::pm::IPackageManagerNative> packageManager =
3441 interface_cast<content::pm::IPackageManagerNative>(binder);
3442 if (packageManager != nullptr) {
3443 binder::Status status = packageManager->hasSystemFeature(
3444 String16("android.hardware.camera.toggle"), 0, &hasCameraPrivacyFeature);
3445
3446 if (status.isOk()) {
3447 mNeedToCheckCameraPrivacyFeature = false;
3448 mHasCameraPrivacyFeature = hasCameraPrivacyFeature;
3449 } else {
3450 ALOGE("Unable to check if camera privacy feature is supported");
3451 }
3452 }
3453 }
3454
3455 return hasCameraPrivacyFeature;
3456}
3457
Michael Grooverd1d435a2018-12-18 17:39:42 -08003458// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003459// CameraState
3460// ----------------------------------------------------------------------------
3461
3462CameraService::CameraState::CameraState(const String8& id, int cost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003463 const std::set<String8>& conflicting, SystemCameraKind systemCameraKind) : mId(id),
3464 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
3465 mSystemCameraKind(systemCameraKind) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08003466
3467CameraService::CameraState::~CameraState() {}
3468
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003469CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003470 Mutex::Autolock lock(mStatusLock);
3471 return mStatus;
3472}
3473
Shuzhen Wang43858162020-01-10 13:42:15 -08003474std::vector<String8> CameraService::CameraState::getUnavailablePhysicalIds() const {
3475 Mutex::Autolock lock(mStatusLock);
3476 std::vector<String8> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
3477 return res;
3478}
3479
Ruben Brunkcc776712015-02-17 20:18:47 -08003480CameraParameters CameraService::CameraState::getShimParams() const {
3481 return mShimParams;
3482}
3483
3484void CameraService::CameraState::setShimParams(const CameraParameters& params) {
3485 mShimParams = params;
3486}
3487
3488int CameraService::CameraState::getCost() const {
3489 return mCost;
3490}
3491
3492std::set<String8> CameraService::CameraState::getConflicting() const {
3493 return mConflicting;
3494}
3495
3496String8 CameraService::CameraState::getId() const {
3497 return mId;
3498}
3499
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003500SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
3501 return mSystemCameraKind;
3502}
3503
Shuzhen Wang43858162020-01-10 13:42:15 -08003504bool CameraService::CameraState::addUnavailablePhysicalId(const String8& physicalId) {
3505 Mutex::Autolock lock(mStatusLock);
3506 auto result = mUnavailablePhysicalIds.insert(physicalId);
3507 return result.second;
3508}
3509
3510bool CameraService::CameraState::removeUnavailablePhysicalId(const String8& physicalId) {
3511 Mutex::Autolock lock(mStatusLock);
3512 auto count = mUnavailablePhysicalIds.erase(physicalId);
3513 return count > 0;
3514}
3515
Ruben Brunkcc776712015-02-17 20:18:47 -08003516// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07003517// ClientEventListener
3518// ----------------------------------------------------------------------------
3519
3520void CameraService::ClientEventListener::onClientAdded(
3521 const resource_policy::ClientDescriptor<String8,
3522 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003523 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003524 if (basicClient.get() != nullptr) {
3525 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3526 notifier.noteStartCamera(descriptor.getKey(),
3527 static_cast<int>(basicClient->getClientUid()));
3528 }
3529}
3530
3531void CameraService::ClientEventListener::onClientRemoved(
3532 const resource_policy::ClientDescriptor<String8,
3533 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003534 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003535 if (basicClient.get() != nullptr) {
3536 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3537 notifier.noteStopCamera(descriptor.getKey(),
3538 static_cast<int>(basicClient->getClientUid()));
3539 }
3540}
3541
3542
3543// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003544// CameraClientManager
3545// ----------------------------------------------------------------------------
3546
Ruben Brunk99e69712015-05-26 17:25:07 -07003547CameraService::CameraClientManager::CameraClientManager() {
3548 setListener(std::make_shared<ClientEventListener>());
3549}
3550
Ruben Brunkcc776712015-02-17 20:18:47 -08003551CameraService::CameraClientManager::~CameraClientManager() {}
3552
3553sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
3554 const String8& id) const {
3555 auto descriptor = get(id);
3556 if (descriptor == nullptr) {
3557 return sp<BasicClient>{nullptr};
3558 }
3559 return descriptor->getValue();
3560}
3561
3562String8 CameraService::CameraClientManager::toString() const {
3563 auto all = getAll();
3564 String8 ret("[");
3565 bool hasAny = false;
3566 for (auto& i : all) {
3567 hasAny = true;
3568 String8 key = i->getKey();
3569 int32_t cost = i->getCost();
3570 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00003571 int32_t score = i->getPriority().getScore();
3572 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08003573 auto conflicting = i->getConflicting();
3574 auto clientSp = i->getValue();
3575 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07003576 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08003577 if (clientSp.get() != nullptr) {
3578 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07003579 uid_t clientUid = clientSp->getClientUid();
3580 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003581 }
Emilian Peev8131a262017-02-01 12:33:43 +00003582 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
3583 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08003584
Ruben Brunk6267b532015-04-30 17:44:07 -07003585 if (clientSp.get() != nullptr) {
3586 ret.appendFormat("User Id: %d, ", clientUserId);
3587 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003588 if (packageName.size() != 0) {
3589 ret.appendFormat("Client Package Name: %s", packageName.string());
3590 }
3591
3592 ret.append(", Conflicting Client Devices: {");
3593 for (auto& j : conflicting) {
3594 ret.appendFormat("%s, ", j.string());
3595 }
3596 ret.append("})");
3597 }
3598 if (hasAny) ret.append("\n");
3599 ret.append("]\n");
3600 return ret;
3601}
3602
3603CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3604 const String8& key, const sp<BasicClient>& value, int32_t cost,
Emilian Peev8131a262017-02-01 12:33:43 +00003605 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
3606 int32_t state) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003607
Steven Moreland89a2c5c2020-01-31 15:02:25 -08003608 bool isVendorClient = getCurrentServingCall() == BinderCallType::HWBINDER;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003609 int32_t score_adj = isVendorClient ? kVendorClientScore : score;
3610 int32_t state_adj = isVendorClient ? kVendorClientState: state;
3611
Ruben Brunkcc776712015-02-17 20:18:47 -08003612 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003613 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj, isVendorClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08003614}
3615
3616CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3617 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
3618 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00003619 partial->getConflicting(), partial->getPriority().getScore(),
3620 partial->getOwnerId(), partial->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08003621}
3622
3623// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07003624
3625static const int kDumpLockRetries = 50;
3626static const int kDumpLockSleep = 60000;
3627
3628static bool tryLock(Mutex& mutex)
3629{
3630 bool locked = false;
3631 for (int i = 0; i < kDumpLockRetries; ++i) {
3632 if (mutex.tryLock() == NO_ERROR) {
3633 locked = true;
3634 break;
3635 }
3636 usleep(kDumpLockSleep);
3637 }
3638 return locked;
3639}
3640
3641status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003642 ATRACE_CALL();
3643
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003644 if (checkCallingPermission(sDumpPermission) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003645 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07003646 CameraThreadState::getCallingPid(),
3647 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003648 return NO_ERROR;
3649 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003650 bool locked = tryLock(mServiceLock);
3651 // failed to lock - CameraService is probably deadlocked
3652 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003653 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003654 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003655
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003656 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003657 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07003658
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003659 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003660 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08003661
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003662 if (locked) mServiceLock.unlock();
3663 return NO_ERROR;
3664 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003665 dprintf(fd, "\n== Service global info: ==\n\n");
3666 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003667 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07003668 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
3669 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003670 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
3671 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
3672 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003673 String8 activeClientString = mActiveClientManager.toString();
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003674 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
3675 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003676
3677 dumpEventLog(fd);
3678
3679 bool stateLocked = tryLock(mCameraStatesLock);
3680 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003681 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003682 }
3683
Emilian Peevbd8c5032018-02-14 23:05:40 +00003684 int argSize = args.size();
3685 for (int i = 0; i < argSize; i++) {
3686 if (args[i] == TagMonitor::kMonitorOption) {
3687 if (i + 1 < argSize) {
3688 mMonitorTags = String8(args[i + 1]);
3689 }
3690 break;
3691 }
3692 }
3693
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003694 for (auto& state : mCameraStates) {
3695 String8 cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003696
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003697 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003698
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003699 CameraParameters p = state.second->getShimParams();
3700 if (!p.isEmpty()) {
3701 dprintf(fd, " Camera1 API shim is using parameters:\n ");
3702 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003703 }
3704
3705 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08003706 if (clientDescriptor != nullptr) {
3707 dprintf(fd, " Device %s is open. Client instance dump:\n",
3708 cameraId.string());
3709 dprintf(fd, " Client priority score: %d state: %d\n",
3710 clientDescriptor->getPriority().getScore(),
3711 clientDescriptor->getPriority().getState());
3712 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
3713
3714 auto client = clientDescriptor->getValue();
3715 dprintf(fd, " Client package: %s\n",
3716 String8(client->getPackageName()).string());
3717
3718 client->dumpClient(fd, args);
3719 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003720 dprintf(fd, " Device %s is closed, no client instance\n",
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003721 cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003722 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003723
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003724 }
3725
3726 if (stateLocked) mCameraStatesLock.unlock();
3727
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003728 if (locked) mServiceLock.unlock();
3729
Emilian Peevf53f66e2017-04-11 14:29:43 +01003730 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003731
3732 dprintf(fd, "\n== Vendor tags: ==\n\n");
3733
3734 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
3735 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00003736 sp<VendorTagDescriptorCache> cache =
3737 VendorTagDescriptorCache::getGlobalVendorTagCache();
3738 if (cache == NULL) {
3739 dprintf(fd, "No vendor tags.\n");
3740 } else {
3741 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
3742 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003743 } else {
3744 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
3745 }
3746
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003747 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003748 dprintf(fd, "\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003749 camera3::CameraTraces::dump(fd, args);
3750
3751 // Process dump arguments, if any
3752 int n = args.size();
3753 String16 verboseOption("-v");
3754 String16 unreachableOption("--unreachable");
3755 for (int i = 0; i < n; i++) {
3756 if (args[i] == verboseOption) {
3757 // change logging level
3758 if (i + 1 >= n) continue;
3759 String8 levelStr(args[i+1]);
3760 int level = atoi(levelStr.string());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003761 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003762 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003763 } else if (args[i] == unreachableOption) {
3764 // Dump memory analysis
3765 // TODO - should limit be an argument parameter?
3766 UnreachableMemoryInfo info;
3767 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
3768 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003769 dprintf(fd, "\n== Unable to dump unreachable memory. "
3770 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003771 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003772 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003773 std::string s = info.ToString(/*log_contents*/ true);
3774 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003775 }
3776 }
3777 }
3778 return NO_ERROR;
3779}
3780
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003781void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003782 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003783
3784 Mutex::Autolock l(mLogLock);
3785 for (const auto& msg : mEventLog) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003786 dprintf(fd, " %s\n", msg.string());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003787 }
3788
3789 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003790 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003791 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003792 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003793 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003794 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003795}
3796
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003797void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003798 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003799 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
3800 if (mTorchClientMap[i] == who) {
3801 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003802 String8 cameraId = mTorchClientMap.keyAt(i);
3803 status_t res = mFlashlight->setTorchMode(cameraId, false);
3804 if (res) {
3805 ALOGE("%s: torch client died but couldn't turn off torch: "
3806 "%s (%d)", __FUNCTION__, strerror(-res), res);
3807 return;
3808 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003809 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003810 break;
3811 }
3812 }
3813}
3814
Ruben Brunkcc776712015-02-17 20:18:47 -08003815/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003816
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003817 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07003818 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
3819 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003820 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003821 // PID here is approximate and can be wrong.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003822 logClientDied(CameraThreadState::getCallingPid(), String8("Binder died unexpectedly"));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003823
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003824 // check torch client
3825 handleTorchClientBinderDied(who);
3826
3827 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08003828 if(!evictClientIdByRemote(who)) {
3829 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003830 return;
3831 }
3832
Ruben Brunkcc776712015-02-17 20:18:47 -08003833 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
3834 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003835}
3836
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003837void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003838 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08003839}
3840
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003841void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
3842 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003843 // Do not lock mServiceLock here or can get into a deadlock from
3844 // connect() -> disconnect -> updateStatus
3845
3846 auto state = getCameraState(cameraId);
3847
3848 if (state == nullptr) {
3849 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
3850 cameraId.string());
3851 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07003852 }
3853
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003854 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
3855 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3856 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3857 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
3858 return;
3859 }
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003860 bool supportsHAL3 = false;
3861 // supportsCameraApi also holds mInterfaceMutex, we can't call it in the
3862 // HIDL onStatusChanged wrapper call (we'll hold mStatusListenerLock and
3863 // mInterfaceMutex together, which can lead to deadlocks)
3864 binder::Status sRet =
3865 supportsCameraApi(String16(cameraId), hardware::ICameraService::API_VERSION_2,
3866 &supportsHAL3);
3867 if (!sRet.isOk()) {
3868 ALOGW("%s: Failed to determine if device supports HAL3 %s, supportsCameraApi call failed",
3869 __FUNCTION__, cameraId.string());
3870 return;
3871 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003872
3873 // Collect the logical cameras without holding mStatusLock in updateStatus
3874 // as that can lead to a deadlock(b/162192331).
3875 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08003876 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08003877 // of the listeners with both the mStatusLock and mStatusListenerLock held
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003878 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind, &supportsHAL3,
3879 &logicalCameraIds]
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003880 (const String8& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003881
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003882 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003883 // Update torch status if it has a flash unit.
3884 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003885 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003886 if (getTorchStatusLocked(cameraId, &torchStatus) !=
3887 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003888 TorchModeStatus newTorchStatus =
3889 status == StatusInternal::PRESENT ?
3890 TorchModeStatus::AVAILABLE_OFF :
3891 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003892 if (torchStatus != newTorchStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003893 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003894 }
3895 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003896 }
3897
3898 Mutex::Autolock lock(mStatusListenerLock);
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003899 notifyPhysicalCameraStatusLocked(mapToInterface(status), String16(cameraId),
3900 logicalCameraIds, deviceKind);
Shuzhen Wang43858162020-01-10 13:42:15 -08003901
Ruben Brunkcc776712015-02-17 20:18:47 -08003902 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003903 bool isVendorListener = listener->isVendorListener();
3904 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
3905 listener->getListenerPid(), listener->getListenerUid()) ||
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07003906 (isVendorListener && !supportsHAL3)) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003907 ALOGV("Skipping discovery callback for system-only camera/HAL1 device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003908 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003909 continue;
3910 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003911 listener->getListener()->onStatusChanged(mapToInterface(status),
Emilian Peev53722fa2019-02-22 17:47:20 -08003912 String16(cameraId));
Ruben Brunkcc776712015-02-17 20:18:47 -08003913 }
3914 });
Igor Murashkincba2c162013-03-20 15:56:31 -07003915}
3916
Shuzhen Wang695044d2020-03-06 09:02:23 -08003917void CameraService::updateOpenCloseStatus(const String8& cameraId, bool open,
3918 const String16& clientPackageName) {
3919 Mutex::Autolock lock(mStatusListenerLock);
3920
3921 for (const auto& it : mListenerList) {
3922 if (!it->isOpenCloseCallbackAllowed()) {
3923 continue;
3924 }
3925
3926 binder::Status ret;
3927 String16 cameraId64(cameraId);
3928 if (open) {
3929 ret = it->getListener()->onCameraOpened(cameraId64, clientPackageName);
3930 } else {
3931 ret = it->getListener()->onCameraClosed(cameraId64);
3932 }
3933 if (!ret.isOk()) {
3934 ALOGE("%s: Failed to trigger onCameraOpened/onCameraClosed callback: %d", __FUNCTION__,
3935 ret.exceptionCode());
3936 }
3937 }
3938}
3939
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003940template<class Func>
3941void CameraService::CameraState::updateStatus(StatusInternal status,
3942 const String8& cameraId,
3943 std::initializer_list<StatusInternal> rejectSourceStates,
3944 Func onStatusUpdatedLocked) {
3945 Mutex::Autolock lock(mStatusLock);
3946 StatusInternal oldStatus = mStatus;
3947 mStatus = status;
3948
3949 if (oldStatus == status) {
3950 return;
3951 }
3952
3953 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
3954 cameraId.string(), oldStatus, status);
3955
3956 if (oldStatus == StatusInternal::NOT_PRESENT &&
3957 (status != StatusInternal::PRESENT &&
3958 status != StatusInternal::ENUMERATING)) {
3959
3960 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
3961 __FUNCTION__);
3962 mStatus = oldStatus;
3963 return;
3964 }
3965
3966 /**
3967 * Sometimes we want to conditionally do a transition.
3968 * For example if a client disconnects, we want to go to PRESENT
3969 * only if we weren't already in NOT_PRESENT or ENUMERATING.
3970 */
3971 for (auto& rejectStatus : rejectSourceStates) {
3972 if (oldStatus == rejectStatus) {
3973 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
3974 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
3975 mStatus = oldStatus;
3976 return;
3977 }
3978 }
3979
3980 onStatusUpdatedLocked(cameraId, status);
3981}
3982
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003983status_t CameraService::getTorchStatusLocked(
3984 const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003985 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003986 if (!status) {
3987 return BAD_VALUE;
3988 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003989 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3990 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003991 // invalid camera ID or the camera doesn't have a flash unit
3992 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003993 }
3994
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003995 *status = mTorchStatusMap.valueAt(index);
3996 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003997}
3998
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003999status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004000 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004001 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
4002 if (index == NAME_NOT_FOUND) {
4003 return BAD_VALUE;
4004 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004005 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004006
4007 return OK;
4008}
4009
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004010std::list<String16> CameraService::getLogicalCameras(
4011 const String8& physicalCameraId) {
4012 std::list<String16> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08004013 Mutex::Autolock lock(mCameraStatesLock);
4014 for (const auto& state : mCameraStates) {
4015 std::vector<std::string> physicalCameraIds;
4016 if (!mCameraProviderManager->isLogicalCamera(state.first.c_str(), &physicalCameraIds)) {
4017 // This is not a logical multi-camera.
4018 continue;
4019 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004020 if (std::find(physicalCameraIds.begin(), physicalCameraIds.end(), physicalCameraId.c_str())
Shuzhen Wang43858162020-01-10 13:42:15 -08004021 == physicalCameraIds.end()) {
4022 // cameraId is not a physical camera of this logical multi-camera.
4023 continue;
4024 }
4025
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004026 retList.emplace_back(String16(state.first));
4027 }
4028 return retList;
4029}
4030
4031void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
4032 const String16& physicalCameraId, const std::list<String16>& logicalCameraIds,
4033 SystemCameraKind deviceKind) {
4034 // mStatusListenerLock is expected to be locked
4035 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08004036 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004037 // Note: we check only the deviceKind of the physical camera id
4038 // since, logical camera ids and their physical camera ids are
4039 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07004040 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
4041 listener->getListenerPid(), listener->getListenerUid())) {
4042 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004043 String8(physicalCameraId).c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07004044 continue;
4045 }
Shuzhen Wang43858162020-01-10 13:42:15 -08004046 listener->getListener()->onPhysicalCameraStatusChanged(status,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004047 logicalCameraId, physicalCameraId);
Shuzhen Wang43858162020-01-10 13:42:15 -08004048 }
4049 }
4050}
4051
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004052
Svet Ganova453d0d2018-01-11 15:37:58 -08004053void CameraService::blockClientsForUid(uid_t uid) {
4054 const auto clients = mActiveClientManager.getAll();
4055 for (auto& current : clients) {
4056 if (current != nullptr) {
4057 const auto basicClient = current->getValue();
4058 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
4059 basicClient->block();
4060 }
4061 }
4062 }
4063}
4064
Michael Grooverd1d435a2018-12-18 17:39:42 -08004065void CameraService::blockAllClients() {
4066 const auto clients = mActiveClientManager.getAll();
4067 for (auto& current : clients) {
4068 if (current != nullptr) {
4069 const auto basicClient = current->getValue();
4070 if (basicClient.get() != nullptr) {
4071 basicClient->block();
4072 }
4073 }
4074 }
4075}
4076
Svet Ganova453d0d2018-01-11 15:37:58 -08004077// NOTE: This is a remote API - make sure all args are validated
4078status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
4079 if (!checkCallingPermission(sManageCameraPermission, nullptr, nullptr)) {
4080 return PERMISSION_DENIED;
4081 }
4082 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
4083 return BAD_VALUE;
4084 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004085 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004086 return handleSetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07004087 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004088 return handleResetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07004089 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004090 return handleGetUidState(args, out, err);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004091 } else if (args.size() >= 2 && args[0] == String16("set-rotate-and-crop")) {
4092 return handleSetRotateAndCrop(args);
4093 } else if (args.size() >= 1 && args[0] == String16("get-rotate-and-crop")) {
4094 return handleGetRotateAndCrop(out);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004095 } else if (args.size() >= 2 && args[0] == String16("set-image-dump-mask")) {
4096 return handleSetImageDumpMask(args);
4097 } else if (args.size() >= 1 && args[0] == String16("get-image-dump-mask")) {
4098 return handleGetImageDumpMask(out);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004099 } else if (args.size() >= 2 && args[0] == String16("set-camera-mute")) {
4100 return handleSetCameraMute(args);
Svet Ganova453d0d2018-01-11 15:37:58 -08004101 } else if (args.size() == 1 && args[0] == String16("help")) {
4102 printHelp(out);
4103 return NO_ERROR;
4104 }
4105 printHelp(err);
4106 return BAD_VALUE;
4107}
4108
4109status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004110 String16 packageName = args[1];
4111
Svet Ganova453d0d2018-01-11 15:37:58 -08004112 bool active = false;
4113 if (args[2] == String16("active")) {
4114 active = true;
4115 } else if ((args[2] != String16("idle"))) {
4116 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
4117 return BAD_VALUE;
4118 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004119
4120 int userId = 0;
4121 if (args.size() >= 5 && args[3] == String16("--user")) {
4122 userId = atoi(String8(args[4]));
4123 }
4124
4125 uid_t uid;
4126 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
4127 return BAD_VALUE;
4128 }
4129
4130 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08004131 return NO_ERROR;
4132}
4133
4134status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004135 String16 packageName = args[1];
4136
4137 int userId = 0;
4138 if (args.size() >= 4 && args[2] == String16("--user")) {
4139 userId = atoi(String8(args[3]));
4140 }
4141
4142 uid_t uid;
4143 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004144 return BAD_VALUE;
4145 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004146
4147 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08004148 return NO_ERROR;
4149}
4150
4151status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004152 String16 packageName = args[1];
4153
4154 int userId = 0;
4155 if (args.size() >= 4 && args[2] == String16("--user")) {
4156 userId = atoi(String8(args[3]));
4157 }
4158
4159 uid_t uid;
4160 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004161 return BAD_VALUE;
4162 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004163
4164 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004165 return dprintf(out, "active\n");
4166 } else {
4167 return dprintf(out, "idle\n");
4168 }
4169}
4170
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004171status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
4172 int rotateValue = atoi(String8(args[1]));
4173 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
4174 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
4175 Mutex::Autolock lock(mServiceLock);
4176
4177 mOverrideRotateAndCropMode = rotateValue;
4178
4179 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
4180
4181 const auto clients = mActiveClientManager.getAll();
4182 for (auto& current : clients) {
4183 if (current != nullptr) {
4184 const auto basicClient = current->getValue();
4185 if (basicClient.get() != nullptr) {
4186 basicClient->setRotateAndCropOverride(rotateValue);
4187 }
4188 }
4189 }
4190
4191 return OK;
4192}
4193
4194status_t CameraService::handleGetRotateAndCrop(int out) {
4195 Mutex::Autolock lock(mServiceLock);
4196
4197 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
4198}
4199
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004200status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
4201 char *endPtr;
4202 errno = 0;
4203 String8 maskString8 = String8(args[1]);
4204 long maskValue = strtol(maskString8.c_str(), &endPtr, 10);
4205
4206 if (errno != 0) return BAD_VALUE;
4207 if (endPtr != maskString8.c_str() + maskString8.size()) return BAD_VALUE;
4208 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
4209
4210 Mutex::Autolock lock(mServiceLock);
4211
4212 mImageDumpMask = maskValue;
4213
4214 return OK;
4215}
4216
4217status_t CameraService::handleGetImageDumpMask(int out) {
4218 Mutex::Autolock lock(mServiceLock);
4219
4220 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
4221}
4222
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004223status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
4224 int muteValue = strtol(String8(args[1]), nullptr, 10);
4225 if (errno != 0) return BAD_VALUE;
4226
4227 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
4228 Mutex::Autolock lock(mServiceLock);
4229
4230 mOverrideCameraMuteMode = (muteValue == 1);
4231
4232 const auto clients = mActiveClientManager.getAll();
4233 for (auto& current : clients) {
4234 if (current != nullptr) {
4235 const auto basicClient = current->getValue();
4236 if (basicClient.get() != nullptr) {
4237 if (basicClient->supportsCameraMute()) {
4238 basicClient->setCameraMute(mOverrideCameraMuteMode);
4239 }
4240 }
4241 }
4242 }
4243
4244 return OK;
4245}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004246
Svet Ganova453d0d2018-01-11 15:37:58 -08004247status_t CameraService::printHelp(int out) {
4248 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07004249 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
4250 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
4251 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004252 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
4253 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
4254 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004255 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
4256 " Valid values 0=OFF, 1=ON for JPEG\n"
4257 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004258 " set-camera-mute <0/1> enable or disable camera muting\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08004259 " help print this message\n");
4260}
4261
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004262int32_t CameraService::updateAudioRestriction() {
4263 Mutex::Autolock lock(mServiceLock);
4264 return updateAudioRestrictionLocked();
4265}
4266
4267int32_t CameraService::updateAudioRestrictionLocked() {
4268 int32_t mode = 0;
4269 // iterate through all active client
4270 for (const auto& i : mActiveClientManager.getAll()) {
4271 const auto clientSp = i->getValue();
4272 mode |= clientSp->getAudioRestriction();
4273 }
4274
4275 bool modeChanged = (mAudioRestriction != mode);
4276 mAudioRestriction = mode;
4277 if (modeChanged) {
4278 mAppOps.setCameraAudioRestriction(mode);
4279 }
4280 return mode;
4281}
4282
Mathias Agopian65ab4712010-07-14 17:59:35 -07004283}; // namespace android