blob: 65f27b116c0a14f5a1938c2d0fdd0432f872d08c [file] [log] [blame]
Mathias Agopian65ab4712010-07-14 17:59:35 -07001/*
Ruben Brunkd1176ef2014-02-21 10:51:38 -08002 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Mathias Agopian65ab4712010-07-14 17:59:35 -070016
17#define LOG_TAG "CameraService"
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -070018#define ATRACE_TAG ATRACE_TAG_CAMERA
Iliyan Malchev8951a972011-04-14 16:55:59 -070019//#define LOG_NDEBUG 0
Mathias Agopian65ab4712010-07-14 17:59:35 -070020
Ruben Brunkcc776712015-02-17 20:18:47 -080021#include <algorithm>
22#include <climits>
Mathias Agopian65ab4712010-07-14 17:59:35 -070023#include <stdio.h>
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -080024#include <cstdlib>
Ruben Brunkcc776712015-02-17 20:18:47 -080025#include <cstring>
26#include <ctime>
27#include <string>
Mathias Agopian65ab4712010-07-14 17:59:35 -070028#include <sys/types.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080029#include <inttypes.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070030#include <pthread.h>
31
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080032#include <android/hardware/ICamera.h>
33#include <android/hardware/ICameraClient.h>
34
Alex Deymo9c2a2c22016-08-25 11:59:14 -070035#include <android-base/macros.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080036#include <android-base/parseint.h>
Jayant Chowdharyb61526c2019-05-13 19:37:42 -070037#include <android-base/stringprintf.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080038#include <binder/ActivityManager.h>
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -080039#include <binder/AppOpsManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070040#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070041#include <binder/MemoryBase.h>
42#include <binder/MemoryHeapBase.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080043#include <binder/PermissionController.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080044#include <binder/IResultReceiver.h>
Steven Moreland89a2c5c2020-01-31 15:02:25 -080045#include <binderthreadstate/CallerUtils.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070046#include <cutils/atomic.h>
Nipun Kwatrab5ca4612010-09-11 19:31:10 -070047#include <cutils/properties.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080048#include <cutils/misc.h>
Mathias Agopiandf712ea2012-02-25 18:48:35 -080049#include <gui/Surface.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070050#include <hardware/hardware.h>
Jayant Chowdharybe543d42018-08-15 13:16:14 -070051#include "hidl/HidlCameraService.h"
52#include <hidl/HidlTransportSupport.h>
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -080053#include <hwbinder/IPCThreadState.h>
Eino-Ville Talvalad89821e2016-04-20 11:23:50 -070054#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070055#include <media/AudioSystem.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080056#include <media/IMediaHTTPService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070057#include <media/mediaplayer.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070058#include <mediautils/BatteryNotifier.h>
Steven Moreland886d7322021-04-02 04:19:45 +000059#include <processinfo/ProcessInfoService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070060#include <utils/Errors.h>
61#include <utils/Log.h>
62#include <utils/String16.h>
Svet Ganov94ec46f2018-06-08 15:03:46 -070063#include <utils/SystemClock.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080064#include <utils/Trace.h>
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080065#include <utils/CallStack.h>
Chien-Yu Chen98a668f2015-12-18 14:10:33 -080066#include <private/android_filesystem_config.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080067#include <system/camera_vendor_tags.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070068#include <system/camera_metadata.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080069
Ruben Brunkb2119af2014-05-09 19:57:56 -070070#include <system/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070071
72#include "CameraService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070073#include "api1/Camera2Client.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070074#include "api2/CameraDeviceClient.h"
Igor Murashkinff3e31d2013-10-23 16:40:06 -070075#include "utils/CameraTraces.h"
Emilian Peevbd8c5032018-02-14 23:05:40 +000076#include "utils/TagMonitor.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070077#include "utils/CameraThreadState.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070078#include "utils/CameraServiceProxyWrapper.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070079
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080080namespace {
81 const char* kPermissionServiceName = "permission";
82}; // namespace anonymous
83
Mathias Agopian65ab4712010-07-14 17:59:35 -070084namespace android {
85
Jayant Chowdharyb61526c2019-05-13 19:37:42 -070086using base::StringPrintf;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080087using binder::Status;
Jayant Chowdharybe543d42018-08-15 13:16:14 -070088using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -080089using hardware::ICamera;
90using hardware::ICameraClient;
91using hardware::ICameraServiceListener;
92using hardware::camera::common::V1_0::CameraDeviceStatus;
93using hardware::camera::common::V1_0::TorchModeStatus;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080094using hardware::camera2::utils::CameraIdAndSessionConfiguration;
95using hardware::camera2::utils::ConcurrentCameraIdCombination;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080096
Mathias Agopian65ab4712010-07-14 17:59:35 -070097// ----------------------------------------------------------------------------
98// Logging support -- this is for debugging only
99// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700100volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700101
Steve Blockb8a80522011-12-20 16:23:08 +0000102#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
103#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700104
105static void setLogLevel(int level) {
106 android_atomic_write(level, &gLogLevel);
107}
108
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800109// Convenience methods for constructing binder::Status objects for error returns
110
111#define STATUS_ERROR(errorCode, errorString) \
112 binder::Status::fromServiceSpecificError(errorCode, \
113 String8::format("%s:%d: %s", __FUNCTION__, __LINE__, errorString))
114
115#define STATUS_ERROR_FMT(errorCode, errorString, ...) \
116 binder::Status::fromServiceSpecificError(errorCode, \
117 String8::format("%s:%d: " errorString, __FUNCTION__, __LINE__, \
118 __VA_ARGS__))
119
Mathias Agopian65ab4712010-07-14 17:59:35 -0700120// ----------------------------------------------------------------------------
121
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700122static const String16 sDumpPermission("android.permission.DUMP");
Svet Ganova453d0d2018-01-11 15:37:58 -0800123static const String16 sManageCameraPermission("android.permission.MANAGE_CAMERA");
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700124static const String16 sCameraPermission("android.permission.CAMERA");
125static const String16 sSystemCameraPermission("android.permission.SYSTEM_CAMERA");
126static const String16
127 sCameraSendSystemEventsPermission("android.permission.CAMERA_SEND_SYSTEM_EVENTS");
Shuzhen Wang695044d2020-03-06 09:02:23 -0800128static const String16 sCameraOpenCloseListenerPermission(
129 "android.permission.CAMERA_OPEN_CLOSE_LISTENER");
Svet Ganova453d0d2018-01-11 15:37:58 -0800130
Eino-Ville Talvala7c602c32021-03-20 17:00:18 -0700131static constexpr int32_t kVendorClientScore = resource_policy::PERCEPTIBLE_APP_ADJ;
132static constexpr int32_t kVendorClientState = ActivityManager::PROCESS_STATE_PERSISTENT_UI;
133
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800134const String8 CameraService::kOfflineDevice("offline-");
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700135
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800136CameraService::CameraService() :
137 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800138 mNumberOfCameras(0),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700139 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700140 mSoundRef(0), mInitialized(false),
141 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000142 ALOGI("CameraService started (pid=%d)", getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800143 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700144}
145
Iliyan Malchev8951a972011-04-14 16:55:59 -0700146void CameraService::onFirstRef()
147{
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -0700148
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
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -0700755void CameraService::clearCachedVariables() {
756 BasicClient::BasicClient::sCameraService = nullptr;
757}
758
Emilian Peevb91f1802021-03-23 14:50:28 -0700759int CameraService::getDeviceVersion(const String8& cameraId, int* facing, int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700760 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800761
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800762 int deviceVersion = 0;
763
Emilian Peevf53f66e2017-04-11 14:29:43 +0100764 status_t res;
765 hardware::hidl_version maxVersion{0,0};
766 res = mCameraProviderManager->getHighestSupportedVersion(cameraId.string(),
767 &maxVersion);
768 if (res != OK) return -1;
769 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800770
Emilian Peevf53f66e2017-04-11 14:29:43 +0100771 hardware::CameraInfo info;
772 if (facing) {
773 res = mCameraProviderManager->getCameraInfo(cameraId.string(), &info);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -0800774 if (res != OK) return -1;
Emilian Peevf53f66e2017-04-11 14:29:43 +0100775 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -0700776 if (orientation) {
777 *orientation = info.orientation;
778 }
Igor Murashkin634a5152013-02-20 17:15:11 -0800779 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100780
Igor Murashkin634a5152013-02-20 17:15:11 -0800781 return deviceVersion;
782}
783
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800784Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700785 switch(err) {
786 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800787 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800788 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800789 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
790 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800791 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800792 return STATUS_ERROR(ERROR_DISCONNECTED,
793 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700794 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800795 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
796 "Camera HAL encountered error %d: %s",
797 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700798 }
Igor Murashkinbfc99152013-02-27 12:55:20 -0800799}
800
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800801Status CameraService::makeClient(const sp<CameraService>& cameraService,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800802 const sp<IInterface>& cameraCb, const String16& packageName,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700803 const std::optional<String16>& featureId, const String8& cameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -0700804 int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
805 int servicePid, int deviceVersion, apiLevel effectiveApiLevel,
Ruben Brunkcc776712015-02-17 20:18:47 -0800806 /*out*/sp<BasicClient>* client) {
807
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700808 // Create CameraClient based on device version reported by the HAL.
809 switch(deviceVersion) {
810 case CAMERA_DEVICE_API_VERSION_1_0:
811 ALOGE("Camera using old HAL version: %d", deviceVersion);
812 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
813 "Camera device \"%s\" HAL version %d no longer supported",
814 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800815 break;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700816 case CAMERA_DEVICE_API_VERSION_3_0:
817 case CAMERA_DEVICE_API_VERSION_3_1:
818 case CAMERA_DEVICE_API_VERSION_3_2:
819 case CAMERA_DEVICE_API_VERSION_3_3:
820 case CAMERA_DEVICE_API_VERSION_3_4:
821 case CAMERA_DEVICE_API_VERSION_3_5:
822 case CAMERA_DEVICE_API_VERSION_3_6:
Shuzhen Wang83bff122020-11-20 15:51:39 -0800823 case CAMERA_DEVICE_API_VERSION_3_7:
Ruben Brunkcc776712015-02-17 20:18:47 -0800824 if (effectiveApiLevel == API_1) { // Camera1 API route
825 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800826 *client = new Camera2Client(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800827 cameraId, api1CameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -0700828 facing, sensorOrientation, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700829 servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800830 } else { // Camera2 API route
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800831 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
832 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800833 *client = new CameraDeviceClient(cameraService, tmp, packageName, featureId,
Emilian Peev8b64f282021-03-25 16:49:57 -0700834 cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800835 }
836 break;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700837 default:
Ruben Brunkcc776712015-02-17 20:18:47 -0800838 // Should not be reachable
839 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800840 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800841 "Camera device \"%s\" has unknown HAL version %d",
842 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800843 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800844 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800845}
846
Ruben Brunk6267b532015-04-30 17:44:07 -0700847String8 CameraService::toString(std::set<userid_t> intSet) {
848 String8 s("");
849 bool first = true;
850 for (userid_t i : intSet) {
851 if (first) {
852 s.appendFormat("%d", i);
853 first = false;
854 } else {
855 s.appendFormat(", %d", i);
856 }
857 }
858 return s;
859}
860
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800861int32_t CameraService::mapToInterface(TorchModeStatus status) {
862 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
863 switch (status) {
864 case TorchModeStatus::NOT_AVAILABLE:
865 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
866 break;
867 case TorchModeStatus::AVAILABLE_OFF:
868 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
869 break;
870 case TorchModeStatus::AVAILABLE_ON:
871 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
872 break;
873 default:
874 ALOGW("Unknown new flash status: %d", status);
875 }
876 return serviceStatus;
877}
878
879CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
880 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
881 switch (status) {
882 case CameraDeviceStatus::NOT_PRESENT:
883 serviceStatus = StatusInternal::NOT_PRESENT;
884 break;
885 case CameraDeviceStatus::PRESENT:
886 serviceStatus = StatusInternal::PRESENT;
887 break;
888 case CameraDeviceStatus::ENUMERATING:
889 serviceStatus = StatusInternal::ENUMERATING;
890 break;
891 default:
892 ALOGW("Unknown new HAL device status: %d", status);
893 }
894 return serviceStatus;
895}
896
897int32_t CameraService::mapToInterface(StatusInternal status) {
898 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
899 switch (status) {
900 case StatusInternal::NOT_PRESENT:
901 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
902 break;
903 case StatusInternal::PRESENT:
904 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
905 break;
906 case StatusInternal::ENUMERATING:
907 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
908 break;
909 case StatusInternal::NOT_AVAILABLE:
910 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
911 break;
912 case StatusInternal::UNKNOWN:
913 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
914 break;
915 default:
916 ALOGW("Unknown new internal device status: %d", status);
917 }
918 return serviceStatus;
919}
920
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800921Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -0700922 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700923
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800924 String16 internalPackageName("cameraserver");
Ruben Brunkcc776712015-02-17 20:18:47 -0800925 String8 id = String8::format("%d", cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800926 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800927 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800928 if (!(ret = connectHelper<ICameraClient,Client>(
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800929 sp<ICameraClient>{nullptr}, id, cameraId,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +0900930 internalPackageName, {}, uid, USE_CALLING_PID,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700931 API_1, /*shimUpdateOnly*/ true, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800932 ).isOk()) {
933 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
Ruben Brunkb2119af2014-05-09 19:57:56 -0700934 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800935 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700936}
937
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800938Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -0700939 /*out*/
940 CameraParameters* parameters) {
941
942 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
943
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800944 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -0700945
946 if (parameters == NULL) {
947 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800948 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -0700949 }
950
Ruben Brunkcc776712015-02-17 20:18:47 -0800951 String8 id = String8::format("%d", cameraId);
952
953 // Check if we already have parameters
954 {
955 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -0700956 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -0800957 auto cameraState = getCameraState(id);
958 if (cameraState == nullptr) {
959 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800960 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
961 "Invalid camera ID: %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -0800962 }
963 CameraParameters p = cameraState->getShimParams();
964 if (!p.isEmpty()) {
965 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800966 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700967 }
968 }
969
Jayant Chowdhary12361932018-08-27 14:46:13 -0700970 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -0800971 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -0700972 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800973 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800974 // Error already logged by callee
975 return ret;
976 }
977
978 // Check for parameters again
979 {
980 // Scope for service lock
981 Mutex::Autolock lock(mServiceLock);
982 auto cameraState = getCameraState(id);
983 if (cameraState == nullptr) {
984 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800985 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
986 "Invalid camera ID: %s", id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -0700987 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800988 CameraParameters p = cameraState->getShimParams();
989 if (!p.isEmpty()) {
990 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800991 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700992 }
993 }
994
Ruben Brunkcc776712015-02-17 20:18:47 -0800995 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
996 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800997 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -0700998}
999
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001000// Can camera service trust the caller based on the calling UID?
1001static bool isTrustedCallingUid(uid_t uid) {
1002 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001003 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001004 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001005 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001006 return true;
1007 default:
1008 return false;
1009 }
1010}
1011
Nicholas Sauera3620332019-04-03 14:05:17 -07001012static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1013 PermissionController pc;
1014 uid = pc.getPackageUid(packageName, 0);
1015 if (uid <= 0) {
1016 ALOGE("Unknown package: '%s'", String8(packageName).string());
1017 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
1018 return BAD_VALUE;
1019 }
1020
1021 if (userId < 0) {
1022 ALOGE("Invalid user: %d", userId);
1023 dprintf(err, "Invalid user: %d\n", userId);
1024 return BAD_VALUE;
1025 }
1026
1027 uid = multiuser_get_uid(userId, uid);
1028 return NO_ERROR;
1029}
1030
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001031Status CameraService::validateConnectLocked(const String8& cameraId,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001032 const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
1033 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001034
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001035#ifdef __BRILLO__
1036 UNUSED(clientName8);
1037 UNUSED(clientUid);
1038 UNUSED(clientPid);
1039 UNUSED(originalClientPid);
1040#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001041 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1042 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001043 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001044 return allowed;
1045 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001046#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001047
Jayant Chowdhary12361932018-08-27 14:46:13 -07001048 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001049
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001050 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001051 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1052 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001053 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1054 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001055 }
1056
Ruben Brunkcc776712015-02-17 20:18:47 -08001057 if (getCameraState(cameraId) == nullptr) {
1058 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1059 cameraId.string());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001060 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1061 "No camera device with ID \"%s\" available", cameraId.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001062 }
1063
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001064 status_t err = checkIfDeviceIsUsable(cameraId);
1065 if (err != NO_ERROR) {
1066 switch(err) {
1067 case -ENODEV:
1068 case -EBUSY:
1069 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1070 "No camera device with ID \"%s\" currently available", cameraId.string());
1071 default:
1072 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1073 "Unknown error connecting to ID \"%s\"", cameraId.string());
1074 }
1075 }
1076 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001077}
1078
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001079Status CameraService::validateClientPermissionsLocked(const String8& cameraId,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001080 const String8& clientName8, int& clientUid, int& clientPid,
1081 /*out*/int& originalClientPid) const {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001082 int callingPid = CameraThreadState::getCallingPid();
1083 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001084
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001085 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001086 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001087 clientUid = callingUid;
1088 } else if (!isTrustedCallingUid(callingUid)) {
1089 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1090 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001091 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1092 "Untrusted caller (calling PID %d, UID %d) trying to "
1093 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1094 callingPid, callingUid, cameraId.string(),
1095 clientName8.string(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001096 }
1097
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001098 // Check if we can trust clientPid
1099 if (clientPid == USE_CALLING_PID) {
1100 clientPid = callingPid;
1101 } else if (!isTrustedCallingUid(callingUid)) {
1102 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1103 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001104 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1105 "Untrusted caller (calling PID %d, UID %d) trying to "
1106 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1107 callingPid, callingUid, cameraId.string(),
1108 clientName8.string(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001109 }
1110
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001111 if (shouldRejectSystemCameraConnection(cameraId)) {
1112 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1113 cameraId.c_str());
1114 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
1115 "available", cameraId.string());
1116 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001117 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1118 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1119 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
1120 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
1121 "found while trying to query device kind", cameraId.string());
1122
1123 }
1124
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001125 // If it's not calling from cameraserver, check the permission if the
1126 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1127 // android.permission.SYSTEM_CAMERA for system only camera devices).
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001128 if (callingPid != getpid() &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001129 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001130 !checkPermission(sCameraPermission, clientPid, clientUid)) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001131 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001132 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1133 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
1134 clientName8.string(), clientUid, clientPid, cameraId.string());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001135 }
1136
Svet Ganova453d0d2018-01-11 15:37:58 -08001137 // Make sure the UID is in an active state to use the camera
Svet Ganov7b4ab782018-03-25 12:48:10 -07001138 if (!mUidPolicy->isUidActive(callingUid, String16(clientName8))) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001139 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001140 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1141 clientPid, clientUid);
1142 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001143 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1144 "calling UID %d proc state %" PRId32 ")",
1145 clientName8.string(), clientUid, clientPid, cameraId.string(),
1146 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001147 }
1148
Michael Grooverd1d435a2018-12-18 17:39:42 -08001149 // If sensor privacy is enabled then prevent access to the camera
1150 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1151 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1152 return STATUS_ERROR_FMT(ERROR_DISABLED,
1153 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
1154 "is enabled", clientName8.string(), clientUid, clientPid, cameraId.string());
1155 }
1156
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001157 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1158 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001159 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001160 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001161
Ruben Brunk6267b532015-04-30 17:44:07 -07001162 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001163
Ruben Brunka8ca9152015-04-07 14:23:40 -07001164 // Only allow clients who are being used by the current foreground device user, unless calling
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001165 // from our own process OR the caller is using the cameraserver's HIDL interface.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001166 if (getCurrentServingCall() != BinderCallType::HWBINDER && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001167 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001168 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1169 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
1170 toString(mAllowedUsers).string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001171 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1172 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
1173 clientUserId, cameraId.string());
Ruben Brunk36597b22015-03-20 22:15:57 -07001174 }
1175
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001176 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001177}
1178
1179status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
1180 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001181 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001182 if (cameraState == nullptr) {
1183 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1184 cameraId.string());
1185 return -ENODEV;
1186 }
1187
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001188 StatusInternal currentStatus = cameraState->getStatus();
1189 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001190 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
1191 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001192 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001193 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001194 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
1195 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001196 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001197 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001198
Ruben Brunkcc776712015-02-17 20:18:47 -08001199 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001200}
1201
Ruben Brunkcc776712015-02-17 20:18:47 -08001202void CameraService::finishConnectLocked(const sp<BasicClient>& client,
1203 const CameraService::DescriptorPtr& desc) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001204
Ruben Brunkcc776712015-02-17 20:18:47 -08001205 // Make a descriptor for the incoming client
1206 auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
1207 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1208
1209 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
1210 String8(client->getPackageName()));
1211
1212 if (evicted.size() > 0) {
1213 // This should never happen - clients should already have been removed in disconnect
1214 for (auto& i : evicted) {
1215 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
1216 __FUNCTION__, i->getKey().string());
1217 }
1218
1219 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1220 __FUNCTION__);
1221 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001222
1223 // And register a death notification for the client callback. Do
1224 // this last to avoid Binder policy where a nested Binder
1225 // transaction might be pre-empted to service the client death
1226 // notification if the client process dies before linkToDeath is
1227 // invoked.
1228 sp<IBinder> remoteCallback = client->getRemote();
1229 if (remoteCallback != nullptr) {
1230 remoteCallback->linkToDeath(this);
1231 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001232}
1233
1234status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
1235 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
1236 /*out*/
1237 sp<BasicClient>* client,
1238 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001239 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001240 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001241 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001242 DescriptorPtr clientDescriptor;
1243 {
1244 if (effectiveApiLevel == API_1) {
1245 // If we are using API1, any existing client for this camera ID with the same remote
1246 // should be returned rather than evicted to allow MediaRecorder to work properly.
1247
1248 auto current = mActiveClientManager.get(cameraId);
1249 if (current != nullptr) {
1250 auto clientSp = current->getValue();
1251 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001252 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
1253 ALOGW("CameraService connect called from same client, but with a different"
1254 " API level, evicting prior client...");
1255 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001256 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001257 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001258 *client = clientSp;
1259 return NO_ERROR;
1260 }
1261 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001262 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001263 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001264
Ruben Brunkcc776712015-02-17 20:18:47 -08001265 // Get current active client PIDs
1266 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1267 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001268
Emilian Peev8131a262017-02-01 12:33:43 +00001269 std::vector<int> priorityScores(ownerPids.size());
1270 std::vector<int> states(ownerPids.size());
Igor Murashkine6800ce2013-03-04 17:25:57 -08001271
Emilian Peev8131a262017-02-01 12:33:43 +00001272 // Get priority scores of all active PIDs
1273 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1274 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1275 /*out*/&priorityScores[0]);
1276 if (err != OK) {
1277 ALOGE("%s: Priority score query failed: %d",
1278 __FUNCTION__, err);
1279 return err;
1280 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001281
Ruben Brunkcc776712015-02-17 20:18:47 -08001282 // Update all active clients' priorities
Emilian Peev8131a262017-02-01 12:33:43 +00001283 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
Ruben Brunkcc776712015-02-17 20:18:47 -08001284 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
Emilian Peev8131a262017-02-01 12:33:43 +00001285 pidToPriorityMap.emplace(ownerPids[i],
Jayant Chowdharyc578a502019-05-08 10:57:54 -07001286 resource_policy::ClientPriority(priorityScores[i], states[i],
1287 /* isVendorClient won't get copied over*/ false));
Ruben Brunkcc776712015-02-17 20:18:47 -08001288 }
1289 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001290
Ruben Brunkcc776712015-02-17 20:18:47 -08001291 // Get state for the given cameraId
1292 auto state = getCameraState(cameraId);
1293 if (state == nullptr) {
1294 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1295 clientPid, cameraId.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001296 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001297 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001298 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001299
1300 // Make descriptor for incoming client
Shuzhen Wang2db86ff2018-04-25 01:11:17 +00001301 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001302 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1303 state->getConflicting(),
Emilian Peev8131a262017-02-01 12:33:43 +00001304 priorityScores[priorityScores.size() - 1],
1305 clientPid,
1306 states[states.size() - 1]);
Ruben Brunkcc776712015-02-17 20:18:47 -08001307
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001308 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1309
Ruben Brunkcc776712015-02-17 20:18:47 -08001310 // Find clients that would be evicted
1311 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1312
1313 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1314 // background, so we cannot do evictions
1315 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1316 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1317 " priority).", clientPid);
1318
1319 sp<BasicClient> clientSp = clientDescriptor->getValue();
1320 String8 curTime = getFormattedCurrentTime();
1321 auto incompatibleClients =
1322 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1323
1324 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Emilian Peev8131a262017-02-01 12:33:43 +00001325 "(PID %d, score %d state %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001326 cameraId.string(), packageName.string(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001327 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001328
1329 for (auto& i : incompatibleClients) {
1330 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001331 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
1332 i->getKey().string(),
1333 String8{i->getValue()->getPackageName()}.string(),
1334 i->getOwnerId(), i->getPriority().getScore(),
1335 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001336 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00001337 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(),
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001338 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001339 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001340 }
1341
1342 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001343 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001344 mEventLog.add(msg);
1345
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001346 auto current = mActiveClientManager.get(cameraId);
1347 if (current != nullptr) {
1348 return -EBUSY; // CAMERA_IN_USE
1349 } else {
1350 return -EUSERS; // MAX_CAMERAS_IN_USE
1351 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001352 }
1353
1354 for (auto& i : evicted) {
1355 sp<BasicClient> clientSp = i->getValue();
1356 if (clientSp.get() == nullptr) {
1357 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1358
1359 // TODO: Remove this
1360 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1361 __FUNCTION__);
1362 mActiveClientManager.remove(i);
1363 continue;
1364 }
1365
1366 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1367 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001368 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001369
Ruben Brunkcc776712015-02-17 20:18:47 -08001370 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001371 logEvent(String8::format("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00001372 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1373 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001374 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
Emilian Peev8131a262017-02-01 12:33:43 +00001375 i->getOwnerId(), i->getPriority().getScore(),
1376 i->getPriority().getState(), cameraId.string(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001377 packageName.string(), clientPid, clientPriority.getScore(),
1378 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08001379
1380 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001381 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001382 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001383 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001384 }
1385
Ruben Brunkcc776712015-02-17 20:18:47 -08001386 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1387 // other clients from connecting in mServiceLockWrapper if held
1388 mServiceLock.unlock();
1389
1390 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07001391 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001392
1393 // Destroy evicted clients
1394 for (auto& i : evictedClients) {
1395 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001396 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001397 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001398
Jayant Chowdhary12361932018-08-27 14:46:13 -07001399 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08001400
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001401 for (const auto& i : evictedClients) {
1402 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1403 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1404 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1405 if (ret == TIMED_OUT) {
1406 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1407 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1408 mActiveClientManager.toString().string());
1409 return -EBUSY;
1410 }
1411 if (ret != NO_ERROR) {
1412 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1413 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1414 ret, mActiveClientManager.toString().string());
1415 return ret;
1416 }
1417 }
1418
1419 evictedClients.clear();
1420
Ruben Brunkcc776712015-02-17 20:18:47 -08001421 // Once clients have been disconnected, relock
1422 mServiceLock.lock();
1423
1424 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1425 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1426 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001427 }
1428
Ruben Brunkcc776712015-02-17 20:18:47 -08001429 *partial = clientDescriptor;
1430 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001431}
1432
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001433Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001434 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001435 int api1CameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001436 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001437 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001438 int clientPid,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001439 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001440 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001441
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001442 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001443 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001444
1445 String8 id = cameraIdIntToStr(api1CameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001446 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001447 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001448 clientPackageName, {}, clientUid, clientPid, API_1,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001449 /*shimUpdateOnly*/ false, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001450
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001451 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001452 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001453 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001454 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001455 }
1456
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001457 *device = client;
1458 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001459}
1460
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001461bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
1462 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001463 // If the client is not a vendor client, don't add listener if
1464 // a) the camera is a publicly hidden secure camera OR
1465 // b) the camera is a system only camera and the client doesn't
1466 // have android.permission.SYSTEM_CAMERA permissions.
1467 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
1468 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1469 !hasPermissionsForSystemCamera(clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001470 return true;
1471 }
1472 return false;
1473}
1474
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001475bool CameraService::shouldRejectSystemCameraConnection(const String8& cameraId) const {
1476 // Rules for rejection:
1477 // 1) If cameraserver tries to access this camera device, accept the
1478 // connection.
1479 // 2) The camera device is a publicly hidden secure camera device AND some
1480 // component is trying to access it on a non-hwbinder thread (generally a non HAL client),
1481 // reject it.
1482 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
1483 // and the serving thread is a non hwbinder thread, the client must have
1484 // android.permission.SYSTEM_CAMERA permissions to connect.
1485
1486 int cPid = CameraThreadState::getCallingPid();
1487 int cUid = CameraThreadState::getCallingUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001488 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
1489 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001490 // This isn't a known camera ID, so it's not a system camera
1491 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
1492 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001493 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001494
1495 // (1) Cameraserver trying to connect, accept.
1496 if (CameraThreadState::getCallingPid() == getpid()) {
1497 return false;
1498 }
1499 // (2)
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001500 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001501 systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
1502 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
1503 return true;
1504 }
1505 // (3) Here we only check for permissions if it is a system only camera device. This is since
1506 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
1507 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
1508 // same behavior for system camera devices.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001509 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001510 systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1511 !hasPermissionsForSystemCamera(cPid, cUid)) {
1512 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
1513 cameraId.c_str());
1514 return true;
1515 }
1516
1517 return false;
1518}
1519
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001520Status CameraService::connectDevice(
1521 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001522 const String16& cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001523 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001524 const std::optional<String16>& clientFeatureId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001525 int clientUid,
1526 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001527 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001528
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001529 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001530 Status ret = Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001531 String8 id = String8(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001532 sp<CameraDeviceClient> client = nullptr;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001533 String16 clientPackageNameAdj = clientPackageName;
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001534
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001535 if (getCurrentServingCall() == BinderCallType::HWBINDER) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001536 std::string vendorClient =
1537 StringPrintf("vendor.client.pid<%d>", CameraThreadState::getCallingPid());
1538 clientPackageNameAdj = String16(vendorClient.c_str());
1539 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001540 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001541 /*api1CameraId*/-1, clientPackageNameAdj, clientFeatureId,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001542 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08001543
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001544 if(!ret.isOk()) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001545 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageNameAdj),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001546 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001547 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001548 }
1549
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001550 *device = client;
1551 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001552}
1553
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001554template<class CALLBACK, class CLIENT>
1555Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001556 int api1CameraId, const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001557 const std::optional<String16>& clientFeatureId, int clientUid, int clientPid,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001558 apiLevel effectiveApiLevel, bool shimUpdateOnly,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001559 /*out*/sp<CLIENT>& device) {
1560 binder::Status ret = binder::Status::ok();
1561
1562 String8 clientName8(clientPackageName);
1563
1564 int originalClientPid = 0;
1565
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001566 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001567 "Camera API version %d", clientPid, clientName8.string(), cameraId.string(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001568 static_cast<int>(effectiveApiLevel));
1569
Shuzhen Wang316781a2020-08-18 18:11:01 -07001570 nsecs_t openTimeNs = systemTime();
1571
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001572 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001573 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07001574 int orientation = 0;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001575 bool isNdk = (clientPackageName.size() == 0);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001576 {
1577 // Acquire mServiceLock and prevent other clients from connecting
1578 std::unique_ptr<AutoConditionLock> lock =
1579 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1580
1581 if (lock == nullptr) {
1582 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
1583 , clientPid);
1584 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1585 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
1586 cameraId.string(), clientName8.string(), clientPid);
1587 }
1588
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07001589 // Enforce client permissions and do basic validity checks
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001590 if(!(ret = validateConnectLocked(cameraId, clientName8,
1591 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
1592 return ret;
1593 }
1594
1595 // Check the shim parameters after acquiring lock, if they have already been updated and
1596 // we were doing a shim update, return immediately
1597 if (shimUpdateOnly) {
1598 auto cameraState = getCameraState(cameraId);
1599 if (cameraState != nullptr) {
1600 if (!cameraState->getShimParams().isEmpty()) return ret;
1601 }
1602 }
1603
1604 status_t err;
1605
1606 sp<BasicClient> clientTmp = nullptr;
1607 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
1608 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
1609 IInterface::asBinder(cameraCb), clientName8, /*out*/&clientTmp,
1610 /*out*/&partial)) != NO_ERROR) {
1611 switch (err) {
1612 case -ENODEV:
1613 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1614 "No camera device with ID \"%s\" currently available",
1615 cameraId.string());
1616 case -EBUSY:
1617 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1618 "Higher-priority client using camera, ID \"%s\" currently unavailable",
1619 cameraId.string());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001620 case -EUSERS:
1621 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1622 "Too many cameras already open, cannot open camera \"%s\"",
1623 cameraId.string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001624 default:
1625 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1626 "Unexpected error %s (%d) opening camera \"%s\"",
1627 strerror(-err), err, cameraId.string());
1628 }
1629 }
1630
1631 if (clientTmp.get() != nullptr) {
1632 // Handle special case for API1 MediaRecorder where the existing client is returned
1633 device = static_cast<CLIENT*>(clientTmp.get());
1634 return ret;
1635 }
1636
1637 // give flashlight a chance to close devices if necessary.
1638 mFlashlight->prepareDeviceOpen(cameraId);
1639
Emilian Peevb91f1802021-03-23 14:50:28 -07001640 int deviceVersion = getDeviceVersion(cameraId, /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08001641 if (facing == -1) {
1642 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.string());
1643 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1644 "Unable to get camera device \"%s\" facing", cameraId.string());
1645 }
1646
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001647 sp<BasicClient> tmp = nullptr;
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001648 if(!(ret = makeClient(this, cameraCb, clientPackageName, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07001649 cameraId, api1CameraId, facing, orientation,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001650 clientPid, clientUid, getpid(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001651 deviceVersion, effectiveApiLevel,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001652 /*out*/&tmp)).isOk()) {
1653 return ret;
1654 }
1655 client = static_cast<CLIENT*>(tmp.get());
1656
1657 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
1658 __FUNCTION__);
1659
Emilian Peevbd8c5032018-02-14 23:05:40 +00001660 err = client->initialize(mCameraProviderManager, mMonitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001661 if (err != OK) {
1662 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001663 // Errors could be from the HAL module open call or from AppOpsManager
1664 switch(err) {
1665 case BAD_VALUE:
1666 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1667 "Illegal argument to HAL module for camera \"%s\"", cameraId.string());
1668 case -EBUSY:
1669 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1670 "Camera \"%s\" is already open", cameraId.string());
1671 case -EUSERS:
1672 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1673 "Too many cameras already open, cannot open camera \"%s\"",
1674 cameraId.string());
1675 case PERMISSION_DENIED:
1676 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1677 "No permission to open camera \"%s\"", cameraId.string());
1678 case -EACCES:
1679 return STATUS_ERROR_FMT(ERROR_DISABLED,
1680 "Camera \"%s\" disabled by policy", cameraId.string());
1681 case -ENODEV:
1682 default:
1683 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1684 "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
1685 strerror(-err), err);
1686 }
1687 }
1688
1689 // Update shim paremeters for legacy clients
1690 if (effectiveApiLevel == API_1) {
1691 // Assume we have always received a Client subclass for API1
1692 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
1693 String8 rawParams = shimClient->getParameters();
1694 CameraParameters params(rawParams);
1695
1696 auto cameraState = getCameraState(cameraId);
1697 if (cameraState != nullptr) {
1698 cameraState->setShimParams(params);
1699 } else {
1700 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
1701 __FUNCTION__, cameraId.string());
1702 }
1703 }
1704
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001705 // Set rotate-and-crop override behavior
1706 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
1707 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
Emilian Peevb91f1802021-03-23 14:50:28 -07001708 } else if (CameraServiceProxyWrapper::isRotateAndCropOverrideNeeded(clientPackageName,
1709 orientation, facing)) {
1710 client->setRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_90);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001711 }
1712
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08001713 // Set camera muting behavior
1714 if (client->supportsCameraMute()) {
Evan Severson09ab4002021-02-10 14:15:19 -08001715 bool isCameraPrivacyEnabled =
1716 mSensorPrivacyPolicy->isCameraPrivacyEnabled(multiuser_get_user_id(clientUid));
1717 client->setCameraMute(mOverrideCameraMuteMode || isCameraPrivacyEnabled);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08001718 }
1719
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001720 if (shimUpdateOnly) {
1721 // If only updating legacy shim parameters, immediately disconnect client
1722 mServiceLock.unlock();
1723 client->disconnect();
1724 mServiceLock.lock();
1725 } else {
1726 // Otherwise, add client to active clients list
1727 finishConnectLocked(client, partial);
1728 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001729
1730 client->setImageDumpMask(mImageDumpMask);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001731 } // lock is destroyed, allow further connect calls
1732
1733 // Important: release the mutex here so the client can call back into the service from its
1734 // destructor (can be at the end of the call)
1735 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001736
1737 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
1738 CameraServiceProxyWrapper::logOpen(cameraId, facing, clientPackageName,
1739 effectiveApiLevel, isNdk, openLatencyMs);
1740
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001741 return ret;
1742}
1743
Emilian Peevb2bc5a42019-11-20 16:02:14 -08001744status_t CameraService::addOfflineClient(String8 cameraId, sp<BasicClient> offlineClient) {
1745 if (offlineClient.get() == nullptr) {
1746 return BAD_VALUE;
1747 }
1748
1749 {
1750 // Acquire mServiceLock and prevent other clients from connecting
1751 std::unique_ptr<AutoConditionLock> lock =
1752 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1753
1754 if (lock == nullptr) {
1755 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
1756 , __FUNCTION__, offlineClient->getClientPid());
1757 return TIMED_OUT;
1758 }
1759
1760 auto onlineClientDesc = mActiveClientManager.get(cameraId);
1761 if (onlineClientDesc.get() == nullptr) {
1762 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
1763 cameraId.c_str());
1764 return BAD_VALUE;
1765 }
1766
1767 // Offline clients do not evict or conflict with other online devices. Resource sharing
1768 // conflicts are handled by the camera provider which will either succeed or fail before
1769 // reaching this method.
1770 const auto& onlinePriority = onlineClientDesc->getPriority();
1771 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
1772 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
1773 /*conflictingKeys*/ std::set<String8>(), onlinePriority.getScore(),
1774 onlineClientDesc->getOwnerId(), onlinePriority.getState());
1775
1776 // Allow only one offline device per camera
1777 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
1778 if (!incompatibleClients.empty()) {
1779 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
1780 return BAD_VALUE;
1781 }
1782
1783 auto err = offlineClient->initialize(mCameraProviderManager, mMonitorTags);
1784 if (err != OK) {
1785 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
1786 return err;
1787 }
1788
1789 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
1790 if (evicted.size() > 0) {
1791 for (auto& i : evicted) {
1792 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
1793 __FUNCTION__, i->getKey().string());
1794 }
1795
1796 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
1797 "properly", __FUNCTION__);
1798
1799 return BAD_VALUE;
1800 }
1801
1802 logConnectedOffline(offlineClientDesc->getKey(),
1803 static_cast<int>(offlineClientDesc->getOwnerId()),
1804 String8(offlineClient->getPackageName()));
1805
1806 sp<IBinder> remoteCallback = offlineClient->getRemote();
1807 if (remoteCallback != nullptr) {
1808 remoteCallback->linkToDeath(this);
1809 }
1810 } // lock is destroyed, allow further connect calls
1811
1812 return OK;
1813}
1814
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001815Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001816 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001817 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001818
1819 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07001820 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001821 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001822 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1823 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001824 }
1825
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001826 String8 id = String8(cameraId.string());
Jayant Chowdhary12361932018-08-27 14:46:13 -07001827 int uid = CameraThreadState::getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001828
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07001829 if (shouldRejectSystemCameraConnection(id)) {
1830 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
1831 " for system only device %s: ", id.string());
1832 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001833 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08001834 auto state = getCameraState(id);
1835 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001836 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001837 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1838 "Camera ID \"%s\" is a not valid camera ID", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001839 }
1840
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001841 StatusInternal cameraStatus = state->getStatus();
1842 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001843 cameraStatus != StatusInternal::NOT_AVAILABLE) {
1844 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001845 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1846 "Camera ID \"%s\" is a not valid camera ID", id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001847 }
1848
1849 {
1850 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001851 TorchModeStatus status;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001852 status_t err = getTorchStatusLocked(id, &status);
1853 if (err != OK) {
1854 if (err == NAME_NOT_FOUND) {
1855 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1856 "Camera \"%s\" does not have a flash unit", id.string());
1857 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001858 ALOGE("%s: getting current torch status failed for camera %s",
1859 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001860 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1861 "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
1862 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001863 }
1864
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001865 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001866 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001867 ALOGE("%s: torch mode of camera %s is not available because "
1868 "camera is in use", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001869 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1870 "Torch for camera \"%s\" is not available due to an existing camera user",
1871 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001872 } else {
1873 ALOGE("%s: torch mode of camera %s is not available due to "
1874 "insufficient resources", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001875 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1876 "Torch for camera \"%s\" is not available due to insufficient resources",
1877 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001878 }
1879 }
1880 }
1881
Ruben Brunk99e69712015-05-26 17:25:07 -07001882 {
1883 // Update UID map - this is used in the torch status changed callbacks, so must be done
1884 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07001885 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -07001886 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
1887 mTorchUidMap[id].first = uid;
1888 mTorchUidMap[id].second = uid;
1889 } else {
1890 // Set the pending UID
1891 mTorchUidMap[id].first = uid;
1892 }
1893 }
1894
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001895 status_t err = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07001896
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001897 if (err != OK) {
1898 int32_t errorCode;
1899 String8 msg;
1900 switch (err) {
1901 case -ENOSYS:
1902 msg = String8::format("Camera \"%s\" has no flashlight",
1903 id.string());
1904 errorCode = ERROR_ILLEGAL_ARGUMENT;
1905 break;
1906 default:
1907 msg = String8::format(
1908 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
1909 id.string(), enabled, strerror(-err), err);
1910 errorCode = ERROR_INVALID_OPERATION;
1911 }
1912 ALOGE("%s: %s", __FUNCTION__, msg.string());
1913 return STATUS_ERROR(errorCode, msg.string());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001914 }
1915
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001916 {
1917 // update the link to client's death
1918 Mutex::Autolock al(mTorchClientMapMutex);
1919 ssize_t index = mTorchClientMap.indexOfKey(id);
1920 if (enabled) {
1921 if (index == NAME_NOT_FOUND) {
1922 mTorchClientMap.add(id, clientBinder);
1923 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07001924 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001925 mTorchClientMap.replaceValueAt(index, clientBinder);
1926 }
1927 clientBinder->linkToDeath(this);
1928 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07001929 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001930 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001931 }
1932
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07001933 int clientPid = CameraThreadState::getCallingPid();
1934 const char *id_cstr = id.c_str();
1935 const char *torchState = enabled ? "on" : "off";
1936 ALOGI("Torch for camera id %s turned %s for client PID %d", id_cstr, torchState, clientPid);
1937 logTorchEvent(id_cstr, torchState , clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001938 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001939}
1940
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001941Status CameraService::notifySystemEvent(int32_t eventId,
1942 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001943 const int pid = CameraThreadState::getCallingPid();
1944 const int selfPid = getpid();
1945
1946 // Permission checks
1947 if (pid != selfPid) {
1948 // Ensure we're being called by system_server, or similar process with
1949 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001950 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001951 const int uid = CameraThreadState::getCallingUid();
1952 ALOGE("Permission Denial: cannot send updates to camera service about system"
1953 " events from pid=%d, uid=%d", pid, uid);
1954 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09001955 "No permission to send updates to camera service about system events"
1956 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001957 }
1958 }
1959
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001960 ATRACE_CALL();
1961
Ruben Brunk36597b22015-03-20 22:15:57 -07001962 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001963 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001964 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07001965 // from a system server crash
1966 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08001967 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001968 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07001969 break;
1970 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001971 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07001972 default: {
1973 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
1974 eventId);
1975 break;
1976 }
1977 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001978 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07001979}
1980
Emilian Peev53722fa2019-02-22 17:47:20 -08001981void CameraService::notifyMonitoredUids() {
1982 Mutex::Autolock lock(mStatusListenerLock);
1983
1984 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001985 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Emilian Peev53722fa2019-02-22 17:47:20 -08001986 if (!ret.isOk()) {
1987 ALOGE("%s: Failed to trigger permission callback: %d", __FUNCTION__,
1988 ret.exceptionCode());
1989 }
1990 }
1991}
1992
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08001993Status CameraService::notifyDeviceStateChange(int64_t newState) {
1994 const int pid = CameraThreadState::getCallingPid();
1995 const int selfPid = getpid();
1996
1997 // Permission checks
1998 if (pid != selfPid) {
1999 // Ensure we're being called by system_server, or similar process with
2000 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002001 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002002 const int uid = CameraThreadState::getCallingUid();
2003 ALOGE("Permission Denial: cannot send updates to camera service about device"
2004 " state changes from pid=%d, uid=%d", pid, uid);
2005 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2006 "No permission to send updates to camera service about device state"
2007 " changes from pid=%d, uid=%d", pid, uid);
2008 }
2009 }
2010
2011 ATRACE_CALL();
2012
2013 using hardware::camera::provider::V2_5::DeviceState;
2014 hardware::hidl_bitfield<DeviceState> newDeviceState{};
2015 if (newState & ICameraService::DEVICE_STATE_BACK_COVERED) {
2016 newDeviceState |= DeviceState::BACK_COVERED;
2017 }
2018 if (newState & ICameraService::DEVICE_STATE_FRONT_COVERED) {
2019 newDeviceState |= DeviceState::FRONT_COVERED;
2020 }
2021 if (newState & ICameraService::DEVICE_STATE_FOLDED) {
2022 newDeviceState |= DeviceState::FOLDED;
2023 }
2024 // Only map vendor bits directly
2025 uint64_t vendorBits = static_cast<uint64_t>(newState) & 0xFFFFFFFF00000000l;
2026 newDeviceState |= vendorBits;
2027
2028 ALOGV("%s: New device state 0x%" PRIx64, __FUNCTION__, newDeviceState);
2029 Mutex::Autolock l(mServiceLock);
2030 mCameraProviderManager->notifyDeviceStateChange(newDeviceState);
2031
2032 return Status::ok();
2033}
2034
Emilian Peev8b64f282021-03-25 16:49:57 -07002035Status CameraService::notifyDisplayConfigurationChange() {
2036 ATRACE_CALL();
2037 const int callingPid = CameraThreadState::getCallingPid();
2038 const int selfPid = getpid();
2039
2040 // Permission checks
2041 if (callingPid != selfPid) {
2042 // Ensure we're being called by system_server, or similar process with
2043 // permissions to notify the camera service about system events
2044 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
2045 const int uid = CameraThreadState::getCallingUid();
2046 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
2047 " changes from pid=%d, uid=%d", callingPid, uid);
2048 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2049 "No permission to send updates to camera service about orientation"
2050 " changes from pid=%d, uid=%d", callingPid, uid);
2051 }
2052 }
2053
2054 Mutex::Autolock lock(mServiceLock);
2055
2056 // Don't do anything if rotate-and-crop override via cmd is active
2057 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
2058
2059 const auto clients = mActiveClientManager.getAll();
2060 for (auto& current : clients) {
2061 if (current != nullptr) {
2062 const auto basicClient = current->getValue();
2063 if (basicClient.get() != nullptr) {
2064 if (CameraServiceProxyWrapper::isRotateAndCropOverrideNeeded(
2065 basicClient->getPackageName(), basicClient->getCameraOrientation(),
2066 basicClient->getCameraFacing())) {
2067 basicClient->setRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_90);
2068 } else {
2069 basicClient->setRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE);
2070 }
2071 }
2072 }
2073 }
2074
2075 return Status::ok();
2076}
2077
2078Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002079 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
2080 ATRACE_CALL();
2081 if (!concurrentCameraIds) {
2082 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
2083 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
2084 }
2085
2086 if (!mInitialized) {
2087 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2088 return STATUS_ERROR(ERROR_DISCONNECTED,
2089 "Camera subsystem is not available");
2090 }
2091 // First call into the provider and get the set of concurrent camera
2092 // combinations
2093 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07002094 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002095 for (auto &combination : concurrentCameraCombinations) {
2096 std::vector<std::string> validCombination;
2097 for (auto &cameraId : combination) {
2098 // if the camera state is not present, skip
2099 String8 cameraIdStr(cameraId.c_str());
2100 auto state = getCameraState(cameraIdStr);
2101 if (state == nullptr) {
2102 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
2103 continue;
2104 }
2105 StatusInternal status = state->getStatus();
2106 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
2107 continue;
2108 }
2109 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
2110 continue;
2111 }
2112 validCombination.push_back(cameraId);
2113 }
2114 if (validCombination.size() != 0) {
2115 concurrentCameraIds->push_back(std::move(validCombination));
2116 }
2117 }
2118 return Status::ok();
2119}
2120
2121Status CameraService::isConcurrentSessionConfigurationSupported(
2122 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
2123 /*out*/bool* isSupported) {
2124 if (!isSupported) {
2125 ALOGE("%s: isSupported is NULL", __FUNCTION__);
2126 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
2127 }
2128
2129 if (!mInitialized) {
2130 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2131 return STATUS_ERROR(ERROR_DISCONNECTED,
2132 "Camera subsystem is not available");
2133 }
2134
2135 // Check for camera permissions
2136 int callingPid = CameraThreadState::getCallingPid();
2137 int callingUid = CameraThreadState::getCallingUid();
2138 if ((callingPid != getpid()) && !checkPermission(sCameraPermission, callingPid, callingUid)) {
2139 ALOGE("%s: pid %d doesn't have camera permissions", __FUNCTION__, callingPid);
2140 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2141 "android.permission.CAMERA needed to call"
2142 "isConcurrentSessionConfigurationSupported");
2143 }
2144
2145 status_t res =
2146 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
2147 cameraIdsAndSessionConfigurations, isSupported);
2148 if (res != OK) {
2149 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
2150 "support %s (%d)", strerror(-res), res);
2151 }
2152 return Status::ok();
2153}
2154
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002155Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
2156 /*out*/
2157 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002158 return addListenerHelper(listener, cameraStatuses);
2159}
2160
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002161binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
2162 std::vector<hardware::CameraStatus>* cameraStatuses) {
2163 return addListenerHelper(listener, cameraStatuses, false, true);
2164}
2165
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002166Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
2167 /*out*/
2168 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002169 bool isVendorListener, bool isProcessLocalTest) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002170
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002171 ATRACE_CALL();
2172
Igor Murashkinbfc99152013-02-27 12:55:20 -08002173 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08002174
Ruben Brunk3450ba72015-06-16 11:00:37 -07002175 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002176 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002177 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002178 }
2179
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002180 auto clientUid = CameraThreadState::getCallingUid();
2181 auto clientPid = CameraThreadState::getCallingPid();
Shuzhen Wang695044d2020-03-06 09:02:23 -08002182 bool openCloseCallbackAllowed = checkPermission(sCameraOpenCloseListenerPermission,
2183 clientPid, clientUid);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002184
Igor Murashkinbfc99152013-02-27 12:55:20 -08002185 Mutex::Autolock lock(mServiceLock);
2186
Ruben Brunkcc776712015-02-17 20:18:47 -08002187 {
2188 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08002189 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002190 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002191 ALOGW("%s: Tried to add listener %p which was already subscribed",
2192 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002193 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08002194 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002195 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002196
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002197 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08002198 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
2199 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002200 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08002201 if (ret != NO_ERROR) {
2202 String8 msg = String8::format("Failed to initialize service listener: %s (%d)",
2203 strerror(-ret), ret);
2204 ALOGE("%s: %s", __FUNCTION__, msg.string());
2205 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
2206 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002207 // The listener still needs to be added to the list of listeners, regardless of what
2208 // permissions the listener process has / whether it is a vendor listener. Since it might be
2209 // eligible to listen to other camera ids.
2210 mListenerList.emplace_back(serviceListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08002211 mUidPolicy->registerMonitorUid(clientUid);
Igor Murashkinbfc99152013-02-27 12:55:20 -08002212 }
2213
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002214 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07002215 {
Ruben Brunkcc776712015-02-17 20:18:47 -08002216 Mutex::Autolock lock(mCameraStatesLock);
2217 for (auto& i : mCameraStates) {
Shuzhen Wang43858162020-01-10 13:42:15 -08002218 cameraStatuses->emplace_back(i.first,
2219 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds());
Igor Murashkincba2c162013-03-20 15:56:31 -07002220 }
2221 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002222 // Remove the camera statuses that should be hidden from the client, we do
2223 // this after collecting the states in order to avoid holding
2224 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
2225 // the same time.
2226 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
2227 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
2228 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
2229 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
2230 ALOGE("%s: Invalid camera id %s, skipping status update",
2231 __FUNCTION__, s.cameraId.c_str());
2232 return true;
2233 }
2234 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
2235 clientUid);}), cameraStatuses->end());
2236
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002237 //cameraStatuses will have non-eligible camera ids removed.
2238 std::set<String16> idsChosenForCallback;
2239 for (const auto &s : *cameraStatuses) {
2240 idsChosenForCallback.insert(String16(s.cameraId));
2241 }
Igor Murashkincba2c162013-03-20 15:56:31 -07002242
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002243 /*
2244 * Immediately signal current torch status to this listener only
2245 * This may be a subset of all the devices, so don't include it in the response directly
2246 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002247 {
2248 Mutex::Autolock al(mTorchStatusMutex);
2249 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002250 String16 id = String16(mTorchStatusMap.keyAt(i).string());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002251 // The camera id is visible to the client. Fine to send torch
2252 // callback.
2253 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
2254 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
2255 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002256 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002257 }
2258
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002259 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08002260}
Ruben Brunkcc776712015-02-17 20:18:47 -08002261
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002262Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002263 ATRACE_CALL();
2264
Igor Murashkinbfc99152013-02-27 12:55:20 -08002265 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
2266
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002267 if (listener == 0) {
2268 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002269 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002270 }
2271
Igor Murashkinbfc99152013-02-27 12:55:20 -08002272 Mutex::Autolock lock(mServiceLock);
2273
Ruben Brunkcc776712015-02-17 20:18:47 -08002274 {
2275 Mutex::Autolock lock(mStatusListenerLock);
2276 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002277 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
2278 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid());
2279 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08002280 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002281 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002282 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002283 }
2284 }
2285
2286 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
2287 __FUNCTION__, listener.get());
2288
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002289 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08002290}
2291
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002292Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002293
2294 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002295 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
2296
2297 if (parameters == NULL) {
2298 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002299 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07002300 }
2301
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002302 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002303
2304 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002305 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07002306 // Error logged by caller
2307 return ret;
2308 }
2309
2310 String8 shimParamsString8 = shimParams.flatten();
2311 String16 shimParamsString16 = String16(shimParamsString8);
2312
2313 *parameters = shimParamsString16;
2314
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002315 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07002316}
2317
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002318Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
2319 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002320 ATRACE_CALL();
2321
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002322 const String8 id = String8(cameraId);
2323
2324 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002325
2326 switch (apiVersion) {
2327 case API_VERSION_1:
2328 case API_VERSION_2:
2329 break;
2330 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002331 String8 msg = String8::format("Unknown API version %d", apiVersion);
2332 ALOGE("%s: %s", __FUNCTION__, msg.string());
2333 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002334 }
2335
Emilian Peev28ad2ea2017-02-07 16:14:32 +00002336 int deviceVersion = getDeviceVersion(id);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002337 switch (deviceVersion) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002338 case CAMERA_DEVICE_API_VERSION_1_0:
2339 case CAMERA_DEVICE_API_VERSION_3_0:
2340 case CAMERA_DEVICE_API_VERSION_3_1:
2341 if (apiVersion == API_VERSION_2) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002342 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without shim",
2343 __FUNCTION__, id.string(), deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002344 *isSupported = false;
2345 } else { // if (apiVersion == API_VERSION_1) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002346 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always supported",
2347 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002348 *isSupported = true;
2349 }
2350 break;
2351 case CAMERA_DEVICE_API_VERSION_3_2:
2352 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -07002353 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002354 case CAMERA_DEVICE_API_VERSION_3_5:
Yin-Chia Yeh56d98ba2020-01-16 16:57:14 -08002355 case CAMERA_DEVICE_API_VERSION_3_6:
Shuzhen Wang83bff122020-11-20 15:51:39 -08002356 case CAMERA_DEVICE_API_VERSION_3_7:
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002357 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
2358 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002359 *isSupported = true;
2360 break;
2361 case -1: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002362 String8 msg = String8::format("Unknown camera ID %s", id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002363 ALOGE("%s: %s", __FUNCTION__, msg.string());
2364 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002365 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002366 default: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002367 String8 msg = String8::format("Unknown device version %x for device %s",
2368 deviceVersion, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002369 ALOGE("%s: %s", __FUNCTION__, msg.string());
2370 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
2371 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07002372 }
2373
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002374 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002375}
2376
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002377Status CameraService::isHiddenPhysicalCamera(const String16& cameraId,
2378 /*out*/ bool *isSupported) {
2379 ATRACE_CALL();
2380
2381 const String8 id = String8(cameraId);
2382
2383 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
2384 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(id.string());
2385
2386 return Status::ok();
2387}
2388
Ruben Brunkcc776712015-02-17 20:18:47 -08002389void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002390 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002391 for (auto& i : mActiveClientManager.getAll()) {
2392 auto clientSp = i->getValue();
2393 if (clientSp.get() == client) {
2394 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08002395 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07002396 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002397 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08002398}
2399
Ruben Brunkcc776712015-02-17 20:18:47 -08002400bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002401 bool ret = false;
2402 {
2403 // Acquire mServiceLock and prevent other clients from connecting
2404 std::unique_ptr<AutoConditionLock> lock =
2405 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08002406
Igor Murashkin634a5152013-02-20 17:15:11 -08002407
Ruben Brunkcc776712015-02-17 20:18:47 -08002408 std::vector<sp<BasicClient>> evicted;
2409 for (auto& i : mActiveClientManager.getAll()) {
2410 auto clientSp = i->getValue();
2411 if (clientSp.get() == nullptr) {
2412 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2413 mActiveClientManager.remove(i);
2414 continue;
2415 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08002416 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002417 mActiveClientManager.remove(i);
2418 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08002419
Ruben Brunkcc776712015-02-17 20:18:47 -08002420 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002421 clientSp->notifyError(
2422 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002423 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08002424 }
2425 }
2426
Ruben Brunkcc776712015-02-17 20:18:47 -08002427 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2428 // other clients from connecting in mServiceLockWrapper if held
2429 mServiceLock.unlock();
2430
Ruben Brunk36597b22015-03-20 22:15:57 -07002431 // Do not clear caller identity, remote caller should be client proccess
2432
Ruben Brunkcc776712015-02-17 20:18:47 -08002433 for (auto& i : evicted) {
2434 if (i.get() != nullptr) {
2435 i->disconnect();
2436 ret = true;
2437 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002438 }
2439
Ruben Brunkcc776712015-02-17 20:18:47 -08002440 // Reacquire mServiceLock
2441 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08002442
Ruben Brunkcc776712015-02-17 20:18:47 -08002443 } // lock is destroyed, allow further connect calls
2444
2445 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07002446}
2447
Ruben Brunkcc776712015-02-17 20:18:47 -08002448std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
2449 const String8& cameraId) const {
2450 std::shared_ptr<CameraState> state;
2451 {
2452 Mutex::Autolock lock(mCameraStatesLock);
2453 auto iter = mCameraStates.find(cameraId);
2454 if (iter != mCameraStates.end()) {
2455 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002456 }
2457 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002458 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002459}
2460
Ruben Brunkcc776712015-02-17 20:18:47 -08002461sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
2462 // Remove from active clients list
2463 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
2464 if (clientDescriptorPtr == nullptr) {
2465 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
2466 cameraId.string());
2467 return sp<BasicClient>{nullptr};
2468 }
2469
2470 return clientDescriptorPtr->getValue();
Keun young Parkd8973a72012-03-28 14:13:09 -07002471}
2472
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002473void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07002474 // Acquire mServiceLock and prevent other clients from connecting
2475 std::unique_ptr<AutoConditionLock> lock =
2476 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
2477
Ruben Brunk6267b532015-04-30 17:44:07 -07002478 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002479 for (size_t i = 0; i < newUserIds.size(); i++) {
2480 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07002481 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002482 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07002483 return;
2484 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002485 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07002486 }
2487
Ruben Brunka8ca9152015-04-07 14:23:40 -07002488
Ruben Brunk6267b532015-04-30 17:44:07 -07002489 if (newAllowedUsers == mAllowedUsers) {
2490 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
2491 return;
2492 }
2493
2494 logUserSwitch(mAllowedUsers, newAllowedUsers);
2495
2496 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07002497
2498 // Current user has switched, evict all current clients.
2499 std::vector<sp<BasicClient>> evicted;
2500 for (auto& i : mActiveClientManager.getAll()) {
2501 auto clientSp = i->getValue();
2502
2503 if (clientSp.get() == nullptr) {
2504 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2505 continue;
2506 }
2507
Ruben Brunk6267b532015-04-30 17:44:07 -07002508 // Don't evict clients that are still allowed.
2509 uid_t clientUid = clientSp->getClientUid();
2510 userid_t clientUserId = multiuser_get_user_id(clientUid);
2511 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
2512 continue;
2513 }
2514
Ruben Brunk36597b22015-03-20 22:15:57 -07002515 evicted.push_back(clientSp);
2516
2517 String8 curTime = getFormattedCurrentTime();
2518
2519 ALOGE("Evicting conflicting client for camera ID %s due to user change",
2520 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07002521
Ruben Brunk36597b22015-03-20 22:15:57 -07002522 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002523 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00002524 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
2525 " to user switch.", i->getKey().string(),
2526 String8{clientSp->getPackageName()}.string(),
2527 i->getOwnerId(), i->getPriority().getScore(),
2528 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07002529
2530 }
2531
2532 // Do not hold mServiceLock while disconnecting clients, but retain the condition
2533 // blocking other clients from connecting in mServiceLockWrapper if held.
2534 mServiceLock.unlock();
2535
2536 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07002537 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07002538
2539 for (auto& i : evicted) {
2540 i->disconnect();
2541 }
2542
Jayant Chowdhary12361932018-08-27 14:46:13 -07002543 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07002544
2545 // Reacquire mServiceLock
2546 mServiceLock.lock();
2547}
Ruben Brunkcc776712015-02-17 20:18:47 -08002548
Ruben Brunka8ca9152015-04-07 14:23:40 -07002549void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002550 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07002551 Mutex::Autolock l(mLogLock);
2552 mEventLog.add(String8::format("%s : %s", curTime.string(), event));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002553}
2554
Ruben Brunka8ca9152015-04-07 14:23:40 -07002555void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002556 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002557 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002558 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002559 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002560}
2561
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002562void CameraService::logDisconnectedOffline(const char* cameraId, int clientPid,
2563 const char* clientPackage) {
2564 // Log the clients evicted
2565 logEvent(String8::format("DISCONNECT offline device %s client for package %s (PID %d)",
2566 cameraId, clientPackage, clientPid));
2567}
2568
Ruben Brunka8ca9152015-04-07 14:23:40 -07002569void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002570 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002571 // Log the clients evicted
2572 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002573 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002574}
2575
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002576void CameraService::logConnectedOffline(const char* cameraId, int clientPid,
2577 const char* clientPackage) {
2578 // Log the clients evicted
2579 logEvent(String8::format("CONNECT offline device %s client for package %s (PID %d)", cameraId,
2580 clientPackage, clientPid));
2581}
2582
Ruben Brunka8ca9152015-04-07 14:23:40 -07002583void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002584 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002585 // Log the client rejected
2586 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002587 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002588}
2589
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002590void CameraService::logTorchEvent(const char* cameraId, const char *torchState, int clientPid) {
2591 // Log torch event
2592 logEvent(String8::format("Torch for camera id %s turned %s for client PID %d", cameraId,
2593 torchState, clientPid));
2594}
2595
Ruben Brunk6267b532015-04-30 17:44:07 -07002596void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
2597 const std::set<userid_t>& newUserIds) {
2598 String8 newUsers = toString(newUserIds);
2599 String8 oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002600 if (oldUsers.size() == 0) {
2601 oldUsers = "<None>";
2602 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07002603 // Log the new and old users
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002604 logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
Ruben Brunk6267b532015-04-30 17:44:07 -07002605 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002606}
2607
2608void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
2609 // Log the device removal
2610 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
2611}
2612
2613void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
2614 // Log the device removal
2615 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
2616}
2617
2618void CameraService::logClientDied(int clientPid, const char* reason) {
2619 // Log the device removal
2620 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07002621}
2622
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002623void CameraService::logServiceError(const char* msg, int errorCode) {
2624 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002625 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002626}
2627
Ruben Brunk36597b22015-03-20 22:15:57 -07002628status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
2629 uint32_t flags) {
2630
Mathias Agopian65ab4712010-07-14 17:59:35 -07002631 // Permission checks
2632 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002633 case SHELL_COMMAND_TRANSACTION: {
2634 int in = data.readFileDescriptor();
2635 int out = data.readFileDescriptor();
2636 int err = data.readFileDescriptor();
2637 int argc = data.readInt32();
2638 Vector<String16> args;
2639 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
2640 args.add(data.readString16());
2641 }
2642 sp<IBinder> unusedCallback;
2643 sp<IResultReceiver> resultReceiver;
2644 status_t status;
2645 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
2646 return status;
2647 }
2648 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
2649 return status;
2650 }
2651 status = shellCommand(in, out, err, args);
2652 if (resultReceiver != nullptr) {
2653 resultReceiver->send(status);
2654 }
2655 return NO_ERROR;
2656 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002657 }
2658
2659 return BnCameraService::onTransact(code, data, reply, flags);
2660}
2661
Mathias Agopian65ab4712010-07-14 17:59:35 -07002662// We share the media players for shutter and recording sound for all clients.
2663// A reference count is kept to determine when we will actually release the
2664// media players.
2665
Jaekyun Seokef498052018-03-23 13:09:44 +09002666sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
2667 sp<MediaPlayer> mp = new MediaPlayer();
2668 status_t error;
2669 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08002670 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09002671 error = mp->prepare();
2672 }
2673 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00002674 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09002675 mp->disconnect();
2676 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002677 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002678 }
2679 return mp;
2680}
2681
username5755fea2018-12-27 09:48:08 +08002682void CameraService::increaseSoundRef() {
2683 Mutex::Autolock lock(mSoundLock);
2684 mSoundRef++;
2685}
2686
2687void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002688 ATRACE_CALL();
2689
username5755fea2018-12-27 09:48:08 +08002690 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
2691 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
2692 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
2693 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
2694 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
2695 }
2696 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
2697 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
2698 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
2699 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002700 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08002701 }
2702 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
2703 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
2704 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
2705 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
2706 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002707 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002708}
2709
username5755fea2018-12-27 09:48:08 +08002710void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002711 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002712 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002713 if (--mSoundRef) return;
2714
2715 for (int i = 0; i < NUM_SOUNDS; i++) {
2716 if (mSoundPlayer[i] != 0) {
2717 mSoundPlayer[i]->disconnect();
2718 mSoundPlayer[i].clear();
2719 }
2720 }
2721}
2722
2723void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002724 ATRACE_CALL();
2725
Mathias Agopian65ab4712010-07-14 17:59:35 -07002726 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07002727 if (kind < 0 || kind >= NUM_SOUNDS) {
2728 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
2729 return;
2730 }
2731
Mathias Agopian65ab4712010-07-14 17:59:35 -07002732 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002733 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002734 sp<MediaPlayer> player = mSoundPlayer[kind];
2735 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08002736 player->seekTo(0);
2737 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002738 }
2739}
2740
2741// ----------------------------------------------------------------------------
2742
2743CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07002744 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002745 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09002746 const std::optional<String16>& clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002747 const String8& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07002748 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002749 int clientPid, uid_t clientUid,
2750 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002751 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08002752 IInterface::asBinder(cameraClient),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002753 clientPackageName, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07002754 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002755 clientPid, clientUid,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002756 servicePid),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002757 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08002758{
Jayant Chowdhary12361932018-08-27 14:46:13 -07002759 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002760 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002761
Igor Murashkin44cfcf02013-03-01 16:22:28 -08002762 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002763
username5755fea2018-12-27 09:48:08 +08002764 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002765
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002766 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002767}
2768
Mathias Agopian65ab4712010-07-14 17:59:35 -07002769// tear down the client
2770CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002771 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08002772 mDestructionStarted = true;
2773
username5755fea2018-12-27 09:48:08 +08002774 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002775 // unconditionally disconnect. function is idempotent
2776 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002777}
2778
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002779sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
2780
Igor Murashkin634a5152013-02-20 17:15:11 -08002781CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002782 const sp<IBinder>& remoteCallback,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09002783 const String16& clientPackageName, const std::optional<String16>& clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07002784 const String8& cameraIdStr, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002785 int clientPid, uid_t clientUid,
2786 int servicePid):
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002787 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07002788 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09002789 mClientPackageName(clientPackageName), mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002790 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002791 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07002792 mDisconnected(false), mUidIsTrusted(false),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002793 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002794 mRemoteBinder(remoteCallback),
2795 mOpsActive(false),
2796 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08002797{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002798 if (sCameraService == nullptr) {
2799 sCameraService = cameraService;
2800 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08002801
2802 // In some cases the calling code has no access to the package it runs under.
2803 // For example, NDK camera API.
2804 // In this case we will get the packages for the calling UID and pick the first one
2805 // for attributing the app op. This will work correctly for runtime permissions
2806 // as for legacy apps we will toggle the app op for all packages in the UID.
2807 // The caveat is that the operation may be attributed to the wrong package and
2808 // stats based on app ops may be slightly off.
2809 if (mClientPackageName.size() <= 0) {
2810 sp<IServiceManager> sm = defaultServiceManager();
2811 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
2812 if (binder == 0) {
2813 ALOGE("Cannot get permission service");
2814 // Leave mClientPackageName unchanged (empty) and the further interaction
2815 // with camera will fail in BasicClient::startCameraOps
2816 return;
2817 }
2818
2819 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
2820 Vector<String16> packages;
2821
2822 permCtrl->getPackagesForUid(mClientUid, packages);
2823
2824 if (packages.isEmpty()) {
2825 ALOGE("No packages for calling UID");
2826 // Leave mClientPackageName unchanged (empty) and the further interaction
2827 // with camera will fail in BasicClient::startCameraOps
2828 return;
2829 }
2830 mClientPackageName = packages[0];
2831 }
Steven Moreland89a2c5c2020-01-31 15:02:25 -08002832 if (getCurrentServingCall() != BinderCallType::HWBINDER) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002833 mAppOpsManager = std::make_unique<AppOpsManager>();
2834 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07002835
2836 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08002837}
2838
2839CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002840 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08002841 mDestructionStarted = true;
2842}
2843
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002844binder::Status CameraService::BasicClient::disconnect() {
2845 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002846 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002847 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07002848 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07002849 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002850
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002851 sCameraService->removeByClient(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002852 sCameraService->logDisconnected(mCameraIdStr, mClientPid, String8(mClientPackageName));
Peter Kalauskasa29c1352018-10-10 12:05:42 -07002853 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
2854 mCameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002855
2856 sp<IBinder> remote = getRemote();
2857 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002858 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08002859 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002860
2861 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07002862 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002863 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
2864 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
2865 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002866
Igor Murashkincba2c162013-03-20 15:56:31 -07002867 // client shouldn't be able to call into us anymore
2868 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002869
2870 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08002871}
2872
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002873status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
2874 // No dumping of clients directly over Binder,
2875 // must go through CameraService::dump
2876 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07002877 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002878 return OK;
2879}
2880
Ruben Brunkcc776712015-02-17 20:18:47 -08002881String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002882 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08002883}
2884
Emilian Peev8b64f282021-03-25 16:49:57 -07002885int CameraService::BasicClient::getCameraFacing() const {
2886 return mCameraFacing;
2887}
2888
2889int CameraService::BasicClient::getCameraOrientation() const {
2890 return mOrientation;
2891}
Ruben Brunkcc776712015-02-17 20:18:47 -08002892
2893int CameraService::BasicClient::getClientPid() const {
2894 return mClientPid;
2895}
2896
Ruben Brunk6267b532015-04-30 17:44:07 -07002897uid_t CameraService::BasicClient::getClientUid() const {
2898 return mClientUid;
2899}
2900
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002901bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
2902 // Defaults to API2.
2903 return level == API_2;
2904}
2905
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002906status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002907 {
2908 Mutex::Autolock l(mAudioRestrictionLock);
2909 mAudioRestriction = mode;
2910 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002911 sCameraService->updateAudioRestriction();
2912 return OK;
2913}
2914
2915int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002916 return sCameraService->updateAudioRestriction();
2917}
2918
2919int32_t CameraService::BasicClient::getAudioRestriction() const {
2920 Mutex::Autolock l(mAudioRestrictionLock);
2921 return mAudioRestriction;
2922}
2923
2924bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
2925 switch (mode) {
2926 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
2927 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
2928 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
2929 return true;
2930 default:
2931 return false;
2932 }
2933}
2934
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002935status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
2936 if (mode == AppOpsManager::MODE_ERRORED) {
2937 ALOGI("Camera %s: Access for \"%s\" has been revoked",
2938 mCameraIdStr.string(), String8(mClientPackageName).string());
2939 return PERMISSION_DENIED;
2940 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
2941 // If the calling Uid is trusted (a native service), the AppOpsManager could
2942 // return MODE_IGNORED. Do not treat such case as error.
2943 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
2944 mClientPackageName);
2945 bool isCameraPrivacyEnabled =
2946 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled(
2947 multiuser_get_user_id(mClientUid));
2948 if (!isUidActive || !isCameraPrivacyEnabled) {
2949 ALOGI("Camera %s: Access for \"%s\" has been restricted",
2950 mCameraIdStr.string(), String8(mClientPackageName).string());
2951 // Return the same error as for device policy manager rejection
2952 return -EACCES;
2953 }
2954 }
2955 return OK;
2956}
2957
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002958status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002959 ATRACE_CALL();
2960
Igor Murashkine6800ce2013-03-04 17:25:57 -08002961 {
2962 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002963 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08002964 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002965 if (mAppOpsManager != nullptr) {
2966 // Notify app ops that the camera is not available
2967 mOpsCallback = new OpsCallback(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002968 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
2969 mClientPackageName, mOpsCallback);
Igor Murashkine6800ce2013-03-04 17:25:57 -08002970
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002971 // Just check for camera acccess here on open - delay startOp until
2972 // camera frames start streaming in startCameraStreamingOps
2973 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
2974 mClientPackageName);
2975 status_t res = handleAppOpMode(mode);
2976 if (res != OK) {
2977 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002978 }
Svetoslav28e8ef72015-05-11 19:21:31 -07002979 }
2980
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002981 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002982
2983 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002984 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002985
Emilian Peev53722fa2019-02-22 17:47:20 -08002986 sCameraService->mUidPolicy->registerMonitorUid(mClientUid);
2987
Shuzhen Wang695044d2020-03-06 09:02:23 -08002988 // Notify listeners of camera open/close status
2989 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
2990
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002991 return OK;
2992}
2993
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002994status_t CameraService::BasicClient::startCameraStreamingOps() {
2995 ATRACE_CALL();
2996
2997 if (!mOpsActive) {
2998 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
2999 return INVALID_OPERATION;
3000 }
3001 if (mOpsStreaming) {
3002 ALOGV("%s: Streaming already active!", __FUNCTION__);
3003 return OK;
3004 }
3005
3006 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
3007 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
3008
3009 if (mAppOpsManager != nullptr) {
3010 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
3011 mClientPackageName, /*startIfModeDefault*/ false, mClientFeatureId,
3012 String16("start camera ") + String16(mCameraIdStr));
3013 status_t res = handleAppOpMode(mode);
3014 if (res != OK) {
3015 return res;
3016 }
3017 }
3018
3019 mOpsStreaming = true;
3020
3021 return OK;
3022}
3023
3024status_t CameraService::BasicClient::finishCameraStreamingOps() {
3025 ATRACE_CALL();
3026
3027 if (!mOpsActive) {
3028 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
3029 return INVALID_OPERATION;
3030 }
3031 if (!mOpsStreaming) {
3032 ALOGV("%s: Streaming not active!", __FUNCTION__);
3033 return OK;
3034 }
3035
3036 if (mAppOpsManager != nullptr) {
3037 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
3038 mClientPackageName, mClientFeatureId);
3039 mOpsStreaming = false;
3040 }
3041
3042 return OK;
3043}
3044
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003045status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003046 ATRACE_CALL();
3047
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003048 if (mOpsStreaming) {
3049 // Make sure we've notified everyone about camera stopping
3050 finishCameraStreamingOps();
3051 }
3052
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003053 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003054 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003055 mOpsActive = false;
3056
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01003057 // This function is called when a client disconnects. This should
3058 // release the camera, but actually only if it was in a proper
3059 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003060 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01003061 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003062
Ruben Brunkcc776712015-02-17 20:18:47 -08003063 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003064 sCameraService->updateStatus(StatusInternal::PRESENT,
3065 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003066 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003067 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003068 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
3069 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08003070 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003071 mOpsCallback.clear();
3072
Emilian Peev53722fa2019-02-22 17:47:20 -08003073 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid);
3074
Shuzhen Wang695044d2020-03-06 09:02:23 -08003075 // Notify listeners of camera open/close status
3076 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
3077
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003078 return OK;
3079}
3080
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003081void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003082 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003083 if (mAppOpsManager == nullptr) {
3084 return;
3085 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003086 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003087 if (op != AppOpsManager::OP_CAMERA) {
3088 ALOGW("Unexpected app ops notification received: %d", op);
3089 return;
3090 }
3091
3092 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003093 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003094 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003095 ALOGV("checkOp returns: %d, %s ", res,
3096 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
3097 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
3098 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
3099 "UNKNOWN");
3100
Shuzhen Wang64900852021-02-05 09:03:29 -08003101 if (res == AppOpsManager::MODE_ERRORED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003102 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003103 String8(mClientPackageName).string());
Svet Ganova453d0d2018-01-11 15:37:58 -08003104 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08003105 } else if (res == AppOpsManager::MODE_IGNORED) {
3106 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Evan Severson09ab4002021-02-10 14:15:19 -08003107 bool isCameraPrivacyEnabled =
3108 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled(
3109 multiuser_get_user_id(mClientUid));
Shuzhen Wang64900852021-02-05 09:03:29 -08003110 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d",
3111 mCameraIdStr.string(), String8(mClientPackageName).string(),
3112 mUidIsTrusted, isUidActive);
3113 // If the calling Uid is trusted (a native service), or the client Uid is active (WAR for
3114 // b/175320666), the AppOpsManager could return MODE_IGNORED. Do not treat such cases as
3115 // error.
Evan Severson09ab4002021-02-10 14:15:19 -08003116 if (!mUidIsTrusted && isUidActive && isCameraPrivacyEnabled) {
3117 setCameraMute(true);
3118 } else if (!mUidIsTrusted && !isUidActive) {
Shuzhen Wang64900852021-02-05 09:03:29 -08003119 block();
3120 }
Evan Severson09ab4002021-02-10 14:15:19 -08003121 } else if (res == AppOpsManager::MODE_ALLOWED) {
3122 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003123 }
3124}
3125
Svet Ganova453d0d2018-01-11 15:37:58 -08003126void CameraService::BasicClient::block() {
3127 ATRACE_CALL();
3128
3129 // Reset the client PID to allow server-initiated disconnect,
3130 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003131 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08003132 CaptureResultExtras resultExtras; // a dummy result (invalid)
3133 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
3134 disconnect();
3135}
3136
Mathias Agopian65ab4712010-07-14 17:59:35 -07003137// ----------------------------------------------------------------------------
3138
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003139void CameraService::Client::notifyError(int32_t errorCode,
Jianing Weicb0652e2014-03-12 18:29:36 -07003140 const CaptureResultExtras& resultExtras) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08003141 (void) resultExtras;
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003142 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07003143 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
3144 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
3145 api1ErrorCode = CAMERA_ERROR_DISABLED;
3146 }
3147 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003148 } else {
3149 ALOGE("mRemoteCallback is NULL!!");
3150 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003151}
3152
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003153// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003154binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003155 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003156 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08003157}
3158
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003159bool CameraService::Client::canCastToApiClient(apiLevel level) const {
3160 return level == API_1;
3161}
3162
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003163CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
3164 mClient(client) {
3165}
3166
3167void CameraService::Client::OpsCallback::opChanged(int32_t op,
3168 const String16& packageName) {
3169 sp<BasicClient> client = mClient.promote();
3170 if (client != NULL) {
3171 client->opChanged(op, packageName);
3172 }
3173}
3174
Mathias Agopian65ab4712010-07-14 17:59:35 -07003175// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08003176// UidPolicy
3177// ----------------------------------------------------------------------------
3178
3179void CameraService::UidPolicy::registerSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003180 Mutex::Autolock _l(mUidLock);
3181
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003182 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07003183 status_t res = mAm.linkToDeath(this);
3184 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08003185 | ActivityManager::UID_OBSERVER_IDLE
Emilian Peev53722fa2019-02-22 17:47:20 -08003186 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganova453d0d2018-01-11 15:37:58 -08003187 ActivityManager::PROCESS_STATE_UNKNOWN,
3188 String16("cameraserver"));
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003189 if (res == OK) {
3190 mRegistered = true;
3191 ALOGV("UidPolicy: Registered with ActivityManager");
3192 }
Svet Ganova453d0d2018-01-11 15:37:58 -08003193}
3194
3195void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003196 Mutex::Autolock _l(mUidLock);
3197
Steven Moreland2f348142019-07-02 15:59:07 -07003198 mAm.unregisterUidObserver(this);
3199 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003200 mRegistered = false;
3201 mActiveUids.clear();
3202 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08003203}
3204
3205void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
3206 onUidIdle(uid, disabled);
3207}
3208
3209void CameraService::UidPolicy::onUidActive(uid_t uid) {
3210 Mutex::Autolock _l(mUidLock);
3211 mActiveUids.insert(uid);
3212}
3213
3214void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
3215 bool deleted = false;
3216 {
3217 Mutex::Autolock _l(mUidLock);
3218 if (mActiveUids.erase(uid) > 0) {
3219 deleted = true;
3220 }
3221 }
3222 if (deleted) {
3223 sp<CameraService> service = mService.promote();
3224 if (service != nullptr) {
3225 service->blockClientsForUid(uid);
3226 }
3227 }
3228}
3229
Emilian Peev53722fa2019-02-22 17:47:20 -08003230void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07003231 int64_t procStateSeq __unused, int32_t capability __unused) {
Emilian Peev53722fa2019-02-22 17:47:20 -08003232 bool procStateChange = false;
3233 {
3234 Mutex::Autolock _l(mUidLock);
3235 if ((mMonitoredUids.find(uid) != mMonitoredUids.end()) &&
3236 (mMonitoredUids[uid].first != procState)) {
3237 mMonitoredUids[uid].first = procState;
3238 procStateChange = true;
3239 }
3240 }
3241
3242 if (procStateChange) {
3243 sp<CameraService> service = mService.promote();
3244 if (service != nullptr) {
3245 service->notifyMonitoredUids();
3246 }
3247 }
3248}
3249
3250void CameraService::UidPolicy::registerMonitorUid(uid_t uid) {
3251 Mutex::Autolock _l(mUidLock);
3252 auto it = mMonitoredUids.find(uid);
3253 if (it != mMonitoredUids.end()) {
3254 it->second.second++;
3255 } else {
3256 mMonitoredUids.emplace(
3257 std::pair<uid_t, std::pair<int32_t, size_t>> (uid,
3258 std::pair<int32_t, size_t> (ActivityManager::PROCESS_STATE_NONEXISTENT, 1)));
3259 }
3260}
3261
3262void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid) {
3263 Mutex::Autolock _l(mUidLock);
3264 auto it = mMonitoredUids.find(uid);
3265 if (it != mMonitoredUids.end()) {
3266 it->second.second--;
3267 if (it->second.second == 0) {
3268 mMonitoredUids.erase(it);
3269 }
3270 } else {
3271 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
3272 }
3273}
3274
Svet Ganov7b4ab782018-03-25 12:48:10 -07003275bool CameraService::UidPolicy::isUidActive(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003276 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003277 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003278}
3279
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003280static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
3281static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003282
Svet Ganov7b4ab782018-03-25 12:48:10 -07003283bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003284 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003285 // If activity manager is unreachable, assume everything is active
3286 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003287 return true;
3288 }
3289 auto it = mOverrideUids.find(uid);
3290 if (it != mOverrideUids.end()) {
3291 return it->second;
3292 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003293 bool active = mActiveUids.find(uid) != mActiveUids.end();
3294 if (!active) {
3295 // We want active UIDs to always access camera with their first attempt since
3296 // there is no guarantee the app is robustly written and would retry getting
3297 // the camera on failure. The inverse case is not a problem as we would take
3298 // camera away soon once we get the callback that the uid is no longer active.
3299 ActivityManager am;
3300 // Okay to access with a lock held as UID changes are dispatched without
3301 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07003302 int64_t startTimeMillis = 0;
3303 do {
3304 // TODO: Fix this b/109950150!
3305 // Okay this is a hack. There is a race between the UID turning active and
3306 // activity being resumed. The proper fix is very risky, so we temporary add
3307 // some polling which should happen pretty rarely anyway as the race is hard
3308 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003309 active = mActiveUids.find(uid) != mActiveUids.end();
Hui Yu12c7ec72020-05-04 17:40:52 +00003310 if (!active) active = am.isUidActive(uid, callingPackage);
Svet Ganov94ec46f2018-06-08 15:03:46 -07003311 if (active) {
3312 break;
3313 }
3314 if (startTimeMillis <= 0) {
3315 startTimeMillis = uptimeMillis();
3316 }
3317 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003318 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003319 if (remainingTimeMillis <= 0) {
3320 break;
3321 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003322 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
3323
3324 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003325 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003326 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003327 } while (true);
3328
Svet Ganov7b4ab782018-03-25 12:48:10 -07003329 if (active) {
3330 // Now that we found out the UID is actually active, cache that
3331 mActiveUids.insert(uid);
3332 }
3333 }
3334 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08003335}
3336
Varun Shahb42f1eb2019-04-16 14:45:13 -07003337int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
3338 Mutex::Autolock _l(mUidLock);
3339 return getProcStateLocked(uid);
3340}
3341
3342int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
3343 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
3344 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
3345 procState = mMonitoredUids[uid].first;
3346 }
3347 return procState;
3348}
3349
Svet Ganov7b4ab782018-03-25 12:48:10 -07003350void CameraService::UidPolicy::UidPolicy::addOverrideUid(uid_t uid,
3351 String16 callingPackage, bool active) {
3352 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08003353}
3354
Svet Ganov7b4ab782018-03-25 12:48:10 -07003355void CameraService::UidPolicy::removeOverrideUid(uid_t uid, String16 callingPackage) {
3356 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08003357}
3358
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003359void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
3360 Mutex::Autolock _l(mUidLock);
3361 ALOGV("UidPolicy: ActivityManager has died");
3362 mRegistered = false;
3363 mActiveUids.clear();
3364}
3365
Svet Ganov7b4ab782018-03-25 12:48:10 -07003366void CameraService::UidPolicy::updateOverrideUid(uid_t uid, String16 callingPackage,
3367 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003368 bool wasActive = false;
3369 bool isActive = false;
3370 {
3371 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003372 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003373 mOverrideUids.erase(uid);
3374 if (insert) {
3375 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
3376 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003377 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003378 }
3379 if (wasActive != isActive && !isActive) {
3380 sp<CameraService> service = mService.promote();
3381 if (service != nullptr) {
3382 service->blockClientsForUid(uid);
3383 }
3384 }
3385}
3386
3387// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08003388// SensorPrivacyPolicy
3389// ----------------------------------------------------------------------------
3390void CameraService::SensorPrivacyPolicy::registerSelf() {
3391 Mutex::Autolock _l(mSensorPrivacyLock);
3392 if (mRegistered) {
3393 return;
3394 }
Evan Severson09ab4002021-02-10 14:15:19 -08003395 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08003396 mSpm.addSensorPrivacyListener(this);
3397 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
3398 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003399 if (res == OK) {
3400 mRegistered = true;
3401 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
3402 }
3403}
3404
3405void CameraService::SensorPrivacyPolicy::unregisterSelf() {
3406 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08003407 mSpm.removeSensorPrivacyListener(this);
3408 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003409 mRegistered = false;
3410 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
3411}
3412
3413bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
3414 Mutex::Autolock _l(mSensorPrivacyLock);
3415 return mSensorPrivacyEnabled;
3416}
3417
Evan Severson09ab4002021-02-10 14:15:19 -08003418bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled(userid_t userId) {
3419 if (!hasCameraPrivacyFeature()) {
3420 return false;
3421 }
3422 return mSpm.isIndividualSensorPrivacyEnabled(userId,
3423 SensorPrivacyManager::INDIVIDUAL_SENSOR_CAMERA);
3424}
3425
Michael Grooverd1d435a2018-12-18 17:39:42 -08003426binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
3427 {
3428 Mutex::Autolock _l(mSensorPrivacyLock);
3429 mSensorPrivacyEnabled = enabled;
3430 }
3431 // if sensor privacy is enabled then block all clients from accessing the camera
Evan Severson09ab4002021-02-10 14:15:19 -08003432 if (enabled) {
3433 sp<CameraService> service = mService.promote();
3434 if (service != nullptr) {
3435 service->blockAllClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08003436 }
3437 }
3438 return binder::Status::ok();
3439}
3440
3441void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
3442 Mutex::Autolock _l(mSensorPrivacyLock);
3443 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
3444 mRegistered = false;
3445}
3446
Evan Severson09ab4002021-02-10 14:15:19 -08003447bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Severson671806e2021-04-20 16:44:53 -07003448 return mSpm.supportsSensorToggle(SensorPrivacyManager::INDIVIDUAL_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08003449}
3450
Michael Grooverd1d435a2018-12-18 17:39:42 -08003451// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003452// CameraState
3453// ----------------------------------------------------------------------------
3454
3455CameraService::CameraState::CameraState(const String8& id, int cost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003456 const std::set<String8>& conflicting, SystemCameraKind systemCameraKind) : mId(id),
3457 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
3458 mSystemCameraKind(systemCameraKind) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08003459
3460CameraService::CameraState::~CameraState() {}
3461
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003462CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003463 Mutex::Autolock lock(mStatusLock);
3464 return mStatus;
3465}
3466
Shuzhen Wang43858162020-01-10 13:42:15 -08003467std::vector<String8> CameraService::CameraState::getUnavailablePhysicalIds() const {
3468 Mutex::Autolock lock(mStatusLock);
3469 std::vector<String8> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
3470 return res;
3471}
3472
Ruben Brunkcc776712015-02-17 20:18:47 -08003473CameraParameters CameraService::CameraState::getShimParams() const {
3474 return mShimParams;
3475}
3476
3477void CameraService::CameraState::setShimParams(const CameraParameters& params) {
3478 mShimParams = params;
3479}
3480
3481int CameraService::CameraState::getCost() const {
3482 return mCost;
3483}
3484
3485std::set<String8> CameraService::CameraState::getConflicting() const {
3486 return mConflicting;
3487}
3488
3489String8 CameraService::CameraState::getId() const {
3490 return mId;
3491}
3492
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003493SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
3494 return mSystemCameraKind;
3495}
3496
Shuzhen Wang43858162020-01-10 13:42:15 -08003497bool CameraService::CameraState::addUnavailablePhysicalId(const String8& physicalId) {
3498 Mutex::Autolock lock(mStatusLock);
3499 auto result = mUnavailablePhysicalIds.insert(physicalId);
3500 return result.second;
3501}
3502
3503bool CameraService::CameraState::removeUnavailablePhysicalId(const String8& physicalId) {
3504 Mutex::Autolock lock(mStatusLock);
3505 auto count = mUnavailablePhysicalIds.erase(physicalId);
3506 return count > 0;
3507}
3508
Ruben Brunkcc776712015-02-17 20:18:47 -08003509// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07003510// ClientEventListener
3511// ----------------------------------------------------------------------------
3512
3513void CameraService::ClientEventListener::onClientAdded(
3514 const resource_policy::ClientDescriptor<String8,
3515 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003516 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003517 if (basicClient.get() != nullptr) {
3518 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3519 notifier.noteStartCamera(descriptor.getKey(),
3520 static_cast<int>(basicClient->getClientUid()));
3521 }
3522}
3523
3524void CameraService::ClientEventListener::onClientRemoved(
3525 const resource_policy::ClientDescriptor<String8,
3526 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003527 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003528 if (basicClient.get() != nullptr) {
3529 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3530 notifier.noteStopCamera(descriptor.getKey(),
3531 static_cast<int>(basicClient->getClientUid()));
3532 }
3533}
3534
3535
3536// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003537// CameraClientManager
3538// ----------------------------------------------------------------------------
3539
Ruben Brunk99e69712015-05-26 17:25:07 -07003540CameraService::CameraClientManager::CameraClientManager() {
3541 setListener(std::make_shared<ClientEventListener>());
3542}
3543
Ruben Brunkcc776712015-02-17 20:18:47 -08003544CameraService::CameraClientManager::~CameraClientManager() {}
3545
3546sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
3547 const String8& id) const {
3548 auto descriptor = get(id);
3549 if (descriptor == nullptr) {
3550 return sp<BasicClient>{nullptr};
3551 }
3552 return descriptor->getValue();
3553}
3554
3555String8 CameraService::CameraClientManager::toString() const {
3556 auto all = getAll();
3557 String8 ret("[");
3558 bool hasAny = false;
3559 for (auto& i : all) {
3560 hasAny = true;
3561 String8 key = i->getKey();
3562 int32_t cost = i->getCost();
3563 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00003564 int32_t score = i->getPriority().getScore();
3565 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08003566 auto conflicting = i->getConflicting();
3567 auto clientSp = i->getValue();
3568 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07003569 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08003570 if (clientSp.get() != nullptr) {
3571 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07003572 uid_t clientUid = clientSp->getClientUid();
3573 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003574 }
Emilian Peev8131a262017-02-01 12:33:43 +00003575 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
3576 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08003577
Ruben Brunk6267b532015-04-30 17:44:07 -07003578 if (clientSp.get() != nullptr) {
3579 ret.appendFormat("User Id: %d, ", clientUserId);
3580 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003581 if (packageName.size() != 0) {
3582 ret.appendFormat("Client Package Name: %s", packageName.string());
3583 }
3584
3585 ret.append(", Conflicting Client Devices: {");
3586 for (auto& j : conflicting) {
3587 ret.appendFormat("%s, ", j.string());
3588 }
3589 ret.append("})");
3590 }
3591 if (hasAny) ret.append("\n");
3592 ret.append("]\n");
3593 return ret;
3594}
3595
3596CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3597 const String8& key, const sp<BasicClient>& value, int32_t cost,
Emilian Peev8131a262017-02-01 12:33:43 +00003598 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
3599 int32_t state) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003600
Steven Moreland89a2c5c2020-01-31 15:02:25 -08003601 bool isVendorClient = getCurrentServingCall() == BinderCallType::HWBINDER;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003602 int32_t score_adj = isVendorClient ? kVendorClientScore : score;
3603 int32_t state_adj = isVendorClient ? kVendorClientState: state;
3604
Ruben Brunkcc776712015-02-17 20:18:47 -08003605 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003606 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj, isVendorClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08003607}
3608
3609CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3610 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
3611 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00003612 partial->getConflicting(), partial->getPriority().getScore(),
3613 partial->getOwnerId(), partial->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08003614}
3615
3616// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07003617
3618static const int kDumpLockRetries = 50;
3619static const int kDumpLockSleep = 60000;
3620
3621static bool tryLock(Mutex& mutex)
3622{
3623 bool locked = false;
3624 for (int i = 0; i < kDumpLockRetries; ++i) {
3625 if (mutex.tryLock() == NO_ERROR) {
3626 locked = true;
3627 break;
3628 }
3629 usleep(kDumpLockSleep);
3630 }
3631 return locked;
3632}
3633
3634status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003635 ATRACE_CALL();
3636
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003637 if (checkCallingPermission(sDumpPermission) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003638 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07003639 CameraThreadState::getCallingPid(),
3640 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003641 return NO_ERROR;
3642 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003643 bool locked = tryLock(mServiceLock);
3644 // failed to lock - CameraService is probably deadlocked
3645 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003646 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003647 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003648
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003649 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003650 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07003651
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003652 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003653 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08003654
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003655 if (locked) mServiceLock.unlock();
3656 return NO_ERROR;
3657 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003658 dprintf(fd, "\n== Service global info: ==\n\n");
3659 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003660 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07003661 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
3662 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003663 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
3664 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
3665 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003666 String8 activeClientString = mActiveClientManager.toString();
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003667 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
3668 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003669
3670 dumpEventLog(fd);
3671
3672 bool stateLocked = tryLock(mCameraStatesLock);
3673 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003674 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003675 }
3676
Emilian Peevbd8c5032018-02-14 23:05:40 +00003677 int argSize = args.size();
3678 for (int i = 0; i < argSize; i++) {
3679 if (args[i] == TagMonitor::kMonitorOption) {
3680 if (i + 1 < argSize) {
3681 mMonitorTags = String8(args[i + 1]);
3682 }
3683 break;
3684 }
3685 }
3686
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003687 for (auto& state : mCameraStates) {
3688 String8 cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003689
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003690 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003691
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003692 CameraParameters p = state.second->getShimParams();
3693 if (!p.isEmpty()) {
3694 dprintf(fd, " Camera1 API shim is using parameters:\n ");
3695 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003696 }
3697
3698 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08003699 if (clientDescriptor != nullptr) {
3700 dprintf(fd, " Device %s is open. Client instance dump:\n",
3701 cameraId.string());
3702 dprintf(fd, " Client priority score: %d state: %d\n",
3703 clientDescriptor->getPriority().getScore(),
3704 clientDescriptor->getPriority().getState());
3705 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
3706
3707 auto client = clientDescriptor->getValue();
3708 dprintf(fd, " Client package: %s\n",
3709 String8(client->getPackageName()).string());
3710
3711 client->dumpClient(fd, args);
3712 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003713 dprintf(fd, " Device %s is closed, no client instance\n",
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003714 cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003715 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003716
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003717 }
3718
3719 if (stateLocked) mCameraStatesLock.unlock();
3720
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003721 if (locked) mServiceLock.unlock();
3722
Emilian Peevf53f66e2017-04-11 14:29:43 +01003723 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003724
3725 dprintf(fd, "\n== Vendor tags: ==\n\n");
3726
3727 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
3728 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00003729 sp<VendorTagDescriptorCache> cache =
3730 VendorTagDescriptorCache::getGlobalVendorTagCache();
3731 if (cache == NULL) {
3732 dprintf(fd, "No vendor tags.\n");
3733 } else {
3734 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
3735 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003736 } else {
3737 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
3738 }
3739
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003740 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003741 dprintf(fd, "\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003742 camera3::CameraTraces::dump(fd, args);
3743
3744 // Process dump arguments, if any
3745 int n = args.size();
3746 String16 verboseOption("-v");
3747 String16 unreachableOption("--unreachable");
3748 for (int i = 0; i < n; i++) {
3749 if (args[i] == verboseOption) {
3750 // change logging level
3751 if (i + 1 >= n) continue;
3752 String8 levelStr(args[i+1]);
3753 int level = atoi(levelStr.string());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003754 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003755 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003756 } else if (args[i] == unreachableOption) {
3757 // Dump memory analysis
3758 // TODO - should limit be an argument parameter?
3759 UnreachableMemoryInfo info;
3760 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
3761 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003762 dprintf(fd, "\n== Unable to dump unreachable memory. "
3763 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003764 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003765 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003766 std::string s = info.ToString(/*log_contents*/ true);
3767 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003768 }
3769 }
3770 }
3771 return NO_ERROR;
3772}
3773
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003774void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003775 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003776
3777 Mutex::Autolock l(mLogLock);
3778 for (const auto& msg : mEventLog) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003779 dprintf(fd, " %s\n", msg.string());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003780 }
3781
3782 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003783 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003784 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003785 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003786 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003787 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003788}
3789
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003790void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003791 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003792 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
3793 if (mTorchClientMap[i] == who) {
3794 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003795 String8 cameraId = mTorchClientMap.keyAt(i);
3796 status_t res = mFlashlight->setTorchMode(cameraId, false);
3797 if (res) {
3798 ALOGE("%s: torch client died but couldn't turn off torch: "
3799 "%s (%d)", __FUNCTION__, strerror(-res), res);
3800 return;
3801 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003802 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003803 break;
3804 }
3805 }
3806}
3807
Ruben Brunkcc776712015-02-17 20:18:47 -08003808/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003809
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003810 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07003811 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
3812 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003813 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003814 // PID here is approximate and can be wrong.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003815 logClientDied(CameraThreadState::getCallingPid(), String8("Binder died unexpectedly"));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003816
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003817 // check torch client
3818 handleTorchClientBinderDied(who);
3819
3820 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08003821 if(!evictClientIdByRemote(who)) {
3822 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003823 return;
3824 }
3825
Ruben Brunkcc776712015-02-17 20:18:47 -08003826 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
3827 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003828}
3829
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003830void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003831 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08003832}
3833
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003834void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
3835 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003836 // Do not lock mServiceLock here or can get into a deadlock from
3837 // connect() -> disconnect -> updateStatus
3838
3839 auto state = getCameraState(cameraId);
3840
3841 if (state == nullptr) {
3842 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
3843 cameraId.string());
3844 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07003845 }
3846
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003847 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
3848 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3849 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3850 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
3851 return;
3852 }
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003853 bool supportsHAL3 = false;
3854 // supportsCameraApi also holds mInterfaceMutex, we can't call it in the
3855 // HIDL onStatusChanged wrapper call (we'll hold mStatusListenerLock and
3856 // mInterfaceMutex together, which can lead to deadlocks)
3857 binder::Status sRet =
3858 supportsCameraApi(String16(cameraId), hardware::ICameraService::API_VERSION_2,
3859 &supportsHAL3);
3860 if (!sRet.isOk()) {
3861 ALOGW("%s: Failed to determine if device supports HAL3 %s, supportsCameraApi call failed",
3862 __FUNCTION__, cameraId.string());
3863 return;
3864 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003865
3866 // Collect the logical cameras without holding mStatusLock in updateStatus
3867 // as that can lead to a deadlock(b/162192331).
3868 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08003869 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08003870 // of the listeners with both the mStatusLock and mStatusListenerLock held
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003871 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind, &supportsHAL3,
3872 &logicalCameraIds]
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003873 (const String8& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003874
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003875 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003876 // Update torch status if it has a flash unit.
3877 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003878 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003879 if (getTorchStatusLocked(cameraId, &torchStatus) !=
3880 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003881 TorchModeStatus newTorchStatus =
3882 status == StatusInternal::PRESENT ?
3883 TorchModeStatus::AVAILABLE_OFF :
3884 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003885 if (torchStatus != newTorchStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003886 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003887 }
3888 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003889 }
3890
3891 Mutex::Autolock lock(mStatusListenerLock);
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003892 notifyPhysicalCameraStatusLocked(mapToInterface(status), String16(cameraId),
3893 logicalCameraIds, deviceKind);
Shuzhen Wang43858162020-01-10 13:42:15 -08003894
Ruben Brunkcc776712015-02-17 20:18:47 -08003895 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003896 bool isVendorListener = listener->isVendorListener();
3897 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
3898 listener->getListenerPid(), listener->getListenerUid()) ||
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07003899 (isVendorListener && !supportsHAL3)) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003900 ALOGV("Skipping discovery callback for system-only camera/HAL1 device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003901 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003902 continue;
3903 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003904 listener->getListener()->onStatusChanged(mapToInterface(status),
Emilian Peev53722fa2019-02-22 17:47:20 -08003905 String16(cameraId));
Ruben Brunkcc776712015-02-17 20:18:47 -08003906 }
3907 });
Igor Murashkincba2c162013-03-20 15:56:31 -07003908}
3909
Shuzhen Wang695044d2020-03-06 09:02:23 -08003910void CameraService::updateOpenCloseStatus(const String8& cameraId, bool open,
3911 const String16& clientPackageName) {
3912 Mutex::Autolock lock(mStatusListenerLock);
3913
3914 for (const auto& it : mListenerList) {
3915 if (!it->isOpenCloseCallbackAllowed()) {
3916 continue;
3917 }
3918
3919 binder::Status ret;
3920 String16 cameraId64(cameraId);
3921 if (open) {
3922 ret = it->getListener()->onCameraOpened(cameraId64, clientPackageName);
3923 } else {
3924 ret = it->getListener()->onCameraClosed(cameraId64);
3925 }
3926 if (!ret.isOk()) {
3927 ALOGE("%s: Failed to trigger onCameraOpened/onCameraClosed callback: %d", __FUNCTION__,
3928 ret.exceptionCode());
3929 }
3930 }
3931}
3932
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003933template<class Func>
3934void CameraService::CameraState::updateStatus(StatusInternal status,
3935 const String8& cameraId,
3936 std::initializer_list<StatusInternal> rejectSourceStates,
3937 Func onStatusUpdatedLocked) {
3938 Mutex::Autolock lock(mStatusLock);
3939 StatusInternal oldStatus = mStatus;
3940 mStatus = status;
3941
3942 if (oldStatus == status) {
3943 return;
3944 }
3945
3946 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
3947 cameraId.string(), oldStatus, status);
3948
3949 if (oldStatus == StatusInternal::NOT_PRESENT &&
3950 (status != StatusInternal::PRESENT &&
3951 status != StatusInternal::ENUMERATING)) {
3952
3953 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
3954 __FUNCTION__);
3955 mStatus = oldStatus;
3956 return;
3957 }
3958
3959 /**
3960 * Sometimes we want to conditionally do a transition.
3961 * For example if a client disconnects, we want to go to PRESENT
3962 * only if we weren't already in NOT_PRESENT or ENUMERATING.
3963 */
3964 for (auto& rejectStatus : rejectSourceStates) {
3965 if (oldStatus == rejectStatus) {
3966 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
3967 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
3968 mStatus = oldStatus;
3969 return;
3970 }
3971 }
3972
3973 onStatusUpdatedLocked(cameraId, status);
3974}
3975
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003976status_t CameraService::getTorchStatusLocked(
3977 const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003978 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003979 if (!status) {
3980 return BAD_VALUE;
3981 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003982 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3983 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003984 // invalid camera ID or the camera doesn't have a flash unit
3985 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003986 }
3987
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003988 *status = mTorchStatusMap.valueAt(index);
3989 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003990}
3991
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003992status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003993 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003994 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3995 if (index == NAME_NOT_FOUND) {
3996 return BAD_VALUE;
3997 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003998 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003999
4000 return OK;
4001}
4002
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004003std::list<String16> CameraService::getLogicalCameras(
4004 const String8& physicalCameraId) {
4005 std::list<String16> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08004006 Mutex::Autolock lock(mCameraStatesLock);
4007 for (const auto& state : mCameraStates) {
4008 std::vector<std::string> physicalCameraIds;
4009 if (!mCameraProviderManager->isLogicalCamera(state.first.c_str(), &physicalCameraIds)) {
4010 // This is not a logical multi-camera.
4011 continue;
4012 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004013 if (std::find(physicalCameraIds.begin(), physicalCameraIds.end(), physicalCameraId.c_str())
Shuzhen Wang43858162020-01-10 13:42:15 -08004014 == physicalCameraIds.end()) {
4015 // cameraId is not a physical camera of this logical multi-camera.
4016 continue;
4017 }
4018
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004019 retList.emplace_back(String16(state.first));
4020 }
4021 return retList;
4022}
4023
4024void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
4025 const String16& physicalCameraId, const std::list<String16>& logicalCameraIds,
4026 SystemCameraKind deviceKind) {
4027 // mStatusListenerLock is expected to be locked
4028 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08004029 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004030 // Note: we check only the deviceKind of the physical camera id
4031 // since, logical camera ids and their physical camera ids are
4032 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07004033 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
4034 listener->getListenerPid(), listener->getListenerUid())) {
4035 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004036 String8(physicalCameraId).c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07004037 continue;
4038 }
Shuzhen Wang43858162020-01-10 13:42:15 -08004039 listener->getListener()->onPhysicalCameraStatusChanged(status,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004040 logicalCameraId, physicalCameraId);
Shuzhen Wang43858162020-01-10 13:42:15 -08004041 }
4042 }
4043}
4044
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004045
Svet Ganova453d0d2018-01-11 15:37:58 -08004046void CameraService::blockClientsForUid(uid_t uid) {
4047 const auto clients = mActiveClientManager.getAll();
4048 for (auto& current : clients) {
4049 if (current != nullptr) {
4050 const auto basicClient = current->getValue();
4051 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
4052 basicClient->block();
4053 }
4054 }
4055 }
4056}
4057
Michael Grooverd1d435a2018-12-18 17:39:42 -08004058void CameraService::blockAllClients() {
4059 const auto clients = mActiveClientManager.getAll();
4060 for (auto& current : clients) {
4061 if (current != nullptr) {
4062 const auto basicClient = current->getValue();
4063 if (basicClient.get() != nullptr) {
4064 basicClient->block();
4065 }
4066 }
4067 }
4068}
4069
Svet Ganova453d0d2018-01-11 15:37:58 -08004070// NOTE: This is a remote API - make sure all args are validated
4071status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
4072 if (!checkCallingPermission(sManageCameraPermission, nullptr, nullptr)) {
4073 return PERMISSION_DENIED;
4074 }
4075 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
4076 return BAD_VALUE;
4077 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004078 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004079 return handleSetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07004080 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004081 return handleResetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07004082 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004083 return handleGetUidState(args, out, err);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004084 } else if (args.size() >= 2 && args[0] == String16("set-rotate-and-crop")) {
4085 return handleSetRotateAndCrop(args);
4086 } else if (args.size() >= 1 && args[0] == String16("get-rotate-and-crop")) {
4087 return handleGetRotateAndCrop(out);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004088 } else if (args.size() >= 2 && args[0] == String16("set-image-dump-mask")) {
4089 return handleSetImageDumpMask(args);
4090 } else if (args.size() >= 1 && args[0] == String16("get-image-dump-mask")) {
4091 return handleGetImageDumpMask(out);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004092 } else if (args.size() >= 2 && args[0] == String16("set-camera-mute")) {
4093 return handleSetCameraMute(args);
Svet Ganova453d0d2018-01-11 15:37:58 -08004094 } else if (args.size() == 1 && args[0] == String16("help")) {
4095 printHelp(out);
4096 return NO_ERROR;
4097 }
4098 printHelp(err);
4099 return BAD_VALUE;
4100}
4101
4102status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004103 String16 packageName = args[1];
4104
Svet Ganova453d0d2018-01-11 15:37:58 -08004105 bool active = false;
4106 if (args[2] == String16("active")) {
4107 active = true;
4108 } else if ((args[2] != String16("idle"))) {
4109 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
4110 return BAD_VALUE;
4111 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004112
4113 int userId = 0;
4114 if (args.size() >= 5 && args[3] == String16("--user")) {
4115 userId = atoi(String8(args[4]));
4116 }
4117
4118 uid_t uid;
4119 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
4120 return BAD_VALUE;
4121 }
4122
4123 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08004124 return NO_ERROR;
4125}
4126
4127status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004128 String16 packageName = args[1];
4129
4130 int userId = 0;
4131 if (args.size() >= 4 && args[2] == String16("--user")) {
4132 userId = atoi(String8(args[3]));
4133 }
4134
4135 uid_t uid;
4136 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004137 return BAD_VALUE;
4138 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004139
4140 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08004141 return NO_ERROR;
4142}
4143
4144status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004145 String16 packageName = args[1];
4146
4147 int userId = 0;
4148 if (args.size() >= 4 && args[2] == String16("--user")) {
4149 userId = atoi(String8(args[3]));
4150 }
4151
4152 uid_t uid;
4153 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004154 return BAD_VALUE;
4155 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004156
4157 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004158 return dprintf(out, "active\n");
4159 } else {
4160 return dprintf(out, "idle\n");
4161 }
4162}
4163
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004164status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
4165 int rotateValue = atoi(String8(args[1]));
4166 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
4167 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
4168 Mutex::Autolock lock(mServiceLock);
4169
4170 mOverrideRotateAndCropMode = rotateValue;
4171
4172 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
4173
4174 const auto clients = mActiveClientManager.getAll();
4175 for (auto& current : clients) {
4176 if (current != nullptr) {
4177 const auto basicClient = current->getValue();
4178 if (basicClient.get() != nullptr) {
4179 basicClient->setRotateAndCropOverride(rotateValue);
4180 }
4181 }
4182 }
4183
4184 return OK;
4185}
4186
4187status_t CameraService::handleGetRotateAndCrop(int out) {
4188 Mutex::Autolock lock(mServiceLock);
4189
4190 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
4191}
4192
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004193status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
4194 char *endPtr;
4195 errno = 0;
4196 String8 maskString8 = String8(args[1]);
4197 long maskValue = strtol(maskString8.c_str(), &endPtr, 10);
4198
4199 if (errno != 0) return BAD_VALUE;
4200 if (endPtr != maskString8.c_str() + maskString8.size()) return BAD_VALUE;
4201 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
4202
4203 Mutex::Autolock lock(mServiceLock);
4204
4205 mImageDumpMask = maskValue;
4206
4207 return OK;
4208}
4209
4210status_t CameraService::handleGetImageDumpMask(int out) {
4211 Mutex::Autolock lock(mServiceLock);
4212
4213 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
4214}
4215
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004216status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
4217 int muteValue = strtol(String8(args[1]), nullptr, 10);
4218 if (errno != 0) return BAD_VALUE;
4219
4220 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
4221 Mutex::Autolock lock(mServiceLock);
4222
4223 mOverrideCameraMuteMode = (muteValue == 1);
4224
4225 const auto clients = mActiveClientManager.getAll();
4226 for (auto& current : clients) {
4227 if (current != nullptr) {
4228 const auto basicClient = current->getValue();
4229 if (basicClient.get() != nullptr) {
4230 if (basicClient->supportsCameraMute()) {
4231 basicClient->setCameraMute(mOverrideCameraMuteMode);
4232 }
4233 }
4234 }
4235 }
4236
4237 return OK;
4238}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004239
Svet Ganova453d0d2018-01-11 15:37:58 -08004240status_t CameraService::printHelp(int out) {
4241 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07004242 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
4243 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
4244 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004245 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
4246 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
4247 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004248 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
4249 " Valid values 0=OFF, 1=ON for JPEG\n"
4250 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004251 " set-camera-mute <0/1> enable or disable camera muting\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08004252 " help print this message\n");
4253}
4254
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004255int32_t CameraService::updateAudioRestriction() {
4256 Mutex::Autolock lock(mServiceLock);
4257 return updateAudioRestrictionLocked();
4258}
4259
4260int32_t CameraService::updateAudioRestrictionLocked() {
4261 int32_t mode = 0;
4262 // iterate through all active client
4263 for (const auto& i : mActiveClientManager.getAll()) {
4264 const auto clientSp = i->getValue();
4265 mode |= clientSp->getAudioRestriction();
4266 }
4267
4268 bool modeChanged = (mAudioRestriction != mode);
4269 mAudioRestriction = mode;
4270 if (modeChanged) {
4271 mAppOps.setCameraAudioRestriction(mode);
4272 }
4273 return mode;
4274}
4275
Mathias Agopian65ab4712010-07-14 17:59:35 -07004276}; // namespace android