blob: 83d2bc986ea54c3cdcaf1c0368b613580c608a71 [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;
Cliff Wud8cae102021-03-11 01:37:42 +080094using hardware::camera2::ICameraInjectionCallback;
95using hardware::camera2::ICameraInjectionSession;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080096using hardware::camera2::utils::CameraIdAndSessionConfiguration;
97using hardware::camera2::utils::ConcurrentCameraIdCombination;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080098
Mathias Agopian65ab4712010-07-14 17:59:35 -070099// ----------------------------------------------------------------------------
100// Logging support -- this is for debugging only
101// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700102volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700103
Steve Blockb8a80522011-12-20 16:23:08 +0000104#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
105#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700106
107static void setLogLevel(int level) {
108 android_atomic_write(level, &gLogLevel);
109}
110
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800111// Convenience methods for constructing binder::Status objects for error returns
112
113#define STATUS_ERROR(errorCode, errorString) \
114 binder::Status::fromServiceSpecificError(errorCode, \
115 String8::format("%s:%d: %s", __FUNCTION__, __LINE__, errorString))
116
117#define STATUS_ERROR_FMT(errorCode, errorString, ...) \
118 binder::Status::fromServiceSpecificError(errorCode, \
119 String8::format("%s:%d: " errorString, __FUNCTION__, __LINE__, \
120 __VA_ARGS__))
121
Mathias Agopian65ab4712010-07-14 17:59:35 -0700122// ----------------------------------------------------------------------------
123
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700124static const String16 sDumpPermission("android.permission.DUMP");
Svet Ganova453d0d2018-01-11 15:37:58 -0800125static const String16 sManageCameraPermission("android.permission.MANAGE_CAMERA");
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700126static const String16 sCameraPermission("android.permission.CAMERA");
127static const String16 sSystemCameraPermission("android.permission.SYSTEM_CAMERA");
128static const String16
129 sCameraSendSystemEventsPermission("android.permission.CAMERA_SEND_SYSTEM_EVENTS");
Shuzhen Wang695044d2020-03-06 09:02:23 -0800130static const String16 sCameraOpenCloseListenerPermission(
131 "android.permission.CAMERA_OPEN_CLOSE_LISTENER");
Cliff Wud8cae102021-03-11 01:37:42 +0800132static const String16
133 sCameraInjectExternalCameraPermission("android.permission.CAMERA_INJECT_EXTERNAL_CAMERA");
Svet Ganova453d0d2018-01-11 15:37:58 -0800134
Eino-Ville Talvala7c602c32021-03-20 17:00:18 -0700135static constexpr int32_t kVendorClientScore = resource_policy::PERCEPTIBLE_APP_ADJ;
136static constexpr int32_t kVendorClientState = ActivityManager::PROCESS_STATE_PERSISTENT_UI;
137
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800138const String8 CameraService::kOfflineDevice("offline-");
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700139
Rucha Katakward9ea6452021-05-06 11:57:16 -0700140// Set to keep track of logged service error events.
141static std::set<String8> sServiceErrorEventSet;
142
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800143CameraService::CameraService() :
144 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800145 mNumberOfCameras(0),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700146 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700147 mSoundRef(0), mInitialized(false),
148 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000149 ALOGI("CameraService started (pid=%d)", getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800150 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700151}
152
Iliyan Malchev8951a972011-04-14 16:55:59 -0700153void CameraService::onFirstRef()
154{
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -0700155
Ruben Brunkcc776712015-02-17 20:18:47 -0800156 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800157
Iliyan Malchev8951a972011-04-14 16:55:59 -0700158 BnCameraService::onFirstRef();
159
Ruben Brunk99e69712015-05-26 17:25:07 -0700160 // Update battery life tracking if service is restarting
161 BatteryNotifier& notifier(BatteryNotifier::getInstance());
162 notifier.noteResetCamera();
163 notifier.noteResetFlashlight();
164
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800165 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800166
Emilian Peevf53f66e2017-04-11 14:29:43 +0100167 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800168 if (res == OK) {
169 mInitialized = true;
170 }
171
Svet Ganova453d0d2018-01-11 15:37:58 -0800172 mUidPolicy = new UidPolicy(this);
173 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800174 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
175 mSensorPrivacyPolicy->registerSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800176 mInjectionStatusListener = new InjectionStatusListener(this);
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700177 mAppOps.setCameraAudioRestriction(mAudioRestriction);
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700178 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
179 if (hcs->registerAsService() != android::OK) {
180 ALOGE("%s: Failed to register default android.frameworks.cameraservice.service@1.0",
181 __FUNCTION__);
182 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700183
184 // This needs to be last call in this function, so that it's as close to
185 // ServiceManager::addService() as possible.
Shuzhen Wang316781a2020-08-18 18:11:01 -0700186 CameraServiceProxyWrapper::pingCameraServiceProxy();
Shuzhen Wang24b44152019-09-20 10:38:11 -0700187 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800188}
189
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800190status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800191 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100192
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800193 std::vector<std::string> deviceIds;
194 {
195 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800196
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800197 if (nullptr == mCameraProviderManager.get()) {
198 mCameraProviderManager = new CameraProviderManager();
199 res = mCameraProviderManager->initialize(this);
200 if (res != OK) {
201 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
202 __FUNCTION__, strerror(-res), res);
Rucha Katakward9ea6452021-05-06 11:57:16 -0700203 logServiceError(String8::format("Unable to initialize camera provider manager"),
204 ERROR_DISCONNECTED);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800205 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100206 }
207 }
208
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800209
210 // Setup vendor tags before we call get_camera_info the first time
211 // because HAL might need to setup static vendor keys in get_camera_info
212 // TODO: maybe put this into CameraProviderManager::initialize()?
213 mCameraProviderManager->setUpVendorTags();
214
215 if (nullptr == mFlashlight.get()) {
216 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700217 }
218
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800219 res = mFlashlight->findFlashUnits();
220 if (res != OK) {
221 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
222 }
223
224 deviceIds = mCameraProviderManager->getCameraDeviceIds();
225 }
226
227
228 for (auto& cameraId : deviceIds) {
229 String8 id8 = String8(cameraId.c_str());
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800230 if (getCameraState(id8) == nullptr) {
231 onDeviceStatusChanged(id8, CameraDeviceStatus::PRESENT);
232 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800233 }
234
Shuzhen Wang89db2992021-05-20 13:09:48 -0700235 //Derive primary rear/front cameras, and filter their charactierstics.
236 //This needs to be done after all cameras are enumerated and camera ids are sorted.
237 filterSPerfClassCharacteristics();
238
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800239 return OK;
240}
241
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700242void CameraService::broadcastTorchModeStatus(const String8& cameraId, TorchModeStatus status,
243 SystemCameraKind systemCameraKind) {
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800244 Mutex::Autolock lock(mStatusListenerLock);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800245 for (auto& i : mListenerList) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700246 if (shouldSkipStatusUpdates(systemCameraKind, i->isVendorListener(), i->getListenerPid(),
247 i->getListenerUid())) {
248 ALOGV("Skipping torch callback for system-only camera device %s",
249 cameraId.c_str());
250 continue;
251 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700252 i->getListener()->onTorchStatusChanged(mapToInterface(status), String16{cameraId});
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800253 }
254}
255
Mathias Agopian65ab4712010-07-14 17:59:35 -0700256CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800257 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800258 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800259 mSensorPrivacyPolicy->unregisterSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800260 mInjectionStatusListener->removeListener();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700261}
262
Emilian Peevaee727d2017-05-04 16:35:48 +0100263void CameraService::onNewProviderRegistered() {
264 enumerateProviders();
265}
266
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700267void CameraService::filterAPI1SystemCameraLocked(
268 const std::vector<std::string> &normalDeviceIds) {
269 mNormalDeviceIdsWithoutSystemCamera.clear();
270 for (auto &deviceId : normalDeviceIds) {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700271 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
272 if (getSystemCameraKind(String8(deviceId.c_str()), &deviceKind) != OK) {
273 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, deviceId.c_str());
274 continue;
275 }
276 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700277 // All system camera ids will necessarily come after public camera
278 // device ids as per the HAL interface contract.
279 break;
280 }
281 mNormalDeviceIdsWithoutSystemCamera.push_back(deviceId);
282 }
283 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
284 mNormalDeviceIdsWithoutSystemCamera.size());
285}
286
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700287status_t CameraService::getSystemCameraKind(const String8& cameraId, SystemCameraKind *kind) const {
288 auto state = getCameraState(cameraId);
289 if (state != nullptr) {
290 *kind = state->getSystemCameraKind();
291 return OK;
292 }
293 // Hidden physical camera ids won't have CameraState
294 return mCameraProviderManager->getSystemCameraKind(cameraId.c_str(), kind);
295}
296
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800297void CameraService::updateCameraNumAndIds() {
298 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700299 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
300 // Excludes hidden secure cameras
301 mNumberOfCameras =
302 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
303 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800304 mNormalDeviceIds =
305 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700306 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800307}
308
Shuzhen Wang89db2992021-05-20 13:09:48 -0700309void CameraService::filterSPerfClassCharacteristics() {
310 static int32_t kPerformanceClassLevel =
311 property_get_int32("ro.odm.build.media_performance_class", 0);
312 static bool kIsSPerformanceClass = (kPerformanceClassLevel == 31);
313
314 if (!kIsSPerformanceClass) return;
315
316 // To claim to be S Performance primary cameras, the cameras must be
317 // backward compatible. So performance class primary camera Ids must be API1
318 // compatible.
319 bool firstRearCameraSeen = false, firstFrontCameraSeen = false;
320 for (const auto& cameraId : mNormalDeviceIdsWithoutSystemCamera) {
321 int facing = -1;
322 int orientation = 0;
323 String8 cameraId8(cameraId.c_str());
324 getDeviceVersion(cameraId8, /*out*/&facing, /*out*/&orientation);
325 if (facing == -1) {
326 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
327 return;
328 }
329
330 if ((facing == hardware::CAMERA_FACING_BACK && !firstRearCameraSeen) ||
331 (facing == hardware::CAMERA_FACING_FRONT && !firstFrontCameraSeen)) {
332 mCameraProviderManager->filterSmallJpegSizes(cameraId);
333
334 if (facing == hardware::CAMERA_FACING_BACK) {
335 firstRearCameraSeen = true;
336 }
337 if (facing == hardware::CAMERA_FACING_FRONT) {
338 firstFrontCameraSeen = true;
339 }
340 }
341
342 if (firstRearCameraSeen && firstFrontCameraSeen) {
343 break;
344 }
345 }
346}
347
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100348void CameraService::addStates(const String8 id) {
349 std::string cameraId(id.c_str());
350 hardware::camera::common::V1_0::CameraResourceCost cost;
351 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700352 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100353 if (res != OK) {
354 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
355 return;
356 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700357 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
358 if (res != OK) {
359 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
360 return;
361 }
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100362 std::set<String8> conflicting;
363 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
364 conflicting.emplace(String8(cost.conflictingDevices[i].c_str()));
365 }
366
367 {
368 Mutex::Autolock lock(mCameraStatesLock);
369 mCameraStates.emplace(id, std::make_shared<CameraState>(id, cost.resourceCost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700370 conflicting, deviceKind));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100371 }
372
373 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100374 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100375 mTorchStatusMap.add(id, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800376
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700377 broadcastTorchModeStatus(id, TorchModeStatus::AVAILABLE_OFF, deviceKind);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100378 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800379
380 updateCameraNumAndIds();
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100381 logDeviceAdded(id, "Device added");
382}
383
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100384void CameraService::removeStates(const String8 id) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800385 updateCameraNumAndIds();
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100386 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100387 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100388 mTorchStatusMap.removeItem(id);
389 }
390
391 {
392 Mutex::Autolock lock(mCameraStatesLock);
393 mCameraStates.erase(id);
394 }
395}
396
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800397void CameraService::onDeviceStatusChanged(const String8& id,
398 CameraDeviceStatus newHalStatus) {
399 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
400 id.string(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700401
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800402 StatusInternal newStatus = mapToInternal(newHalStatus);
403
Ruben Brunkcc776712015-02-17 20:18:47 -0800404 std::shared_ptr<CameraState> state = getCameraState(id);
405
406 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700407 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100408 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700409 __FUNCTION__, id.string());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100410
411 // First add as absent to make sure clients are notified below
412 addStates(id);
413
414 updateStatus(newStatus, id);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700415 } else {
416 ALOGE("%s: Bad camera ID %s", __FUNCTION__, id.string());
417 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700418 return;
419 }
420
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800421 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800422
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800423 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800424 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700425 return;
426 }
427
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800428 if (newStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700429 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
430 newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800431
432 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
433 // to this device until the status changes
434 updateStatus(StatusInternal::NOT_PRESENT, id);
435
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800436 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700437 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800438 // Don't do this in updateStatus to avoid deadlock over mServiceLock
439 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700440
Ruben Brunkcc776712015-02-17 20:18:47 -0800441 // Remove cached shim parameters
442 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700443
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800444 // Remove online as well as offline client from the list of active clients,
445 // if they are present
446 clientToDisconnectOnline = removeClientLocked(id);
447 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + id);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700448 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800449
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800450 disconnectClient(id, clientToDisconnectOnline);
451 disconnectClient(kOfflineDevice + id, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700452
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100453 removeStates(id);
Ruben Brunkcc776712015-02-17 20:18:47 -0800454 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800455 if (oldStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700456 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
457 newStatus));
458 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800459 updateStatus(newStatus, id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700460 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800461}
Igor Murashkincba2c162013-03-20 15:56:31 -0700462
Shuzhen Wang43858162020-01-10 13:42:15 -0800463void CameraService::onDeviceStatusChanged(const String8& id,
464 const String8& physicalId,
465 CameraDeviceStatus newHalStatus) {
466 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
467 __FUNCTION__, id.string(), physicalId.string(), newHalStatus);
468
469 StatusInternal newStatus = mapToInternal(newHalStatus);
470
471 std::shared_ptr<CameraState> state = getCameraState(id);
472
473 if (state == nullptr) {
474 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
475 __FUNCTION__, id.string(), physicalId.string());
476 return;
477 }
478
479 StatusInternal logicalCameraStatus = state->getStatus();
480 if (logicalCameraStatus != StatusInternal::PRESENT &&
481 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
482 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
483 __FUNCTION__, physicalId.string(), newHalStatus, logicalCameraStatus);
484 return;
485 }
486
487 bool updated = false;
488 if (newStatus == StatusInternal::PRESENT) {
489 updated = state->removeUnavailablePhysicalId(physicalId);
490 } else {
491 updated = state->addUnavailablePhysicalId(physicalId);
492 }
493
494 if (updated) {
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800495 String8 idCombo = id + " : " + physicalId;
496 if (newStatus == StatusInternal::PRESENT) {
497 logDeviceAdded(idCombo,
498 String8::format("Device status changed to %d", newStatus));
499 } else {
500 logDeviceRemoved(idCombo,
501 String8::format("Device status changed to %d", newStatus));
502 }
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700503 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
504 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
505 if (getSystemCameraKind(id, &deviceKind) != OK) {
506 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.string());
507 return;
508 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800509 String16 id16(id), physicalId16(physicalId);
510 Mutex::Autolock lock(mStatusListenerLock);
511 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700512 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
513 listener->getListenerPid(), listener->getListenerUid())) {
514 ALOGV("Skipping discovery callback for system-only camera device %s",
515 id.c_str());
516 continue;
517 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800518 listener->getListener()->onPhysicalCameraStatusChanged(mapToInterface(newStatus),
519 id16, physicalId16);
520 }
521 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700522}
523
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800524void CameraService::disconnectClient(const String8& id, sp<BasicClient> clientToDisconnect) {
525 if (clientToDisconnect.get() != nullptr) {
526 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
527 __FUNCTION__, id.string());
528 // Notify the client of disconnection
529 clientToDisconnect->notifyError(
530 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
531 CaptureResultExtras{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800532 clientToDisconnect->disconnect();
533 }
534}
535
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800536void CameraService::onTorchStatusChanged(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800537 TorchModeStatus newStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700538 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
539 status_t res = getSystemCameraKind(cameraId, &systemCameraKind);
540 if (res != OK) {
541 ALOGE("%s: Could not get system camera kind for camera id %s", __FUNCTION__,
542 cameraId.string());
543 return;
544 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800545 Mutex::Autolock al(mTorchStatusMutex);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700546 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800547}
548
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800549void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700550 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800551 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
552 __FUNCTION__, cameraId.string(), newStatus);
553
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800554 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800555 status_t res = getTorchStatusLocked(cameraId, &status);
556 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700557 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
558 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800559 return;
560 }
561 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800562 return;
563 }
564
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800565 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800566 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800567 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
568 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800569 return;
570 }
571
Ruben Brunkcc776712015-02-17 20:18:47 -0800572 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700573 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700574 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700575 auto iter = mTorchUidMap.find(cameraId);
576 if (iter != mTorchUidMap.end()) {
577 int oldUid = iter->second.second;
578 int newUid = iter->second.first;
579 BatteryNotifier& notifier(BatteryNotifier::getInstance());
580 if (oldUid != newUid) {
581 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800582 if (status == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700583 notifier.noteFlashlightOff(cameraId, oldUid);
584 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800585 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700586 notifier.noteFlashlightOn(cameraId, newUid);
587 }
588 iter->second.second = newUid;
589 } else {
590 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800591 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700592 notifier.noteFlashlightOn(cameraId, oldUid);
593 } else {
594 notifier.noteFlashlightOff(cameraId, oldUid);
595 }
596 }
597 }
598 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700599 broadcastTorchModeStatus(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800600}
601
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700602static bool hasPermissionsForSystemCamera(int callingPid, int callingUid) {
603 return checkPermission(sSystemCameraPermission, callingPid, callingUid) &&
604 checkPermission(sCameraPermission, callingPid, callingUid);
605}
606
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800607Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700608 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100609 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700610 bool hasSystemCameraPermissions =
611 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
612 CameraThreadState::getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700613 switch (type) {
614 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700615 if (hasSystemCameraPermissions) {
616 *numCameras = static_cast<int>(mNormalDeviceIds.size());
617 } else {
618 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
619 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800620 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700621 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700622 if (hasSystemCameraPermissions) {
623 *numCameras = mNumberOfCameras;
624 } else {
625 *numCameras = mNumberOfCamerasWithoutSystemCamera;
626 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800627 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700628 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800629 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700630 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800631 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
632 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700633 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800634 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700635}
636
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800637Status CameraService::getCameraInfo(int cameraId,
638 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700639 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100640 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700641 std::string cameraIdStr = cameraIdIntToStrLocked(cameraId);
642 if (shouldRejectSystemCameraConnection(String8(cameraIdStr.c_str()))) {
643 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
644 "characteristics for system only device %s: ", cameraIdStr.c_str());
645 }
Emilian Peevaee727d2017-05-04 16:35:48 +0100646
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800647 if (!mInitialized) {
Rucha Katakward9ea6452021-05-06 11:57:16 -0700648 logServiceError(String8::format("Camera subsystem is not available"),ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800649 return STATUS_ERROR(ERROR_DISCONNECTED,
650 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -0700651 }
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700652 bool hasSystemCameraPermissions =
653 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
654 CameraThreadState::getCallingUid());
655 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
656 if (hasSystemCameraPermissions) {
657 cameraIdBound = mNumberOfCameras;
658 }
659 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800660 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
661 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700662 }
663
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800664 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800665 status_t err = mCameraProviderManager->getCameraInfo(
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700666 cameraIdStr.c_str(), cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100667 if (err != OK) {
668 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
669 "Error retrieving camera info from device %d: %s (%d)", cameraId,
670 strerror(-err), err);
Rucha Katakward9ea6452021-05-06 11:57:16 -0700671 logServiceError(String8::format("Error retrieving camera info from device %d",cameraId),
672 ERROR_INVALID_OPERATION);
Ruben Brunkcc776712015-02-17 20:18:47 -0800673 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100674
Ruben Brunkcc776712015-02-17 20:18:47 -0800675 return ret;
676}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700677
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800678std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700679 const std::vector<std::string> *deviceIds = &mNormalDeviceIdsWithoutSystemCamera;
680 auto callingPid = CameraThreadState::getCallingPid();
681 auto callingUid = CameraThreadState::getCallingUid();
682 if (checkPermission(sSystemCameraPermission, callingPid, callingUid) ||
683 getpid() == callingPid) {
684 deviceIds = &mNormalDeviceIds;
685 }
686 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(deviceIds->size())) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800687 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700688 __FUNCTION__, cameraIdInt, deviceIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800689 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800690 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800691
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700692 return (*deviceIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800693}
694
695String8 CameraService::cameraIdIntToStr(int cameraIdInt) {
696 Mutex::Autolock lock(mServiceLock);
697 return String8(cameraIdIntToStrLocked(cameraIdInt).c_str());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800698}
699
700Status CameraService::getCameraCharacteristics(const String16& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800701 CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700702 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700703 if (!cameraInfo) {
704 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800705 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -0700706 }
707
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800708 if (!mInitialized) {
709 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Rucha Katakward9ea6452021-05-06 11:57:16 -0700710 logServiceError(String8::format("Camera subsystem is not available"),ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800711 return STATUS_ERROR(ERROR_DISCONNECTED,
712 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -0700713 }
714
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700715 if (shouldRejectSystemCameraConnection(String8(cameraId))) {
716 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
717 "characteristics for system only device %s: ", String8(cameraId).string());
718 }
719
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800720 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800721
Emilian Peevf53f66e2017-04-11 14:29:43 +0100722 status_t res = mCameraProviderManager->getCameraCharacteristics(
723 String8(cameraId).string(), cameraInfo);
724 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700725 if (res == NAME_NOT_FOUND) {
726 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
727 "characteristics for unknown device %s: %s (%d)", String8(cameraId).string(),
728 strerror(-res), res);
729 } else {
Rucha Katakward9ea6452021-05-06 11:57:16 -0700730 logServiceError(String8::format("Unable to retrieve camera characteristics for "
731 "device %s.", String8(cameraId).string()),ERROR_INVALID_OPERATION);
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700732 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
733 "characteristics for device %s: %s (%d)", String8(cameraId).string(),
734 strerror(-res), res);
735 }
Ruben Brunkb2119af2014-05-09 19:57:56 -0700736 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700737 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
738 if (getSystemCameraKind(String8(cameraId), &deviceKind) != OK) {
739 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, String8(cameraId).string());
740 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera kind "
741 "for device %s", String8(cameraId).string());
742 }
Jayant Chowdhary12361932018-08-27 14:46:13 -0700743 int callingPid = CameraThreadState::getCallingPid();
744 int callingUid = CameraThreadState::getCallingUid();
Emilian Peeve20c6372018-08-14 18:45:53 +0100745 std::vector<int32_t> tagsRemoved;
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700746 // If it's not calling from cameraserver, check the permission only if
747 // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
748 // it would've already been checked in shouldRejectSystemCameraConnection.
Emilian Peeve20c6372018-08-14 18:45:53 +0100749 if ((callingPid != getpid()) &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700750 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700751 !checkPermission(sCameraPermission, callingPid, callingUid)) {
Emilian Peeve20c6372018-08-14 18:45:53 +0100752 res = cameraInfo->removePermissionEntries(
753 mCameraProviderManager->getProviderTagIdLocked(String8(cameraId).string()),
754 &tagsRemoved);
755 if (res != OK) {
756 cameraInfo->clear();
757 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
758 " characteristics needing camera permission for device %s: %s (%d)",
759 String8(cameraId).string(), strerror(-res), res);
760 }
761 }
762
763 if (!tagsRemoved.empty()) {
764 res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
765 tagsRemoved.data(), tagsRemoved.size());
766 if (res != OK) {
767 cameraInfo->clear();
768 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
769 "keys needing permission for device %s: %s (%d)", String8(cameraId).string(),
770 strerror(-res), res);
771 }
772 }
773
Zhijun He2b59be82013-09-25 10:14:30 -0700774 return ret;
775}
776
Ruben Brunkcc776712015-02-17 20:18:47 -0800777String8 CameraService::getFormattedCurrentTime() {
778 time_t now = time(nullptr);
779 char formattedTime[64];
780 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
781 return String8(formattedTime);
782}
783
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800784Status CameraService::getCameraVendorTagDescriptor(
785 /*out*/
786 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700787 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800788 if (!mInitialized) {
789 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800790 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800791 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -0800792 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
793 if (globalDescriptor != nullptr) {
794 *desc = *(globalDescriptor.get());
795 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800796 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800797}
798
Emilian Peev71c73a22017-03-21 16:35:51 +0000799Status CameraService::getCameraVendorTagCache(
800 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
801 ATRACE_CALL();
802 if (!mInitialized) {
803 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
804 return STATUS_ERROR(ERROR_DISCONNECTED,
805 "Camera subsystem not available");
806 }
807 sp<VendorTagDescriptorCache> globalCache =
808 VendorTagDescriptorCache::getGlobalVendorTagCache();
809 if (globalCache != nullptr) {
810 *cache = *(globalCache.get());
811 }
812 return Status::ok();
813}
814
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -0700815void CameraService::clearCachedVariables() {
816 BasicClient::BasicClient::sCameraService = nullptr;
817}
818
Emilian Peevb91f1802021-03-23 14:50:28 -0700819int CameraService::getDeviceVersion(const String8& cameraId, int* facing, int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700820 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800821
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800822 int deviceVersion = 0;
823
Emilian Peevf53f66e2017-04-11 14:29:43 +0100824 status_t res;
825 hardware::hidl_version maxVersion{0,0};
826 res = mCameraProviderManager->getHighestSupportedVersion(cameraId.string(),
827 &maxVersion);
828 if (res != OK) return -1;
829 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800830
Emilian Peevf53f66e2017-04-11 14:29:43 +0100831 hardware::CameraInfo info;
832 if (facing) {
833 res = mCameraProviderManager->getCameraInfo(cameraId.string(), &info);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -0800834 if (res != OK) return -1;
Emilian Peevf53f66e2017-04-11 14:29:43 +0100835 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -0700836 if (orientation) {
837 *orientation = info.orientation;
838 }
Igor Murashkin634a5152013-02-20 17:15:11 -0800839 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100840
Igor Murashkin634a5152013-02-20 17:15:11 -0800841 return deviceVersion;
842}
843
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800844Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700845 switch(err) {
846 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800847 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800848 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800849 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
850 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800851 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800852 return STATUS_ERROR(ERROR_DISCONNECTED,
853 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700854 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800855 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
856 "Camera HAL encountered error %d: %s",
857 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700858 }
Igor Murashkinbfc99152013-02-27 12:55:20 -0800859}
860
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800861Status CameraService::makeClient(const sp<CameraService>& cameraService,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800862 const sp<IInterface>& cameraCb, const String16& packageName,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700863 const std::optional<String16>& featureId, const String8& cameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -0700864 int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
865 int servicePid, int deviceVersion, apiLevel effectiveApiLevel,
Ruben Brunkcc776712015-02-17 20:18:47 -0800866 /*out*/sp<BasicClient>* client) {
867
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700868 // Create CameraClient based on device version reported by the HAL.
869 switch(deviceVersion) {
870 case CAMERA_DEVICE_API_VERSION_1_0:
871 ALOGE("Camera using old HAL version: %d", deviceVersion);
872 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
873 "Camera device \"%s\" HAL version %d no longer supported",
874 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800875 break;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700876 case CAMERA_DEVICE_API_VERSION_3_0:
877 case CAMERA_DEVICE_API_VERSION_3_1:
878 case CAMERA_DEVICE_API_VERSION_3_2:
879 case CAMERA_DEVICE_API_VERSION_3_3:
880 case CAMERA_DEVICE_API_VERSION_3_4:
881 case CAMERA_DEVICE_API_VERSION_3_5:
882 case CAMERA_DEVICE_API_VERSION_3_6:
Shuzhen Wang83bff122020-11-20 15:51:39 -0800883 case CAMERA_DEVICE_API_VERSION_3_7:
Ruben Brunkcc776712015-02-17 20:18:47 -0800884 if (effectiveApiLevel == API_1) { // Camera1 API route
885 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800886 *client = new Camera2Client(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800887 cameraId, api1CameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -0700888 facing, sensorOrientation, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700889 servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800890 } else { // Camera2 API route
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800891 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
892 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800893 *client = new CameraDeviceClient(cameraService, tmp, packageName, featureId,
Emilian Peev8b64f282021-03-25 16:49:57 -0700894 cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800895 }
896 break;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700897 default:
Ruben Brunkcc776712015-02-17 20:18:47 -0800898 // Should not be reachable
899 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800900 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800901 "Camera device \"%s\" has unknown HAL version %d",
902 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800903 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800904 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800905}
906
Ruben Brunk6267b532015-04-30 17:44:07 -0700907String8 CameraService::toString(std::set<userid_t> intSet) {
908 String8 s("");
909 bool first = true;
910 for (userid_t i : intSet) {
911 if (first) {
912 s.appendFormat("%d", i);
913 first = false;
914 } else {
915 s.appendFormat(", %d", i);
916 }
917 }
918 return s;
919}
920
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800921int32_t CameraService::mapToInterface(TorchModeStatus status) {
922 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
923 switch (status) {
924 case TorchModeStatus::NOT_AVAILABLE:
925 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
926 break;
927 case TorchModeStatus::AVAILABLE_OFF:
928 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
929 break;
930 case TorchModeStatus::AVAILABLE_ON:
931 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
932 break;
933 default:
934 ALOGW("Unknown new flash status: %d", status);
935 }
936 return serviceStatus;
937}
938
939CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
940 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
941 switch (status) {
942 case CameraDeviceStatus::NOT_PRESENT:
943 serviceStatus = StatusInternal::NOT_PRESENT;
944 break;
945 case CameraDeviceStatus::PRESENT:
946 serviceStatus = StatusInternal::PRESENT;
947 break;
948 case CameraDeviceStatus::ENUMERATING:
949 serviceStatus = StatusInternal::ENUMERATING;
950 break;
951 default:
952 ALOGW("Unknown new HAL device status: %d", status);
953 }
954 return serviceStatus;
955}
956
957int32_t CameraService::mapToInterface(StatusInternal status) {
958 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
959 switch (status) {
960 case StatusInternal::NOT_PRESENT:
961 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
962 break;
963 case StatusInternal::PRESENT:
964 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
965 break;
966 case StatusInternal::ENUMERATING:
967 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
968 break;
969 case StatusInternal::NOT_AVAILABLE:
970 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
971 break;
972 case StatusInternal::UNKNOWN:
973 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
974 break;
975 default:
976 ALOGW("Unknown new internal device status: %d", status);
977 }
978 return serviceStatus;
979}
980
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800981Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -0700982 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700983
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800984 String16 internalPackageName("cameraserver");
Ruben Brunkcc776712015-02-17 20:18:47 -0800985 String8 id = String8::format("%d", cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800986 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800987 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800988 if (!(ret = connectHelper<ICameraClient,Client>(
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800989 sp<ICameraClient>{nullptr}, id, cameraId,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +0900990 internalPackageName, {}, uid, USE_CALLING_PID,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +0000991 API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800992 ).isOk()) {
993 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
Ruben Brunkb2119af2014-05-09 19:57:56 -0700994 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800995 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700996}
997
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800998Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -0700999 /*out*/
1000 CameraParameters* parameters) {
1001
1002 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1003
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001004 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001005
1006 if (parameters == NULL) {
1007 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001008 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001009 }
1010
Ruben Brunkcc776712015-02-17 20:18:47 -08001011 String8 id = String8::format("%d", cameraId);
1012
1013 // Check if we already have parameters
1014 {
1015 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001016 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001017 auto cameraState = getCameraState(id);
1018 if (cameraState == nullptr) {
1019 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001020 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1021 "Invalid camera ID: %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001022 }
1023 CameraParameters p = cameraState->getShimParams();
1024 if (!p.isEmpty()) {
1025 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001026 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001027 }
1028 }
1029
Jayant Chowdhary12361932018-08-27 14:46:13 -07001030 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001031 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001032 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001033 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001034 // Error already logged by callee
1035 return ret;
1036 }
1037
1038 // Check for parameters again
1039 {
1040 // Scope for service lock
1041 Mutex::Autolock lock(mServiceLock);
1042 auto cameraState = getCameraState(id);
1043 if (cameraState == nullptr) {
1044 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001045 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1046 "Invalid camera ID: %s", id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001047 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001048 CameraParameters p = cameraState->getShimParams();
1049 if (!p.isEmpty()) {
1050 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001051 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001052 }
1053 }
1054
Ruben Brunkcc776712015-02-17 20:18:47 -08001055 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1056 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001057 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001058}
1059
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001060// Can camera service trust the caller based on the calling UID?
1061static bool isTrustedCallingUid(uid_t uid) {
1062 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001063 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001064 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001065 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001066 return true;
1067 default:
1068 return false;
1069 }
1070}
1071
Nicholas Sauera3620332019-04-03 14:05:17 -07001072static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1073 PermissionController pc;
1074 uid = pc.getPackageUid(packageName, 0);
1075 if (uid <= 0) {
1076 ALOGE("Unknown package: '%s'", String8(packageName).string());
1077 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
1078 return BAD_VALUE;
1079 }
1080
1081 if (userId < 0) {
1082 ALOGE("Invalid user: %d", userId);
1083 dprintf(err, "Invalid user: %d\n", userId);
1084 return BAD_VALUE;
1085 }
1086
1087 uid = multiuser_get_uid(userId, uid);
1088 return NO_ERROR;
1089}
1090
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001091Status CameraService::validateConnectLocked(const String8& cameraId,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001092 const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
1093 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001094
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001095#ifdef __BRILLO__
1096 UNUSED(clientName8);
1097 UNUSED(clientUid);
1098 UNUSED(clientPid);
1099 UNUSED(originalClientPid);
1100#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001101 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1102 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001103 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001104 return allowed;
1105 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001106#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001107
Jayant Chowdhary12361932018-08-27 14:46:13 -07001108 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001109
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001110 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001111 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1112 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001113 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1114 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001115 }
1116
Ruben Brunkcc776712015-02-17 20:18:47 -08001117 if (getCameraState(cameraId) == nullptr) {
1118 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1119 cameraId.string());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001120 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1121 "No camera device with ID \"%s\" available", cameraId.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001122 }
1123
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001124 status_t err = checkIfDeviceIsUsable(cameraId);
1125 if (err != NO_ERROR) {
1126 switch(err) {
1127 case -ENODEV:
1128 case -EBUSY:
1129 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1130 "No camera device with ID \"%s\" currently available", cameraId.string());
1131 default:
1132 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1133 "Unknown error connecting to ID \"%s\"", cameraId.string());
1134 }
1135 }
1136 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001137}
1138
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001139Status CameraService::validateClientPermissionsLocked(const String8& cameraId,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001140 const String8& clientName8, int& clientUid, int& clientPid,
1141 /*out*/int& originalClientPid) const {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001142 int callingPid = CameraThreadState::getCallingPid();
1143 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001144
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001145 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001146 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001147 clientUid = callingUid;
1148 } else if (!isTrustedCallingUid(callingUid)) {
1149 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1150 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001151 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1152 "Untrusted caller (calling PID %d, UID %d) trying to "
1153 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1154 callingPid, callingUid, cameraId.string(),
1155 clientName8.string(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001156 }
1157
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001158 // Check if we can trust clientPid
1159 if (clientPid == USE_CALLING_PID) {
1160 clientPid = callingPid;
1161 } else if (!isTrustedCallingUid(callingUid)) {
1162 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1163 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001164 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1165 "Untrusted caller (calling PID %d, UID %d) trying to "
1166 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1167 callingPid, callingUid, cameraId.string(),
1168 clientName8.string(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001169 }
1170
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001171 if (shouldRejectSystemCameraConnection(cameraId)) {
1172 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1173 cameraId.c_str());
1174 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
1175 "available", cameraId.string());
1176 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001177 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1178 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1179 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
1180 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
1181 "found while trying to query device kind", cameraId.string());
1182
1183 }
1184
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001185 // If it's not calling from cameraserver, check the permission if the
1186 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1187 // android.permission.SYSTEM_CAMERA for system only camera devices).
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001188 if (callingPid != getpid() &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001189 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001190 !checkPermission(sCameraPermission, clientPid, clientUid)) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001191 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001192 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1193 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
1194 clientName8.string(), clientUid, clientPid, cameraId.string());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001195 }
1196
Svet Ganova453d0d2018-01-11 15:37:58 -08001197 // Make sure the UID is in an active state to use the camera
Svet Ganov7b4ab782018-03-25 12:48:10 -07001198 if (!mUidPolicy->isUidActive(callingUid, String16(clientName8))) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001199 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001200 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1201 clientPid, clientUid);
1202 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001203 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1204 "calling UID %d proc state %" PRId32 ")",
1205 clientName8.string(), clientUid, clientPid, cameraId.string(),
1206 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001207 }
1208
Michael Grooverd1d435a2018-12-18 17:39:42 -08001209 // If sensor privacy is enabled then prevent access to the camera
1210 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1211 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1212 return STATUS_ERROR_FMT(ERROR_DISABLED,
1213 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
1214 "is enabled", clientName8.string(), clientUid, clientPid, cameraId.string());
1215 }
1216
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001217 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1218 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001219 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001220 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001221
Ruben Brunk6267b532015-04-30 17:44:07 -07001222 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001223
Ruben Brunka8ca9152015-04-07 14:23:40 -07001224 // Only allow clients who are being used by the current foreground device user, unless calling
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001225 // from our own process OR the caller is using the cameraserver's HIDL interface.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001226 if (getCurrentServingCall() != BinderCallType::HWBINDER && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001227 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001228 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1229 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
1230 toString(mAllowedUsers).string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001231 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1232 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
1233 clientUserId, cameraId.string());
Ruben Brunk36597b22015-03-20 22:15:57 -07001234 }
1235
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001236 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001237}
1238
1239status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
1240 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001241 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001242 if (cameraState == nullptr) {
1243 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1244 cameraId.string());
1245 return -ENODEV;
1246 }
1247
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001248 StatusInternal currentStatus = cameraState->getStatus();
1249 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001250 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
1251 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001252 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001253 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001254 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
1255 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001256 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001257 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001258
Ruben Brunkcc776712015-02-17 20:18:47 -08001259 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001260}
1261
Ruben Brunkcc776712015-02-17 20:18:47 -08001262void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001263 const CameraService::DescriptorPtr& desc, int oomScoreOffset) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001264
Ruben Brunkcc776712015-02-17 20:18:47 -08001265 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001266 auto clientDescriptor =
1267 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
1268 oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08001269 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1270
1271 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
1272 String8(client->getPackageName()));
1273
1274 if (evicted.size() > 0) {
1275 // This should never happen - clients should already have been removed in disconnect
1276 for (auto& i : evicted) {
1277 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
1278 __FUNCTION__, i->getKey().string());
1279 }
1280
1281 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1282 __FUNCTION__);
1283 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001284
1285 // And register a death notification for the client callback. Do
1286 // this last to avoid Binder policy where a nested Binder
1287 // transaction might be pre-empted to service the client death
1288 // notification if the client process dies before linkToDeath is
1289 // invoked.
1290 sp<IBinder> remoteCallback = client->getRemote();
1291 if (remoteCallback != nullptr) {
1292 remoteCallback->linkToDeath(this);
1293 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001294}
1295
1296status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
1297 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001298 int oomScoreOffset,
Ruben Brunkcc776712015-02-17 20:18:47 -08001299 /*out*/
1300 sp<BasicClient>* client,
1301 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001302 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001303 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001304 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001305 DescriptorPtr clientDescriptor;
1306 {
1307 if (effectiveApiLevel == API_1) {
1308 // If we are using API1, any existing client for this camera ID with the same remote
1309 // should be returned rather than evicted to allow MediaRecorder to work properly.
1310
1311 auto current = mActiveClientManager.get(cameraId);
1312 if (current != nullptr) {
1313 auto clientSp = current->getValue();
1314 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001315 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
1316 ALOGW("CameraService connect called from same client, but with a different"
1317 " API level, evicting prior client...");
1318 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001319 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001320 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001321 *client = clientSp;
1322 return NO_ERROR;
1323 }
1324 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001325 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001326 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001327
Ruben Brunkcc776712015-02-17 20:18:47 -08001328 // Get current active client PIDs
1329 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1330 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001331
Emilian Peev8131a262017-02-01 12:33:43 +00001332 std::vector<int> priorityScores(ownerPids.size());
1333 std::vector<int> states(ownerPids.size());
Igor Murashkine6800ce2013-03-04 17:25:57 -08001334
Emilian Peev8131a262017-02-01 12:33:43 +00001335 // Get priority scores of all active PIDs
1336 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1337 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1338 /*out*/&priorityScores[0]);
1339 if (err != OK) {
1340 ALOGE("%s: Priority score query failed: %d",
1341 __FUNCTION__, err);
1342 return err;
1343 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001344
Ruben Brunkcc776712015-02-17 20:18:47 -08001345 // Update all active clients' priorities
Emilian Peev8131a262017-02-01 12:33:43 +00001346 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
Ruben Brunkcc776712015-02-17 20:18:47 -08001347 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
Emilian Peev8131a262017-02-01 12:33:43 +00001348 pidToPriorityMap.emplace(ownerPids[i],
Jayant Chowdharyc578a502019-05-08 10:57:54 -07001349 resource_policy::ClientPriority(priorityScores[i], states[i],
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001350 /* isVendorClient won't get copied over*/ false,
1351 /* oomScoreOffset won't get copied over*/ 0));
Ruben Brunkcc776712015-02-17 20:18:47 -08001352 }
1353 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001354
Ruben Brunkcc776712015-02-17 20:18:47 -08001355 // Get state for the given cameraId
1356 auto state = getCameraState(cameraId);
1357 if (state == nullptr) {
1358 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1359 clientPid, cameraId.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001360 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001361 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001362 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001363
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001364 int32_t actualScore = priorityScores[priorityScores.size() - 1];
1365 int32_t actualState = states[states.size() - 1];
1366
1367 // Make descriptor for incoming client. We store the oomScoreOffset
1368 // since we might need it later on new handleEvictionsLocked and
1369 // ProcessInfoService would not take that into account.
Shuzhen Wang2db86ff2018-04-25 01:11:17 +00001370 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001371 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001372 state->getConflicting(), actualScore, clientPid, actualState,
1373 oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08001374
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001375 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1376
Ruben Brunkcc776712015-02-17 20:18:47 -08001377 // Find clients that would be evicted
1378 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1379
1380 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1381 // background, so we cannot do evictions
1382 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1383 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1384 " priority).", clientPid);
1385
1386 sp<BasicClient> clientSp = clientDescriptor->getValue();
1387 String8 curTime = getFormattedCurrentTime();
1388 auto incompatibleClients =
1389 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1390
1391 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Emilian Peev8131a262017-02-01 12:33:43 +00001392 "(PID %d, score %d state %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001393 cameraId.string(), packageName.string(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001394 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001395
1396 for (auto& i : incompatibleClients) {
1397 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001398 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
1399 i->getKey().string(),
1400 String8{i->getValue()->getPackageName()}.string(),
1401 i->getOwnerId(), i->getPriority().getScore(),
1402 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001403 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00001404 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(),
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001405 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001406 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001407 }
1408
1409 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001410 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001411 mEventLog.add(msg);
1412
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001413 auto current = mActiveClientManager.get(cameraId);
1414 if (current != nullptr) {
1415 return -EBUSY; // CAMERA_IN_USE
1416 } else {
1417 return -EUSERS; // MAX_CAMERAS_IN_USE
1418 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001419 }
1420
1421 for (auto& i : evicted) {
1422 sp<BasicClient> clientSp = i->getValue();
1423 if (clientSp.get() == nullptr) {
1424 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1425
1426 // TODO: Remove this
1427 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1428 __FUNCTION__);
1429 mActiveClientManager.remove(i);
1430 continue;
1431 }
1432
1433 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1434 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001435 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001436
Ruben Brunkcc776712015-02-17 20:18:47 -08001437 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001438 logEvent(String8::format("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00001439 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1440 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001441 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
Emilian Peev8131a262017-02-01 12:33:43 +00001442 i->getOwnerId(), i->getPriority().getScore(),
1443 i->getPriority().getState(), cameraId.string(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001444 packageName.string(), clientPid, clientPriority.getScore(),
1445 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08001446
1447 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001448 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001449 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001450 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001451 }
1452
Ruben Brunkcc776712015-02-17 20:18:47 -08001453 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1454 // other clients from connecting in mServiceLockWrapper if held
1455 mServiceLock.unlock();
1456
1457 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07001458 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001459
1460 // Destroy evicted clients
1461 for (auto& i : evictedClients) {
1462 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001463 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001464 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001465
Jayant Chowdhary12361932018-08-27 14:46:13 -07001466 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08001467
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001468 for (const auto& i : evictedClients) {
1469 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1470 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1471 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1472 if (ret == TIMED_OUT) {
1473 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1474 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1475 mActiveClientManager.toString().string());
1476 return -EBUSY;
1477 }
1478 if (ret != NO_ERROR) {
1479 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1480 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1481 ret, mActiveClientManager.toString().string());
1482 return ret;
1483 }
1484 }
1485
1486 evictedClients.clear();
1487
Ruben Brunkcc776712015-02-17 20:18:47 -08001488 // Once clients have been disconnected, relock
1489 mServiceLock.lock();
1490
1491 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1492 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1493 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001494 }
1495
Ruben Brunkcc776712015-02-17 20:18:47 -08001496 *partial = clientDescriptor;
1497 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001498}
1499
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001500Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001501 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001502 int api1CameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001503 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001504 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001505 int clientPid,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001506 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001507 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001508
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001509 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001510 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001511
1512 String8 id = cameraIdIntToStr(api1CameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001513 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001514 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001515 clientPackageName, {}, clientUid, clientPid, API_1,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001516 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001517
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001518 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001519 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001520 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001521 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001522 }
1523
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001524 *device = client;
1525 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001526}
1527
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001528bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
1529 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001530 // If the client is not a vendor client, don't add listener if
1531 // a) the camera is a publicly hidden secure camera OR
1532 // b) the camera is a system only camera and the client doesn't
1533 // have android.permission.SYSTEM_CAMERA permissions.
1534 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
1535 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1536 !hasPermissionsForSystemCamera(clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001537 return true;
1538 }
1539 return false;
1540}
1541
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001542bool CameraService::shouldRejectSystemCameraConnection(const String8& cameraId) const {
1543 // Rules for rejection:
1544 // 1) If cameraserver tries to access this camera device, accept the
1545 // connection.
1546 // 2) The camera device is a publicly hidden secure camera device AND some
1547 // component is trying to access it on a non-hwbinder thread (generally a non HAL client),
1548 // reject it.
1549 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
1550 // and the serving thread is a non hwbinder thread, the client must have
1551 // android.permission.SYSTEM_CAMERA permissions to connect.
1552
1553 int cPid = CameraThreadState::getCallingPid();
1554 int cUid = CameraThreadState::getCallingUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001555 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
1556 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001557 // This isn't a known camera ID, so it's not a system camera
1558 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
1559 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001560 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001561
1562 // (1) Cameraserver trying to connect, accept.
1563 if (CameraThreadState::getCallingPid() == getpid()) {
1564 return false;
1565 }
1566 // (2)
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001567 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001568 systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
1569 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
1570 return true;
1571 }
1572 // (3) Here we only check for permissions if it is a system only camera device. This is since
1573 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
1574 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
1575 // same behavior for system camera devices.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001576 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001577 systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1578 !hasPermissionsForSystemCamera(cPid, cUid)) {
1579 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
1580 cameraId.c_str());
1581 return true;
1582 }
1583
1584 return false;
1585}
1586
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001587Status CameraService::connectDevice(
1588 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001589 const String16& cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001590 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001591 const std::optional<String16>& clientFeatureId,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001592 int clientUid, int oomScoreOffset,
Ruben Brunkcc776712015-02-17 20:18:47 -08001593 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001594 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001595
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001596 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001597 Status ret = Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001598 String8 id = String8(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001599 sp<CameraDeviceClient> client = nullptr;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001600 String16 clientPackageNameAdj = clientPackageName;
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001601 int callingPid = CameraThreadState::getCallingPid();
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001602
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001603 if (getCurrentServingCall() == BinderCallType::HWBINDER) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001604 std::string vendorClient =
1605 StringPrintf("vendor.client.pid<%d>", CameraThreadState::getCallingPid());
1606 clientPackageNameAdj = String16(vendorClient.c_str());
1607 }
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001608
1609 if (oomScoreOffset < 0) {
1610 String8 msg =
1611 String8::format("Cannot increase the priority of a client %s pid %d for "
1612 "camera id %s", String8(clientPackageNameAdj).string(), callingPid,
1613 id.string());
1614 ALOGE("%s: %s", __FUNCTION__, msg.string());
1615 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
1616 }
1617
1618 // enforce system camera permissions
1619 if (oomScoreOffset > 0 &&
1620 !hasPermissionsForSystemCamera(callingPid, CameraThreadState::getCallingUid())) {
1621 String8 msg =
1622 String8::format("Cannot change the priority of a client %s pid %d for "
1623 "camera id %s without SYSTEM_CAMERA permissions",
1624 String8(clientPackageNameAdj).string(), callingPid, id.string());
1625 ALOGE("%s: %s", __FUNCTION__, msg.string());
1626 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.string());
1627 }
1628
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001629 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001630 /*api1CameraId*/-1, clientPackageNameAdj, clientFeatureId,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001631 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, oomScoreOffset,
1632 /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08001633
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001634 if(!ret.isOk()) {
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001635 logRejected(id, callingPid, String8(clientPackageNameAdj), ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001636 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001637 }
1638
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001639 *device = client;
1640 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001641}
1642
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001643template<class CALLBACK, class CLIENT>
1644Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001645 int api1CameraId, const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001646 const std::optional<String16>& clientFeatureId, int clientUid, int clientPid,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001647 apiLevel effectiveApiLevel, bool shimUpdateOnly, int oomScoreOffset,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001648 /*out*/sp<CLIENT>& device) {
1649 binder::Status ret = binder::Status::ok();
1650
1651 String8 clientName8(clientPackageName);
1652
1653 int originalClientPid = 0;
1654
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001655 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001656 "Camera API version %d", clientPid, clientName8.string(), cameraId.string(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001657 static_cast<int>(effectiveApiLevel));
1658
Shuzhen Wang316781a2020-08-18 18:11:01 -07001659 nsecs_t openTimeNs = systemTime();
1660
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001661 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001662 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07001663 int orientation = 0;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001664 bool isNdk = (clientPackageName.size() == 0);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001665 {
1666 // Acquire mServiceLock and prevent other clients from connecting
1667 std::unique_ptr<AutoConditionLock> lock =
1668 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1669
1670 if (lock == nullptr) {
1671 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
1672 , clientPid);
1673 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1674 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
1675 cameraId.string(), clientName8.string(), clientPid);
1676 }
1677
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07001678 // Enforce client permissions and do basic validity checks
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001679 if(!(ret = validateConnectLocked(cameraId, clientName8,
1680 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
1681 return ret;
1682 }
1683
1684 // Check the shim parameters after acquiring lock, if they have already been updated and
1685 // we were doing a shim update, return immediately
1686 if (shimUpdateOnly) {
1687 auto cameraState = getCameraState(cameraId);
1688 if (cameraState != nullptr) {
1689 if (!cameraState->getShimParams().isEmpty()) return ret;
1690 }
1691 }
1692
1693 status_t err;
1694
1695 sp<BasicClient> clientTmp = nullptr;
1696 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
1697 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001698 IInterface::asBinder(cameraCb), clientName8, oomScoreOffset, /*out*/&clientTmp,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001699 /*out*/&partial)) != NO_ERROR) {
1700 switch (err) {
1701 case -ENODEV:
1702 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1703 "No camera device with ID \"%s\" currently available",
1704 cameraId.string());
1705 case -EBUSY:
1706 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1707 "Higher-priority client using camera, ID \"%s\" currently unavailable",
1708 cameraId.string());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001709 case -EUSERS:
1710 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1711 "Too many cameras already open, cannot open camera \"%s\"",
1712 cameraId.string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001713 default:
1714 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1715 "Unexpected error %s (%d) opening camera \"%s\"",
1716 strerror(-err), err, cameraId.string());
1717 }
1718 }
1719
1720 if (clientTmp.get() != nullptr) {
1721 // Handle special case for API1 MediaRecorder where the existing client is returned
1722 device = static_cast<CLIENT*>(clientTmp.get());
1723 return ret;
1724 }
1725
1726 // give flashlight a chance to close devices if necessary.
1727 mFlashlight->prepareDeviceOpen(cameraId);
1728
Emilian Peevb91f1802021-03-23 14:50:28 -07001729 int deviceVersion = getDeviceVersion(cameraId, /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08001730 if (facing == -1) {
1731 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.string());
1732 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1733 "Unable to get camera device \"%s\" facing", cameraId.string());
1734 }
1735
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001736 sp<BasicClient> tmp = nullptr;
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001737 if(!(ret = makeClient(this, cameraCb, clientPackageName, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07001738 cameraId, api1CameraId, facing, orientation,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001739 clientPid, clientUid, getpid(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001740 deviceVersion, effectiveApiLevel,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001741 /*out*/&tmp)).isOk()) {
1742 return ret;
1743 }
1744 client = static_cast<CLIENT*>(tmp.get());
1745
1746 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
1747 __FUNCTION__);
1748
Emilian Peevbd8c5032018-02-14 23:05:40 +00001749 err = client->initialize(mCameraProviderManager, mMonitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001750 if (err != OK) {
1751 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001752 // Errors could be from the HAL module open call or from AppOpsManager
1753 switch(err) {
1754 case BAD_VALUE:
1755 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1756 "Illegal argument to HAL module for camera \"%s\"", cameraId.string());
1757 case -EBUSY:
1758 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1759 "Camera \"%s\" is already open", cameraId.string());
1760 case -EUSERS:
1761 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1762 "Too many cameras already open, cannot open camera \"%s\"",
1763 cameraId.string());
1764 case PERMISSION_DENIED:
1765 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1766 "No permission to open camera \"%s\"", cameraId.string());
1767 case -EACCES:
1768 return STATUS_ERROR_FMT(ERROR_DISABLED,
1769 "Camera \"%s\" disabled by policy", cameraId.string());
1770 case -ENODEV:
1771 default:
1772 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1773 "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
1774 strerror(-err), err);
1775 }
1776 }
1777
1778 // Update shim paremeters for legacy clients
1779 if (effectiveApiLevel == API_1) {
1780 // Assume we have always received a Client subclass for API1
1781 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
1782 String8 rawParams = shimClient->getParameters();
1783 CameraParameters params(rawParams);
1784
1785 auto cameraState = getCameraState(cameraId);
1786 if (cameraState != nullptr) {
1787 cameraState->setShimParams(params);
1788 } else {
1789 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
1790 __FUNCTION__, cameraId.string());
1791 }
1792 }
1793
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001794 // Set rotate-and-crop override behavior
1795 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
1796 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
Emilian Peevb91f1802021-03-23 14:50:28 -07001797 } else if (CameraServiceProxyWrapper::isRotateAndCropOverrideNeeded(clientPackageName,
1798 orientation, facing)) {
1799 client->setRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_90);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001800 }
1801
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08001802 // Set camera muting behavior
1803 if (client->supportsCameraMute()) {
Evan Severson09ab4002021-02-10 14:15:19 -08001804 bool isCameraPrivacyEnabled =
1805 mSensorPrivacyPolicy->isCameraPrivacyEnabled(multiuser_get_user_id(clientUid));
1806 client->setCameraMute(mOverrideCameraMuteMode || isCameraPrivacyEnabled);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08001807 }
1808
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001809 if (shimUpdateOnly) {
1810 // If only updating legacy shim parameters, immediately disconnect client
1811 mServiceLock.unlock();
1812 client->disconnect();
1813 mServiceLock.lock();
1814 } else {
1815 // Otherwise, add client to active clients list
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001816 finishConnectLocked(client, partial, oomScoreOffset);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001817 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001818
1819 client->setImageDumpMask(mImageDumpMask);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001820 } // lock is destroyed, allow further connect calls
1821
1822 // Important: release the mutex here so the client can call back into the service from its
1823 // destructor (can be at the end of the call)
1824 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001825
1826 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
1827 CameraServiceProxyWrapper::logOpen(cameraId, facing, clientPackageName,
1828 effectiveApiLevel, isNdk, openLatencyMs);
1829
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001830 return ret;
1831}
1832
Emilian Peevb2bc5a42019-11-20 16:02:14 -08001833status_t CameraService::addOfflineClient(String8 cameraId, sp<BasicClient> offlineClient) {
1834 if (offlineClient.get() == nullptr) {
1835 return BAD_VALUE;
1836 }
1837
1838 {
1839 // Acquire mServiceLock and prevent other clients from connecting
1840 std::unique_ptr<AutoConditionLock> lock =
1841 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1842
1843 if (lock == nullptr) {
1844 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
1845 , __FUNCTION__, offlineClient->getClientPid());
1846 return TIMED_OUT;
1847 }
1848
1849 auto onlineClientDesc = mActiveClientManager.get(cameraId);
1850 if (onlineClientDesc.get() == nullptr) {
1851 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
1852 cameraId.c_str());
1853 return BAD_VALUE;
1854 }
1855
1856 // Offline clients do not evict or conflict with other online devices. Resource sharing
1857 // conflicts are handled by the camera provider which will either succeed or fail before
1858 // reaching this method.
1859 const auto& onlinePriority = onlineClientDesc->getPriority();
1860 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
1861 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
1862 /*conflictingKeys*/ std::set<String8>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001863 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
1864 /*ommScoreOffset*/ 0);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08001865
1866 // Allow only one offline device per camera
1867 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
1868 if (!incompatibleClients.empty()) {
1869 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
1870 return BAD_VALUE;
1871 }
1872
1873 auto err = offlineClient->initialize(mCameraProviderManager, mMonitorTags);
1874 if (err != OK) {
1875 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
1876 return err;
1877 }
1878
1879 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
1880 if (evicted.size() > 0) {
1881 for (auto& i : evicted) {
1882 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
1883 __FUNCTION__, i->getKey().string());
1884 }
1885
1886 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
1887 "properly", __FUNCTION__);
1888
1889 return BAD_VALUE;
1890 }
1891
1892 logConnectedOffline(offlineClientDesc->getKey(),
1893 static_cast<int>(offlineClientDesc->getOwnerId()),
1894 String8(offlineClient->getPackageName()));
1895
1896 sp<IBinder> remoteCallback = offlineClient->getRemote();
1897 if (remoteCallback != nullptr) {
1898 remoteCallback->linkToDeath(this);
1899 }
1900 } // lock is destroyed, allow further connect calls
1901
1902 return OK;
1903}
1904
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001905Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001906 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001907 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001908
1909 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07001910 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001911 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001912 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1913 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001914 }
1915
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001916 String8 id = String8(cameraId.string());
Jayant Chowdhary12361932018-08-27 14:46:13 -07001917 int uid = CameraThreadState::getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001918
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07001919 if (shouldRejectSystemCameraConnection(id)) {
1920 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
1921 " for system only device %s: ", id.string());
1922 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001923 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08001924 auto state = getCameraState(id);
1925 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001926 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001927 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1928 "Camera ID \"%s\" is a not valid camera ID", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001929 }
1930
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001931 StatusInternal cameraStatus = state->getStatus();
1932 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001933 cameraStatus != StatusInternal::NOT_AVAILABLE) {
1934 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001935 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1936 "Camera ID \"%s\" is a not valid camera ID", id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001937 }
1938
1939 {
1940 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001941 TorchModeStatus status;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001942 status_t err = getTorchStatusLocked(id, &status);
1943 if (err != OK) {
1944 if (err == NAME_NOT_FOUND) {
1945 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1946 "Camera \"%s\" does not have a flash unit", id.string());
1947 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001948 ALOGE("%s: getting current torch status failed for camera %s",
1949 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001950 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1951 "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
1952 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001953 }
1954
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001955 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001956 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001957 ALOGE("%s: torch mode of camera %s is not available because "
1958 "camera is in use", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001959 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1960 "Torch for camera \"%s\" is not available due to an existing camera user",
1961 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001962 } else {
1963 ALOGE("%s: torch mode of camera %s is not available due to "
1964 "insufficient resources", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001965 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1966 "Torch for camera \"%s\" is not available due to insufficient resources",
1967 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001968 }
1969 }
1970 }
1971
Ruben Brunk99e69712015-05-26 17:25:07 -07001972 {
1973 // Update UID map - this is used in the torch status changed callbacks, so must be done
1974 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07001975 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -07001976 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
1977 mTorchUidMap[id].first = uid;
1978 mTorchUidMap[id].second = uid;
1979 } else {
1980 // Set the pending UID
1981 mTorchUidMap[id].first = uid;
1982 }
1983 }
1984
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001985 status_t err = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07001986
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001987 if (err != OK) {
1988 int32_t errorCode;
1989 String8 msg;
1990 switch (err) {
1991 case -ENOSYS:
1992 msg = String8::format("Camera \"%s\" has no flashlight",
1993 id.string());
1994 errorCode = ERROR_ILLEGAL_ARGUMENT;
1995 break;
1996 default:
1997 msg = String8::format(
1998 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
1999 id.string(), enabled, strerror(-err), err);
2000 errorCode = ERROR_INVALID_OPERATION;
2001 }
2002 ALOGE("%s: %s", __FUNCTION__, msg.string());
Rucha Katakward9ea6452021-05-06 11:57:16 -07002003 logServiceError(msg,errorCode);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002004 return STATUS_ERROR(errorCode, msg.string());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002005 }
2006
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002007 {
2008 // update the link to client's death
2009 Mutex::Autolock al(mTorchClientMapMutex);
2010 ssize_t index = mTorchClientMap.indexOfKey(id);
2011 if (enabled) {
2012 if (index == NAME_NOT_FOUND) {
2013 mTorchClientMap.add(id, clientBinder);
2014 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07002015 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002016 mTorchClientMap.replaceValueAt(index, clientBinder);
2017 }
2018 clientBinder->linkToDeath(this);
2019 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07002020 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002021 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002022 }
2023
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002024 int clientPid = CameraThreadState::getCallingPid();
2025 const char *id_cstr = id.c_str();
2026 const char *torchState = enabled ? "on" : "off";
2027 ALOGI("Torch for camera id %s turned %s for client PID %d", id_cstr, torchState, clientPid);
2028 logTorchEvent(id_cstr, torchState , clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002029 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002030}
2031
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002032Status CameraService::notifySystemEvent(int32_t eventId,
2033 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002034 const int pid = CameraThreadState::getCallingPid();
2035 const int selfPid = getpid();
2036
2037 // Permission checks
2038 if (pid != selfPid) {
2039 // Ensure we're being called by system_server, or similar process with
2040 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002041 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002042 const int uid = CameraThreadState::getCallingUid();
2043 ALOGE("Permission Denial: cannot send updates to camera service about system"
2044 " events from pid=%d, uid=%d", pid, uid);
2045 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09002046 "No permission to send updates to camera service about system events"
2047 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002048 }
2049 }
2050
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002051 ATRACE_CALL();
2052
Ruben Brunk36597b22015-03-20 22:15:57 -07002053 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002054 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08002055 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002056 // from a system server crash
2057 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08002058 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002059 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07002060 break;
2061 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002062 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07002063 default: {
2064 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
2065 eventId);
2066 break;
2067 }
2068 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002069 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002070}
2071
Emilian Peev53722fa2019-02-22 17:47:20 -08002072void CameraService::notifyMonitoredUids() {
2073 Mutex::Autolock lock(mStatusListenerLock);
2074
2075 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002076 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Emilian Peev53722fa2019-02-22 17:47:20 -08002077 if (!ret.isOk()) {
2078 ALOGE("%s: Failed to trigger permission callback: %d", __FUNCTION__,
2079 ret.exceptionCode());
2080 }
2081 }
2082}
2083
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002084Status CameraService::notifyDeviceStateChange(int64_t newState) {
2085 const int pid = CameraThreadState::getCallingPid();
2086 const int selfPid = getpid();
2087
2088 // Permission checks
2089 if (pid != selfPid) {
2090 // Ensure we're being called by system_server, or similar process with
2091 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002092 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002093 const int uid = CameraThreadState::getCallingUid();
2094 ALOGE("Permission Denial: cannot send updates to camera service about device"
2095 " state changes from pid=%d, uid=%d", pid, uid);
2096 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2097 "No permission to send updates to camera service about device state"
2098 " changes from pid=%d, uid=%d", pid, uid);
2099 }
2100 }
2101
2102 ATRACE_CALL();
2103
2104 using hardware::camera::provider::V2_5::DeviceState;
2105 hardware::hidl_bitfield<DeviceState> newDeviceState{};
2106 if (newState & ICameraService::DEVICE_STATE_BACK_COVERED) {
2107 newDeviceState |= DeviceState::BACK_COVERED;
2108 }
2109 if (newState & ICameraService::DEVICE_STATE_FRONT_COVERED) {
2110 newDeviceState |= DeviceState::FRONT_COVERED;
2111 }
2112 if (newState & ICameraService::DEVICE_STATE_FOLDED) {
2113 newDeviceState |= DeviceState::FOLDED;
2114 }
2115 // Only map vendor bits directly
2116 uint64_t vendorBits = static_cast<uint64_t>(newState) & 0xFFFFFFFF00000000l;
2117 newDeviceState |= vendorBits;
2118
2119 ALOGV("%s: New device state 0x%" PRIx64, __FUNCTION__, newDeviceState);
2120 Mutex::Autolock l(mServiceLock);
2121 mCameraProviderManager->notifyDeviceStateChange(newDeviceState);
2122
2123 return Status::ok();
2124}
2125
Emilian Peev8b64f282021-03-25 16:49:57 -07002126Status CameraService::notifyDisplayConfigurationChange() {
2127 ATRACE_CALL();
2128 const int callingPid = CameraThreadState::getCallingPid();
2129 const int selfPid = getpid();
2130
2131 // Permission checks
2132 if (callingPid != selfPid) {
2133 // Ensure we're being called by system_server, or similar process with
2134 // permissions to notify the camera service about system events
2135 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
2136 const int uid = CameraThreadState::getCallingUid();
2137 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
2138 " changes from pid=%d, uid=%d", callingPid, uid);
2139 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2140 "No permission to send updates to camera service about orientation"
2141 " changes from pid=%d, uid=%d", callingPid, uid);
2142 }
2143 }
2144
2145 Mutex::Autolock lock(mServiceLock);
2146
2147 // Don't do anything if rotate-and-crop override via cmd is active
2148 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
2149
2150 const auto clients = mActiveClientManager.getAll();
2151 for (auto& current : clients) {
2152 if (current != nullptr) {
2153 const auto basicClient = current->getValue();
2154 if (basicClient.get() != nullptr) {
2155 if (CameraServiceProxyWrapper::isRotateAndCropOverrideNeeded(
2156 basicClient->getPackageName(), basicClient->getCameraOrientation(),
2157 basicClient->getCameraFacing())) {
2158 basicClient->setRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_90);
2159 } else {
2160 basicClient->setRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE);
2161 }
2162 }
2163 }
2164 }
2165
2166 return Status::ok();
2167}
2168
2169Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002170 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
2171 ATRACE_CALL();
2172 if (!concurrentCameraIds) {
2173 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
2174 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
2175 }
2176
2177 if (!mInitialized) {
2178 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Rucha Katakward9ea6452021-05-06 11:57:16 -07002179 logServiceError(String8::format("Camera subsystem is not available"),ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002180 return STATUS_ERROR(ERROR_DISCONNECTED,
2181 "Camera subsystem is not available");
2182 }
2183 // First call into the provider and get the set of concurrent camera
2184 // combinations
2185 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07002186 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002187 for (auto &combination : concurrentCameraCombinations) {
2188 std::vector<std::string> validCombination;
2189 for (auto &cameraId : combination) {
2190 // if the camera state is not present, skip
2191 String8 cameraIdStr(cameraId.c_str());
2192 auto state = getCameraState(cameraIdStr);
2193 if (state == nullptr) {
2194 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
2195 continue;
2196 }
2197 StatusInternal status = state->getStatus();
2198 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
2199 continue;
2200 }
2201 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
2202 continue;
2203 }
2204 validCombination.push_back(cameraId);
2205 }
2206 if (validCombination.size() != 0) {
2207 concurrentCameraIds->push_back(std::move(validCombination));
2208 }
2209 }
2210 return Status::ok();
2211}
2212
2213Status CameraService::isConcurrentSessionConfigurationSupported(
2214 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
2215 /*out*/bool* isSupported) {
2216 if (!isSupported) {
2217 ALOGE("%s: isSupported is NULL", __FUNCTION__);
2218 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
2219 }
2220
2221 if (!mInitialized) {
2222 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2223 return STATUS_ERROR(ERROR_DISCONNECTED,
2224 "Camera subsystem is not available");
2225 }
2226
2227 // Check for camera permissions
2228 int callingPid = CameraThreadState::getCallingPid();
2229 int callingUid = CameraThreadState::getCallingUid();
2230 if ((callingPid != getpid()) && !checkPermission(sCameraPermission, callingPid, callingUid)) {
2231 ALOGE("%s: pid %d doesn't have camera permissions", __FUNCTION__, callingPid);
2232 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2233 "android.permission.CAMERA needed to call"
2234 "isConcurrentSessionConfigurationSupported");
2235 }
2236
2237 status_t res =
2238 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
2239 cameraIdsAndSessionConfigurations, isSupported);
2240 if (res != OK) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07002241 logServiceError(String8::format("Unable to query session configuration support"),
2242 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002243 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
2244 "support %s (%d)", strerror(-res), res);
2245 }
2246 return Status::ok();
2247}
2248
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002249Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
2250 /*out*/
2251 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002252 return addListenerHelper(listener, cameraStatuses);
2253}
2254
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002255binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
2256 std::vector<hardware::CameraStatus>* cameraStatuses) {
2257 return addListenerHelper(listener, cameraStatuses, false, true);
2258}
2259
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002260Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
2261 /*out*/
2262 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002263 bool isVendorListener, bool isProcessLocalTest) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002264
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002265 ATRACE_CALL();
2266
Igor Murashkinbfc99152013-02-27 12:55:20 -08002267 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08002268
Ruben Brunk3450ba72015-06-16 11:00:37 -07002269 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002270 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002271 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002272 }
2273
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002274 auto clientUid = CameraThreadState::getCallingUid();
2275 auto clientPid = CameraThreadState::getCallingPid();
Shuzhen Wang695044d2020-03-06 09:02:23 -08002276 bool openCloseCallbackAllowed = checkPermission(sCameraOpenCloseListenerPermission,
2277 clientPid, clientUid);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002278
Igor Murashkinbfc99152013-02-27 12:55:20 -08002279 Mutex::Autolock lock(mServiceLock);
2280
Ruben Brunkcc776712015-02-17 20:18:47 -08002281 {
2282 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08002283 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002284 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002285 ALOGW("%s: Tried to add listener %p which was already subscribed",
2286 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002287 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08002288 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002289 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002290
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002291 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08002292 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
2293 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002294 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08002295 if (ret != NO_ERROR) {
2296 String8 msg = String8::format("Failed to initialize service listener: %s (%d)",
2297 strerror(-ret), ret);
Rucha Katakward9ea6452021-05-06 11:57:16 -07002298 logServiceError(msg,ERROR_ILLEGAL_ARGUMENT);
Emilian Peev53722fa2019-02-22 17:47:20 -08002299 ALOGE("%s: %s", __FUNCTION__, msg.string());
2300 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
2301 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002302 // The listener still needs to be added to the list of listeners, regardless of what
2303 // permissions the listener process has / whether it is a vendor listener. Since it might be
2304 // eligible to listen to other camera ids.
2305 mListenerList.emplace_back(serviceListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08002306 mUidPolicy->registerMonitorUid(clientUid);
Igor Murashkinbfc99152013-02-27 12:55:20 -08002307 }
2308
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002309 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07002310 {
Ruben Brunkcc776712015-02-17 20:18:47 -08002311 Mutex::Autolock lock(mCameraStatesLock);
2312 for (auto& i : mCameraStates) {
Shuzhen Wang43858162020-01-10 13:42:15 -08002313 cameraStatuses->emplace_back(i.first,
2314 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds());
Igor Murashkincba2c162013-03-20 15:56:31 -07002315 }
2316 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002317 // Remove the camera statuses that should be hidden from the client, we do
2318 // this after collecting the states in order to avoid holding
2319 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
2320 // the same time.
2321 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
2322 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
2323 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
2324 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
2325 ALOGE("%s: Invalid camera id %s, skipping status update",
2326 __FUNCTION__, s.cameraId.c_str());
2327 return true;
2328 }
2329 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
2330 clientUid);}), cameraStatuses->end());
2331
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002332 //cameraStatuses will have non-eligible camera ids removed.
2333 std::set<String16> idsChosenForCallback;
2334 for (const auto &s : *cameraStatuses) {
2335 idsChosenForCallback.insert(String16(s.cameraId));
2336 }
Igor Murashkincba2c162013-03-20 15:56:31 -07002337
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002338 /*
2339 * Immediately signal current torch status to this listener only
2340 * This may be a subset of all the devices, so don't include it in the response directly
2341 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002342 {
2343 Mutex::Autolock al(mTorchStatusMutex);
2344 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002345 String16 id = String16(mTorchStatusMap.keyAt(i).string());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002346 // The camera id is visible to the client. Fine to send torch
2347 // callback.
2348 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
2349 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
2350 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002351 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002352 }
2353
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002354 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08002355}
Ruben Brunkcc776712015-02-17 20:18:47 -08002356
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002357Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002358 ATRACE_CALL();
2359
Igor Murashkinbfc99152013-02-27 12:55:20 -08002360 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
2361
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002362 if (listener == 0) {
2363 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002364 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002365 }
2366
Igor Murashkinbfc99152013-02-27 12:55:20 -08002367 Mutex::Autolock lock(mServiceLock);
2368
Ruben Brunkcc776712015-02-17 20:18:47 -08002369 {
2370 Mutex::Autolock lock(mStatusListenerLock);
2371 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002372 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
2373 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid());
2374 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08002375 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002376 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002377 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002378 }
2379 }
2380
2381 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
2382 __FUNCTION__, listener.get());
2383
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002384 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08002385}
2386
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002387Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002388
2389 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002390 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
2391
2392 if (parameters == NULL) {
2393 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002394 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07002395 }
2396
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002397 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002398
2399 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002400 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07002401 // Error logged by caller
2402 return ret;
2403 }
2404
2405 String8 shimParamsString8 = shimParams.flatten();
2406 String16 shimParamsString16 = String16(shimParamsString8);
2407
2408 *parameters = shimParamsString16;
2409
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002410 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07002411}
2412
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002413Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
2414 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002415 ATRACE_CALL();
2416
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002417 const String8 id = String8(cameraId);
2418
2419 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002420
2421 switch (apiVersion) {
2422 case API_VERSION_1:
2423 case API_VERSION_2:
2424 break;
2425 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002426 String8 msg = String8::format("Unknown API version %d", apiVersion);
2427 ALOGE("%s: %s", __FUNCTION__, msg.string());
2428 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002429 }
2430
Emilian Peev28ad2ea2017-02-07 16:14:32 +00002431 int deviceVersion = getDeviceVersion(id);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002432 switch (deviceVersion) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002433 case CAMERA_DEVICE_API_VERSION_1_0:
2434 case CAMERA_DEVICE_API_VERSION_3_0:
2435 case CAMERA_DEVICE_API_VERSION_3_1:
2436 if (apiVersion == API_VERSION_2) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002437 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without shim",
2438 __FUNCTION__, id.string(), deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002439 *isSupported = false;
2440 } else { // if (apiVersion == API_VERSION_1) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002441 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always supported",
2442 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002443 *isSupported = true;
2444 }
2445 break;
2446 case CAMERA_DEVICE_API_VERSION_3_2:
2447 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -07002448 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002449 case CAMERA_DEVICE_API_VERSION_3_5:
Yin-Chia Yeh56d98ba2020-01-16 16:57:14 -08002450 case CAMERA_DEVICE_API_VERSION_3_6:
Shuzhen Wang83bff122020-11-20 15:51:39 -08002451 case CAMERA_DEVICE_API_VERSION_3_7:
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002452 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
2453 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002454 *isSupported = true;
2455 break;
2456 case -1: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002457 String8 msg = String8::format("Unknown camera ID %s", id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002458 ALOGE("%s: %s", __FUNCTION__, msg.string());
2459 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002460 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002461 default: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002462 String8 msg = String8::format("Unknown device version %x for device %s",
2463 deviceVersion, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002464 ALOGE("%s: %s", __FUNCTION__, msg.string());
2465 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
2466 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07002467 }
2468
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002469 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002470}
2471
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002472Status CameraService::isHiddenPhysicalCamera(const String16& cameraId,
2473 /*out*/ bool *isSupported) {
2474 ATRACE_CALL();
2475
2476 const String8 id = String8(cameraId);
2477
2478 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
2479 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(id.string());
2480
2481 return Status::ok();
2482}
2483
Cliff Wud8cae102021-03-11 01:37:42 +08002484Status CameraService::injectCamera(
2485 const String16& packageName, const String16& internalCamId,
2486 const String16& externalCamId,
2487 const sp<ICameraInjectionCallback>& callback,
2488 /*out*/
2489 sp<hardware::camera2::ICameraInjectionSession>* cameraInjectionSession) {
2490 ATRACE_CALL();
2491
2492 if (!checkCallingPermission(sCameraInjectExternalCameraPermission)) {
2493 const int pid = CameraThreadState::getCallingPid();
2494 const int uid = CameraThreadState::getCallingUid();
2495 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
2496 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2497 "Permission Denial: no permission to inject camera");
2498 }
2499
2500 ALOGV(
2501 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
2502 "%s",
2503 __FUNCTION__, String8(packageName).string(),
2504 String8(internalCamId).string(), String8(externalCamId).string());
2505
2506 binder::Status ret = binder::Status::ok();
2507 // TODO: Implement the injection camera function.
2508 // ret = internalInjectCamera(...);
2509 // if(!ret.isOk()) {
2510 // mInjectionStatusListener->notifyInjectionError(...);
2511 // return ret;
2512 // }
2513
2514 mInjectionStatusListener->addListener(callback);
2515 *cameraInjectionSession = new CameraInjectionSession(this);
2516
2517 return ret;
2518}
2519
Ruben Brunkcc776712015-02-17 20:18:47 -08002520void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002521 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002522 for (auto& i : mActiveClientManager.getAll()) {
2523 auto clientSp = i->getValue();
2524 if (clientSp.get() == client) {
2525 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08002526 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07002527 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002528 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08002529}
2530
Ruben Brunkcc776712015-02-17 20:18:47 -08002531bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002532 bool ret = false;
2533 {
2534 // Acquire mServiceLock and prevent other clients from connecting
2535 std::unique_ptr<AutoConditionLock> lock =
2536 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08002537
Igor Murashkin634a5152013-02-20 17:15:11 -08002538
Ruben Brunkcc776712015-02-17 20:18:47 -08002539 std::vector<sp<BasicClient>> evicted;
2540 for (auto& i : mActiveClientManager.getAll()) {
2541 auto clientSp = i->getValue();
2542 if (clientSp.get() == nullptr) {
2543 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2544 mActiveClientManager.remove(i);
2545 continue;
2546 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08002547 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002548 mActiveClientManager.remove(i);
2549 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08002550
Ruben Brunkcc776712015-02-17 20:18:47 -08002551 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002552 clientSp->notifyError(
2553 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002554 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08002555 }
2556 }
2557
Ruben Brunkcc776712015-02-17 20:18:47 -08002558 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2559 // other clients from connecting in mServiceLockWrapper if held
2560 mServiceLock.unlock();
2561
Ruben Brunk36597b22015-03-20 22:15:57 -07002562 // Do not clear caller identity, remote caller should be client proccess
2563
Ruben Brunkcc776712015-02-17 20:18:47 -08002564 for (auto& i : evicted) {
2565 if (i.get() != nullptr) {
2566 i->disconnect();
2567 ret = true;
2568 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002569 }
2570
Ruben Brunkcc776712015-02-17 20:18:47 -08002571 // Reacquire mServiceLock
2572 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08002573
Ruben Brunkcc776712015-02-17 20:18:47 -08002574 } // lock is destroyed, allow further connect calls
2575
2576 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07002577}
2578
Ruben Brunkcc776712015-02-17 20:18:47 -08002579std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
2580 const String8& cameraId) const {
2581 std::shared_ptr<CameraState> state;
2582 {
2583 Mutex::Autolock lock(mCameraStatesLock);
2584 auto iter = mCameraStates.find(cameraId);
2585 if (iter != mCameraStates.end()) {
2586 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002587 }
2588 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002589 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002590}
2591
Ruben Brunkcc776712015-02-17 20:18:47 -08002592sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
2593 // Remove from active clients list
2594 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
2595 if (clientDescriptorPtr == nullptr) {
2596 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
2597 cameraId.string());
2598 return sp<BasicClient>{nullptr};
2599 }
2600
2601 return clientDescriptorPtr->getValue();
Keun young Parkd8973a72012-03-28 14:13:09 -07002602}
2603
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002604void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07002605 // Acquire mServiceLock and prevent other clients from connecting
2606 std::unique_ptr<AutoConditionLock> lock =
2607 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
2608
Ruben Brunk6267b532015-04-30 17:44:07 -07002609 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002610 for (size_t i = 0; i < newUserIds.size(); i++) {
2611 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07002612 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002613 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07002614 return;
2615 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002616 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07002617 }
2618
Ruben Brunka8ca9152015-04-07 14:23:40 -07002619
Ruben Brunk6267b532015-04-30 17:44:07 -07002620 if (newAllowedUsers == mAllowedUsers) {
2621 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
2622 return;
2623 }
2624
2625 logUserSwitch(mAllowedUsers, newAllowedUsers);
2626
2627 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07002628
2629 // Current user has switched, evict all current clients.
2630 std::vector<sp<BasicClient>> evicted;
2631 for (auto& i : mActiveClientManager.getAll()) {
2632 auto clientSp = i->getValue();
2633
2634 if (clientSp.get() == nullptr) {
2635 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2636 continue;
2637 }
2638
Ruben Brunk6267b532015-04-30 17:44:07 -07002639 // Don't evict clients that are still allowed.
2640 uid_t clientUid = clientSp->getClientUid();
2641 userid_t clientUserId = multiuser_get_user_id(clientUid);
2642 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
2643 continue;
2644 }
2645
Ruben Brunk36597b22015-03-20 22:15:57 -07002646 evicted.push_back(clientSp);
2647
2648 String8 curTime = getFormattedCurrentTime();
2649
2650 ALOGE("Evicting conflicting client for camera ID %s due to user change",
2651 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07002652
Ruben Brunk36597b22015-03-20 22:15:57 -07002653 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002654 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00002655 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
2656 " to user switch.", i->getKey().string(),
2657 String8{clientSp->getPackageName()}.string(),
2658 i->getOwnerId(), i->getPriority().getScore(),
2659 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07002660
2661 }
2662
2663 // Do not hold mServiceLock while disconnecting clients, but retain the condition
2664 // blocking other clients from connecting in mServiceLockWrapper if held.
2665 mServiceLock.unlock();
2666
2667 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07002668 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07002669
2670 for (auto& i : evicted) {
2671 i->disconnect();
2672 }
2673
Jayant Chowdhary12361932018-08-27 14:46:13 -07002674 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07002675
2676 // Reacquire mServiceLock
2677 mServiceLock.lock();
2678}
Ruben Brunkcc776712015-02-17 20:18:47 -08002679
Ruben Brunka8ca9152015-04-07 14:23:40 -07002680void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002681 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07002682 Mutex::Autolock l(mLogLock);
Rucha Katakward9ea6452021-05-06 11:57:16 -07002683 String8 msg = String8::format("%s : %s", curTime.string(), event);
2684 // For service error events, print the msg only once.
2685 if(!msg.contains("SERVICE ERROR")) {
2686 mEventLog.add(msg);
2687 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
2688 // Error event not added to the dumpsys log before
2689 mEventLog.add(msg);
2690 sServiceErrorEventSet.insert(msg);
2691 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002692}
2693
Ruben Brunka8ca9152015-04-07 14:23:40 -07002694void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002695 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002696 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002697 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002698 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002699}
2700
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002701void CameraService::logDisconnectedOffline(const char* cameraId, int clientPid,
2702 const char* clientPackage) {
2703 // Log the clients evicted
2704 logEvent(String8::format("DISCONNECT offline device %s client for package %s (PID %d)",
2705 cameraId, clientPackage, clientPid));
2706}
2707
Ruben Brunka8ca9152015-04-07 14:23:40 -07002708void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002709 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002710 // Log the clients evicted
2711 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002712 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002713}
2714
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002715void CameraService::logConnectedOffline(const char* cameraId, int clientPid,
2716 const char* clientPackage) {
2717 // Log the clients evicted
2718 logEvent(String8::format("CONNECT offline device %s client for package %s (PID %d)", cameraId,
2719 clientPackage, clientPid));
2720}
2721
Ruben Brunka8ca9152015-04-07 14:23:40 -07002722void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002723 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002724 // Log the client rejected
2725 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002726 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002727}
2728
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002729void CameraService::logTorchEvent(const char* cameraId, const char *torchState, int clientPid) {
2730 // Log torch event
2731 logEvent(String8::format("Torch for camera id %s turned %s for client PID %d", cameraId,
2732 torchState, clientPid));
2733}
2734
Ruben Brunk6267b532015-04-30 17:44:07 -07002735void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
2736 const std::set<userid_t>& newUserIds) {
2737 String8 newUsers = toString(newUserIds);
2738 String8 oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002739 if (oldUsers.size() == 0) {
2740 oldUsers = "<None>";
2741 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07002742 // Log the new and old users
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002743 logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
Ruben Brunk6267b532015-04-30 17:44:07 -07002744 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002745}
2746
2747void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
2748 // Log the device removal
2749 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
2750}
2751
2752void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
2753 // Log the device removal
2754 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
2755}
2756
2757void CameraService::logClientDied(int clientPid, const char* reason) {
2758 // Log the device removal
2759 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07002760}
2761
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002762void CameraService::logServiceError(const char* msg, int errorCode) {
2763 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002764 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002765}
2766
Ruben Brunk36597b22015-03-20 22:15:57 -07002767status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
2768 uint32_t flags) {
2769
Mathias Agopian65ab4712010-07-14 17:59:35 -07002770 // Permission checks
2771 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002772 case SHELL_COMMAND_TRANSACTION: {
2773 int in = data.readFileDescriptor();
2774 int out = data.readFileDescriptor();
2775 int err = data.readFileDescriptor();
2776 int argc = data.readInt32();
2777 Vector<String16> args;
2778 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
2779 args.add(data.readString16());
2780 }
2781 sp<IBinder> unusedCallback;
2782 sp<IResultReceiver> resultReceiver;
2783 status_t status;
2784 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
2785 return status;
2786 }
2787 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
2788 return status;
2789 }
2790 status = shellCommand(in, out, err, args);
2791 if (resultReceiver != nullptr) {
2792 resultReceiver->send(status);
2793 }
2794 return NO_ERROR;
2795 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002796 }
2797
2798 return BnCameraService::onTransact(code, data, reply, flags);
2799}
2800
Mathias Agopian65ab4712010-07-14 17:59:35 -07002801// We share the media players for shutter and recording sound for all clients.
2802// A reference count is kept to determine when we will actually release the
2803// media players.
2804
Jaekyun Seokef498052018-03-23 13:09:44 +09002805sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
2806 sp<MediaPlayer> mp = new MediaPlayer();
2807 status_t error;
2808 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08002809 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09002810 error = mp->prepare();
2811 }
2812 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00002813 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09002814 mp->disconnect();
2815 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002816 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002817 }
2818 return mp;
2819}
2820
username5755fea2018-12-27 09:48:08 +08002821void CameraService::increaseSoundRef() {
2822 Mutex::Autolock lock(mSoundLock);
2823 mSoundRef++;
2824}
2825
2826void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002827 ATRACE_CALL();
2828
username5755fea2018-12-27 09:48:08 +08002829 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
2830 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
2831 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
2832 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
2833 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
2834 }
2835 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
2836 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
2837 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
2838 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002839 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08002840 }
2841 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
2842 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
2843 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
2844 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
2845 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002846 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002847}
2848
username5755fea2018-12-27 09:48:08 +08002849void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002850 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002851 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002852 if (--mSoundRef) return;
2853
2854 for (int i = 0; i < NUM_SOUNDS; i++) {
2855 if (mSoundPlayer[i] != 0) {
2856 mSoundPlayer[i]->disconnect();
2857 mSoundPlayer[i].clear();
2858 }
2859 }
2860}
2861
2862void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002863 ATRACE_CALL();
2864
Mathias Agopian65ab4712010-07-14 17:59:35 -07002865 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07002866 if (kind < 0 || kind >= NUM_SOUNDS) {
2867 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
2868 return;
2869 }
2870
Mathias Agopian65ab4712010-07-14 17:59:35 -07002871 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002872 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002873 sp<MediaPlayer> player = mSoundPlayer[kind];
2874 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08002875 player->seekTo(0);
2876 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002877 }
2878}
2879
2880// ----------------------------------------------------------------------------
2881
2882CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07002883 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002884 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09002885 const std::optional<String16>& clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002886 const String8& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07002887 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002888 int clientPid, uid_t clientUid,
2889 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002890 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08002891 IInterface::asBinder(cameraClient),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002892 clientPackageName, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07002893 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002894 clientPid, clientUid,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002895 servicePid),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002896 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08002897{
Jayant Chowdhary12361932018-08-27 14:46:13 -07002898 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002899 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002900
Igor Murashkin44cfcf02013-03-01 16:22:28 -08002901 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002902
username5755fea2018-12-27 09:48:08 +08002903 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002904
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002905 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002906}
2907
Mathias Agopian65ab4712010-07-14 17:59:35 -07002908// tear down the client
2909CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002910 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08002911 mDestructionStarted = true;
2912
username5755fea2018-12-27 09:48:08 +08002913 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002914 // unconditionally disconnect. function is idempotent
2915 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002916}
2917
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002918sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
2919
Igor Murashkin634a5152013-02-20 17:15:11 -08002920CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002921 const sp<IBinder>& remoteCallback,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09002922 const String16& clientPackageName, const std::optional<String16>& clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07002923 const String8& cameraIdStr, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002924 int clientPid, uid_t clientUid,
2925 int servicePid):
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002926 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07002927 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09002928 mClientPackageName(clientPackageName), mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002929 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002930 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07002931 mDisconnected(false), mUidIsTrusted(false),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002932 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002933 mRemoteBinder(remoteCallback),
2934 mOpsActive(false),
2935 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08002936{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002937 if (sCameraService == nullptr) {
2938 sCameraService = cameraService;
2939 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08002940
2941 // In some cases the calling code has no access to the package it runs under.
2942 // For example, NDK camera API.
2943 // In this case we will get the packages for the calling UID and pick the first one
2944 // for attributing the app op. This will work correctly for runtime permissions
2945 // as for legacy apps we will toggle the app op for all packages in the UID.
2946 // The caveat is that the operation may be attributed to the wrong package and
2947 // stats based on app ops may be slightly off.
2948 if (mClientPackageName.size() <= 0) {
2949 sp<IServiceManager> sm = defaultServiceManager();
2950 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
2951 if (binder == 0) {
2952 ALOGE("Cannot get permission service");
2953 // Leave mClientPackageName unchanged (empty) and the further interaction
2954 // with camera will fail in BasicClient::startCameraOps
2955 return;
2956 }
2957
2958 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
2959 Vector<String16> packages;
2960
2961 permCtrl->getPackagesForUid(mClientUid, packages);
2962
2963 if (packages.isEmpty()) {
2964 ALOGE("No packages for calling UID");
2965 // Leave mClientPackageName unchanged (empty) and the further interaction
2966 // with camera will fail in BasicClient::startCameraOps
2967 return;
2968 }
2969 mClientPackageName = packages[0];
2970 }
Steven Moreland89a2c5c2020-01-31 15:02:25 -08002971 if (getCurrentServingCall() != BinderCallType::HWBINDER) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002972 mAppOpsManager = std::make_unique<AppOpsManager>();
2973 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07002974
2975 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08002976}
2977
2978CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002979 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08002980 mDestructionStarted = true;
2981}
2982
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002983binder::Status CameraService::BasicClient::disconnect() {
2984 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002985 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002986 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07002987 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07002988 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002989
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002990 sCameraService->removeByClient(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002991 sCameraService->logDisconnected(mCameraIdStr, mClientPid, String8(mClientPackageName));
Peter Kalauskasa29c1352018-10-10 12:05:42 -07002992 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
2993 mCameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002994
2995 sp<IBinder> remote = getRemote();
2996 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002997 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08002998 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002999
3000 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07003001 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003002 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
3003 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
3004 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003005
Igor Murashkincba2c162013-03-20 15:56:31 -07003006 // client shouldn't be able to call into us anymore
3007 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003008
3009 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08003010}
3011
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08003012status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
3013 // No dumping of clients directly over Binder,
3014 // must go through CameraService::dump
3015 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07003016 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08003017 return OK;
3018}
3019
Ruben Brunkcc776712015-02-17 20:18:47 -08003020String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003021 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08003022}
3023
Emilian Peev8b64f282021-03-25 16:49:57 -07003024int CameraService::BasicClient::getCameraFacing() const {
3025 return mCameraFacing;
3026}
3027
3028int CameraService::BasicClient::getCameraOrientation() const {
3029 return mOrientation;
3030}
Ruben Brunkcc776712015-02-17 20:18:47 -08003031
3032int CameraService::BasicClient::getClientPid() const {
3033 return mClientPid;
3034}
3035
Ruben Brunk6267b532015-04-30 17:44:07 -07003036uid_t CameraService::BasicClient::getClientUid() const {
3037 return mClientUid;
3038}
3039
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003040bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
3041 // Defaults to API2.
3042 return level == API_2;
3043}
3044
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07003045status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003046 {
3047 Mutex::Autolock l(mAudioRestrictionLock);
3048 mAudioRestriction = mode;
3049 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07003050 sCameraService->updateAudioRestriction();
3051 return OK;
3052}
3053
3054int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003055 return sCameraService->updateAudioRestriction();
3056}
3057
3058int32_t CameraService::BasicClient::getAudioRestriction() const {
3059 Mutex::Autolock l(mAudioRestrictionLock);
3060 return mAudioRestriction;
3061}
3062
3063bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
3064 switch (mode) {
3065 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
3066 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
3067 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
3068 return true;
3069 default:
3070 return false;
3071 }
3072}
3073
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003074status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
3075 if (mode == AppOpsManager::MODE_ERRORED) {
3076 ALOGI("Camera %s: Access for \"%s\" has been revoked",
3077 mCameraIdStr.string(), String8(mClientPackageName).string());
3078 return PERMISSION_DENIED;
3079 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
3080 // If the calling Uid is trusted (a native service), the AppOpsManager could
3081 // return MODE_IGNORED. Do not treat such case as error.
3082 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
3083 mClientPackageName);
3084 bool isCameraPrivacyEnabled =
3085 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled(
3086 multiuser_get_user_id(mClientUid));
3087 if (!isUidActive || !isCameraPrivacyEnabled) {
3088 ALOGI("Camera %s: Access for \"%s\" has been restricted",
3089 mCameraIdStr.string(), String8(mClientPackageName).string());
3090 // Return the same error as for device policy manager rejection
3091 return -EACCES;
3092 }
3093 }
3094 return OK;
3095}
3096
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003097status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003098 ATRACE_CALL();
3099
Igor Murashkine6800ce2013-03-04 17:25:57 -08003100 {
3101 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003102 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08003103 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003104 if (mAppOpsManager != nullptr) {
3105 // Notify app ops that the camera is not available
3106 mOpsCallback = new OpsCallback(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003107 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
3108 mClientPackageName, mOpsCallback);
Igor Murashkine6800ce2013-03-04 17:25:57 -08003109
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003110 // Just check for camera acccess here on open - delay startOp until
3111 // camera frames start streaming in startCameraStreamingOps
3112 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
3113 mClientPackageName);
3114 status_t res = handleAppOpMode(mode);
3115 if (res != OK) {
3116 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003117 }
Svetoslav28e8ef72015-05-11 19:21:31 -07003118 }
3119
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003120 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003121
3122 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003123 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003124
Emilian Peev53722fa2019-02-22 17:47:20 -08003125 sCameraService->mUidPolicy->registerMonitorUid(mClientUid);
3126
Shuzhen Wang695044d2020-03-06 09:02:23 -08003127 // Notify listeners of camera open/close status
3128 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
3129
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003130 return OK;
3131}
3132
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003133status_t CameraService::BasicClient::startCameraStreamingOps() {
3134 ATRACE_CALL();
3135
3136 if (!mOpsActive) {
3137 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
3138 return INVALID_OPERATION;
3139 }
3140 if (mOpsStreaming) {
3141 ALOGV("%s: Streaming already active!", __FUNCTION__);
3142 return OK;
3143 }
3144
3145 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
3146 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
3147
3148 if (mAppOpsManager != nullptr) {
3149 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
3150 mClientPackageName, /*startIfModeDefault*/ false, mClientFeatureId,
3151 String16("start camera ") + String16(mCameraIdStr));
3152 status_t res = handleAppOpMode(mode);
3153 if (res != OK) {
3154 return res;
3155 }
3156 }
3157
3158 mOpsStreaming = true;
3159
3160 return OK;
3161}
3162
3163status_t CameraService::BasicClient::finishCameraStreamingOps() {
3164 ATRACE_CALL();
3165
3166 if (!mOpsActive) {
3167 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
3168 return INVALID_OPERATION;
3169 }
3170 if (!mOpsStreaming) {
3171 ALOGV("%s: Streaming not active!", __FUNCTION__);
3172 return OK;
3173 }
3174
3175 if (mAppOpsManager != nullptr) {
3176 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
3177 mClientPackageName, mClientFeatureId);
3178 mOpsStreaming = false;
3179 }
3180
3181 return OK;
3182}
3183
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003184status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003185 ATRACE_CALL();
3186
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003187 if (mOpsStreaming) {
3188 // Make sure we've notified everyone about camera stopping
3189 finishCameraStreamingOps();
3190 }
3191
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003192 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003193 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003194 mOpsActive = false;
3195
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01003196 // This function is called when a client disconnects. This should
3197 // release the camera, but actually only if it was in a proper
3198 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003199 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01003200 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003201
Ruben Brunkcc776712015-02-17 20:18:47 -08003202 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003203 sCameraService->updateStatus(StatusInternal::PRESENT,
3204 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003205 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003206 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003207 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
3208 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08003209 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003210 mOpsCallback.clear();
3211
Emilian Peev53722fa2019-02-22 17:47:20 -08003212 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid);
3213
Shuzhen Wang695044d2020-03-06 09:02:23 -08003214 // Notify listeners of camera open/close status
3215 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
3216
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003217 return OK;
3218}
3219
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003220void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003221 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003222 if (mAppOpsManager == nullptr) {
3223 return;
3224 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003225 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003226 if (op != AppOpsManager::OP_CAMERA) {
3227 ALOGW("Unexpected app ops notification received: %d", op);
3228 return;
3229 }
3230
3231 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003232 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003233 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003234 ALOGV("checkOp returns: %d, %s ", res,
3235 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
3236 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
3237 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
3238 "UNKNOWN");
3239
Shuzhen Wang64900852021-02-05 09:03:29 -08003240 if (res == AppOpsManager::MODE_ERRORED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003241 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003242 String8(mClientPackageName).string());
Svet Ganova453d0d2018-01-11 15:37:58 -08003243 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08003244 } else if (res == AppOpsManager::MODE_IGNORED) {
3245 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Evan Severson09ab4002021-02-10 14:15:19 -08003246 bool isCameraPrivacyEnabled =
3247 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled(
3248 multiuser_get_user_id(mClientUid));
Shuzhen Wang64900852021-02-05 09:03:29 -08003249 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d",
3250 mCameraIdStr.string(), String8(mClientPackageName).string(),
3251 mUidIsTrusted, isUidActive);
3252 // If the calling Uid is trusted (a native service), or the client Uid is active (WAR for
3253 // b/175320666), the AppOpsManager could return MODE_IGNORED. Do not treat such cases as
3254 // error.
Evan Severson09ab4002021-02-10 14:15:19 -08003255 if (!mUidIsTrusted && isUidActive && isCameraPrivacyEnabled) {
3256 setCameraMute(true);
3257 } else if (!mUidIsTrusted && !isUidActive) {
Shuzhen Wang64900852021-02-05 09:03:29 -08003258 block();
3259 }
Evan Severson09ab4002021-02-10 14:15:19 -08003260 } else if (res == AppOpsManager::MODE_ALLOWED) {
3261 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003262 }
3263}
3264
Svet Ganova453d0d2018-01-11 15:37:58 -08003265void CameraService::BasicClient::block() {
3266 ATRACE_CALL();
3267
3268 // Reset the client PID to allow server-initiated disconnect,
3269 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003270 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08003271 CaptureResultExtras resultExtras; // a dummy result (invalid)
3272 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
3273 disconnect();
3274}
3275
Mathias Agopian65ab4712010-07-14 17:59:35 -07003276// ----------------------------------------------------------------------------
3277
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003278void CameraService::Client::notifyError(int32_t errorCode,
Jianing Weicb0652e2014-03-12 18:29:36 -07003279 const CaptureResultExtras& resultExtras) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08003280 (void) resultExtras;
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003281 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07003282 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
3283 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
3284 api1ErrorCode = CAMERA_ERROR_DISABLED;
3285 }
3286 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003287 } else {
3288 ALOGE("mRemoteCallback is NULL!!");
3289 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003290}
3291
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003292// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003293binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003294 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003295 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08003296}
3297
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003298bool CameraService::Client::canCastToApiClient(apiLevel level) const {
3299 return level == API_1;
3300}
3301
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003302CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
3303 mClient(client) {
3304}
3305
3306void CameraService::Client::OpsCallback::opChanged(int32_t op,
3307 const String16& packageName) {
3308 sp<BasicClient> client = mClient.promote();
3309 if (client != NULL) {
3310 client->opChanged(op, packageName);
3311 }
3312}
3313
Mathias Agopian65ab4712010-07-14 17:59:35 -07003314// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08003315// UidPolicy
3316// ----------------------------------------------------------------------------
3317
3318void CameraService::UidPolicy::registerSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003319 Mutex::Autolock _l(mUidLock);
3320
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003321 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07003322 status_t res = mAm.linkToDeath(this);
3323 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08003324 | ActivityManager::UID_OBSERVER_IDLE
Emilian Peev53722fa2019-02-22 17:47:20 -08003325 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganova453d0d2018-01-11 15:37:58 -08003326 ActivityManager::PROCESS_STATE_UNKNOWN,
3327 String16("cameraserver"));
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003328 if (res == OK) {
3329 mRegistered = true;
3330 ALOGV("UidPolicy: Registered with ActivityManager");
3331 }
Svet Ganova453d0d2018-01-11 15:37:58 -08003332}
3333
3334void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003335 Mutex::Autolock _l(mUidLock);
3336
Steven Moreland2f348142019-07-02 15:59:07 -07003337 mAm.unregisterUidObserver(this);
3338 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003339 mRegistered = false;
3340 mActiveUids.clear();
3341 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08003342}
3343
3344void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
3345 onUidIdle(uid, disabled);
3346}
3347
3348void CameraService::UidPolicy::onUidActive(uid_t uid) {
3349 Mutex::Autolock _l(mUidLock);
3350 mActiveUids.insert(uid);
3351}
3352
3353void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
3354 bool deleted = false;
3355 {
3356 Mutex::Autolock _l(mUidLock);
3357 if (mActiveUids.erase(uid) > 0) {
3358 deleted = true;
3359 }
3360 }
3361 if (deleted) {
3362 sp<CameraService> service = mService.promote();
3363 if (service != nullptr) {
3364 service->blockClientsForUid(uid);
3365 }
3366 }
3367}
3368
Emilian Peev53722fa2019-02-22 17:47:20 -08003369void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07003370 int64_t procStateSeq __unused, int32_t capability __unused) {
Emilian Peev53722fa2019-02-22 17:47:20 -08003371 bool procStateChange = false;
3372 {
3373 Mutex::Autolock _l(mUidLock);
3374 if ((mMonitoredUids.find(uid) != mMonitoredUids.end()) &&
3375 (mMonitoredUids[uid].first != procState)) {
3376 mMonitoredUids[uid].first = procState;
3377 procStateChange = true;
3378 }
3379 }
3380
3381 if (procStateChange) {
3382 sp<CameraService> service = mService.promote();
3383 if (service != nullptr) {
3384 service->notifyMonitoredUids();
3385 }
3386 }
3387}
3388
3389void CameraService::UidPolicy::registerMonitorUid(uid_t uid) {
3390 Mutex::Autolock _l(mUidLock);
3391 auto it = mMonitoredUids.find(uid);
3392 if (it != mMonitoredUids.end()) {
3393 it->second.second++;
3394 } else {
3395 mMonitoredUids.emplace(
3396 std::pair<uid_t, std::pair<int32_t, size_t>> (uid,
3397 std::pair<int32_t, size_t> (ActivityManager::PROCESS_STATE_NONEXISTENT, 1)));
3398 }
3399}
3400
3401void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid) {
3402 Mutex::Autolock _l(mUidLock);
3403 auto it = mMonitoredUids.find(uid);
3404 if (it != mMonitoredUids.end()) {
3405 it->second.second--;
3406 if (it->second.second == 0) {
3407 mMonitoredUids.erase(it);
3408 }
3409 } else {
3410 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
3411 }
3412}
3413
Svet Ganov7b4ab782018-03-25 12:48:10 -07003414bool CameraService::UidPolicy::isUidActive(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003415 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003416 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003417}
3418
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003419static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
3420static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003421
Svet Ganov7b4ab782018-03-25 12:48:10 -07003422bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003423 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003424 // If activity manager is unreachable, assume everything is active
3425 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003426 return true;
3427 }
3428 auto it = mOverrideUids.find(uid);
3429 if (it != mOverrideUids.end()) {
3430 return it->second;
3431 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003432 bool active = mActiveUids.find(uid) != mActiveUids.end();
3433 if (!active) {
3434 // We want active UIDs to always access camera with their first attempt since
3435 // there is no guarantee the app is robustly written and would retry getting
3436 // the camera on failure. The inverse case is not a problem as we would take
3437 // camera away soon once we get the callback that the uid is no longer active.
3438 ActivityManager am;
3439 // Okay to access with a lock held as UID changes are dispatched without
3440 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07003441 int64_t startTimeMillis = 0;
3442 do {
3443 // TODO: Fix this b/109950150!
3444 // Okay this is a hack. There is a race between the UID turning active and
3445 // activity being resumed. The proper fix is very risky, so we temporary add
3446 // some polling which should happen pretty rarely anyway as the race is hard
3447 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003448 active = mActiveUids.find(uid) != mActiveUids.end();
Hui Yu12c7ec72020-05-04 17:40:52 +00003449 if (!active) active = am.isUidActive(uid, callingPackage);
Svet Ganov94ec46f2018-06-08 15:03:46 -07003450 if (active) {
3451 break;
3452 }
3453 if (startTimeMillis <= 0) {
3454 startTimeMillis = uptimeMillis();
3455 }
3456 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003457 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003458 if (remainingTimeMillis <= 0) {
3459 break;
3460 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003461 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
3462
3463 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003464 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003465 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003466 } while (true);
3467
Svet Ganov7b4ab782018-03-25 12:48:10 -07003468 if (active) {
3469 // Now that we found out the UID is actually active, cache that
3470 mActiveUids.insert(uid);
3471 }
3472 }
3473 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08003474}
3475
Varun Shahb42f1eb2019-04-16 14:45:13 -07003476int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
3477 Mutex::Autolock _l(mUidLock);
3478 return getProcStateLocked(uid);
3479}
3480
3481int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
3482 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
3483 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
3484 procState = mMonitoredUids[uid].first;
3485 }
3486 return procState;
3487}
3488
Svet Ganov7b4ab782018-03-25 12:48:10 -07003489void CameraService::UidPolicy::UidPolicy::addOverrideUid(uid_t uid,
3490 String16 callingPackage, bool active) {
3491 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08003492}
3493
Svet Ganov7b4ab782018-03-25 12:48:10 -07003494void CameraService::UidPolicy::removeOverrideUid(uid_t uid, String16 callingPackage) {
3495 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08003496}
3497
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003498void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
3499 Mutex::Autolock _l(mUidLock);
3500 ALOGV("UidPolicy: ActivityManager has died");
3501 mRegistered = false;
3502 mActiveUids.clear();
3503}
3504
Svet Ganov7b4ab782018-03-25 12:48:10 -07003505void CameraService::UidPolicy::updateOverrideUid(uid_t uid, String16 callingPackage,
3506 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003507 bool wasActive = false;
3508 bool isActive = false;
3509 {
3510 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003511 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003512 mOverrideUids.erase(uid);
3513 if (insert) {
3514 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
3515 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003516 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003517 }
3518 if (wasActive != isActive && !isActive) {
3519 sp<CameraService> service = mService.promote();
3520 if (service != nullptr) {
3521 service->blockClientsForUid(uid);
3522 }
3523 }
3524}
3525
3526// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08003527// SensorPrivacyPolicy
3528// ----------------------------------------------------------------------------
3529void CameraService::SensorPrivacyPolicy::registerSelf() {
3530 Mutex::Autolock _l(mSensorPrivacyLock);
3531 if (mRegistered) {
3532 return;
3533 }
Evan Severson09ab4002021-02-10 14:15:19 -08003534 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08003535 mSpm.addSensorPrivacyListener(this);
3536 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
3537 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003538 if (res == OK) {
3539 mRegistered = true;
3540 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
3541 }
3542}
3543
3544void CameraService::SensorPrivacyPolicy::unregisterSelf() {
3545 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08003546 mSpm.removeSensorPrivacyListener(this);
3547 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003548 mRegistered = false;
3549 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
3550}
3551
3552bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
3553 Mutex::Autolock _l(mSensorPrivacyLock);
3554 return mSensorPrivacyEnabled;
3555}
3556
Evan Severson09ab4002021-02-10 14:15:19 -08003557bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled(userid_t userId) {
3558 if (!hasCameraPrivacyFeature()) {
3559 return false;
3560 }
3561 return mSpm.isIndividualSensorPrivacyEnabled(userId,
3562 SensorPrivacyManager::INDIVIDUAL_SENSOR_CAMERA);
3563}
3564
Michael Grooverd1d435a2018-12-18 17:39:42 -08003565binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
3566 {
3567 Mutex::Autolock _l(mSensorPrivacyLock);
3568 mSensorPrivacyEnabled = enabled;
3569 }
3570 // if sensor privacy is enabled then block all clients from accessing the camera
Evan Severson09ab4002021-02-10 14:15:19 -08003571 if (enabled) {
3572 sp<CameraService> service = mService.promote();
3573 if (service != nullptr) {
3574 service->blockAllClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08003575 }
3576 }
3577 return binder::Status::ok();
3578}
3579
3580void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
3581 Mutex::Autolock _l(mSensorPrivacyLock);
3582 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
3583 mRegistered = false;
3584}
3585
Evan Severson09ab4002021-02-10 14:15:19 -08003586bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Severson671806e2021-04-20 16:44:53 -07003587 return mSpm.supportsSensorToggle(SensorPrivacyManager::INDIVIDUAL_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08003588}
3589
Michael Grooverd1d435a2018-12-18 17:39:42 -08003590// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003591// CameraState
3592// ----------------------------------------------------------------------------
3593
3594CameraService::CameraState::CameraState(const String8& id, int cost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003595 const std::set<String8>& conflicting, SystemCameraKind systemCameraKind) : mId(id),
3596 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
3597 mSystemCameraKind(systemCameraKind) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08003598
3599CameraService::CameraState::~CameraState() {}
3600
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003601CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003602 Mutex::Autolock lock(mStatusLock);
3603 return mStatus;
3604}
3605
Shuzhen Wang43858162020-01-10 13:42:15 -08003606std::vector<String8> CameraService::CameraState::getUnavailablePhysicalIds() const {
3607 Mutex::Autolock lock(mStatusLock);
3608 std::vector<String8> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
3609 return res;
3610}
3611
Ruben Brunkcc776712015-02-17 20:18:47 -08003612CameraParameters CameraService::CameraState::getShimParams() const {
3613 return mShimParams;
3614}
3615
3616void CameraService::CameraState::setShimParams(const CameraParameters& params) {
3617 mShimParams = params;
3618}
3619
3620int CameraService::CameraState::getCost() const {
3621 return mCost;
3622}
3623
3624std::set<String8> CameraService::CameraState::getConflicting() const {
3625 return mConflicting;
3626}
3627
3628String8 CameraService::CameraState::getId() const {
3629 return mId;
3630}
3631
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003632SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
3633 return mSystemCameraKind;
3634}
3635
Shuzhen Wang43858162020-01-10 13:42:15 -08003636bool CameraService::CameraState::addUnavailablePhysicalId(const String8& physicalId) {
3637 Mutex::Autolock lock(mStatusLock);
3638 auto result = mUnavailablePhysicalIds.insert(physicalId);
3639 return result.second;
3640}
3641
3642bool CameraService::CameraState::removeUnavailablePhysicalId(const String8& physicalId) {
3643 Mutex::Autolock lock(mStatusLock);
3644 auto count = mUnavailablePhysicalIds.erase(physicalId);
3645 return count > 0;
3646}
3647
Ruben Brunkcc776712015-02-17 20:18:47 -08003648// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07003649// ClientEventListener
3650// ----------------------------------------------------------------------------
3651
3652void CameraService::ClientEventListener::onClientAdded(
3653 const resource_policy::ClientDescriptor<String8,
3654 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003655 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003656 if (basicClient.get() != nullptr) {
3657 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3658 notifier.noteStartCamera(descriptor.getKey(),
3659 static_cast<int>(basicClient->getClientUid()));
3660 }
3661}
3662
3663void CameraService::ClientEventListener::onClientRemoved(
3664 const resource_policy::ClientDescriptor<String8,
3665 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003666 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003667 if (basicClient.get() != nullptr) {
3668 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3669 notifier.noteStopCamera(descriptor.getKey(),
3670 static_cast<int>(basicClient->getClientUid()));
3671 }
3672}
3673
3674
3675// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003676// CameraClientManager
3677// ----------------------------------------------------------------------------
3678
Ruben Brunk99e69712015-05-26 17:25:07 -07003679CameraService::CameraClientManager::CameraClientManager() {
3680 setListener(std::make_shared<ClientEventListener>());
3681}
3682
Ruben Brunkcc776712015-02-17 20:18:47 -08003683CameraService::CameraClientManager::~CameraClientManager() {}
3684
3685sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
3686 const String8& id) const {
3687 auto descriptor = get(id);
3688 if (descriptor == nullptr) {
3689 return sp<BasicClient>{nullptr};
3690 }
3691 return descriptor->getValue();
3692}
3693
3694String8 CameraService::CameraClientManager::toString() const {
3695 auto all = getAll();
3696 String8 ret("[");
3697 bool hasAny = false;
3698 for (auto& i : all) {
3699 hasAny = true;
3700 String8 key = i->getKey();
3701 int32_t cost = i->getCost();
3702 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00003703 int32_t score = i->getPriority().getScore();
3704 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08003705 auto conflicting = i->getConflicting();
3706 auto clientSp = i->getValue();
3707 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07003708 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08003709 if (clientSp.get() != nullptr) {
3710 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07003711 uid_t clientUid = clientSp->getClientUid();
3712 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003713 }
Emilian Peev8131a262017-02-01 12:33:43 +00003714 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
3715 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08003716
Ruben Brunk6267b532015-04-30 17:44:07 -07003717 if (clientSp.get() != nullptr) {
3718 ret.appendFormat("User Id: %d, ", clientUserId);
3719 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003720 if (packageName.size() != 0) {
3721 ret.appendFormat("Client Package Name: %s", packageName.string());
3722 }
3723
3724 ret.append(", Conflicting Client Devices: {");
3725 for (auto& j : conflicting) {
3726 ret.appendFormat("%s, ", j.string());
3727 }
3728 ret.append("})");
3729 }
3730 if (hasAny) ret.append("\n");
3731 ret.append("]\n");
3732 return ret;
3733}
3734
3735CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3736 const String8& key, const sp<BasicClient>& value, int32_t cost,
Emilian Peev8131a262017-02-01 12:33:43 +00003737 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00003738 int32_t state, int32_t oomScoreOffset) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003739
Steven Moreland89a2c5c2020-01-31 15:02:25 -08003740 bool isVendorClient = getCurrentServingCall() == BinderCallType::HWBINDER;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003741 int32_t score_adj = isVendorClient ? kVendorClientScore : score;
3742 int32_t state_adj = isVendorClient ? kVendorClientState: state;
3743
Ruben Brunkcc776712015-02-17 20:18:47 -08003744 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00003745 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj, isVendorClient,
3746 oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08003747}
3748
3749CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00003750 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
3751 int32_t oomScoreOffset) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003752 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00003753 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00003754 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08003755}
3756
3757// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08003758// InjectionStatusListener
3759// ----------------------------------------------------------------------------
3760
3761void CameraService::InjectionStatusListener::addListener(
3762 const sp<ICameraInjectionCallback>& callback) {
3763 Mutex::Autolock lock(mListenerLock);
3764 if (mCameraInjectionCallback) return;
3765 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
3766 if (res == OK) {
3767 mCameraInjectionCallback = callback;
3768 }
3769}
3770
3771void CameraService::InjectionStatusListener::removeListener() {
3772 Mutex::Autolock lock(mListenerLock);
3773 if (mCameraInjectionCallback == nullptr) {
3774 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
3775 return;
3776 }
3777 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
3778 mCameraInjectionCallback = nullptr;
3779}
3780
3781void CameraService::InjectionStatusListener::notifyInjectionError(
3782 int errorCode) {
3783 Mutex::Autolock lock(mListenerLock);
3784 if (mCameraInjectionCallback == nullptr) {
3785 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
3786 return;
3787 }
3788 mCameraInjectionCallback->onInjectionError(errorCode);
3789}
3790
3791void CameraService::InjectionStatusListener::binderDied(
3792 const wp<IBinder>& /*who*/) {
3793 Mutex::Autolock lock(mListenerLock);
3794 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
3795 auto parent = mParent.promote();
3796 if (parent != nullptr) {
3797 parent->stopInjectionImpl();
3798 }
3799}
3800
3801// ----------------------------------------------------------------------------
3802// CameraInjectionSession
3803// ----------------------------------------------------------------------------
3804
3805binder::Status CameraService::CameraInjectionSession::stopInjection() {
3806 Mutex::Autolock lock(mInjectionSessionLock);
3807 auto parent = mParent.promote();
3808 if (parent == nullptr) {
3809 ALOGE("CameraInjectionSession: Parent is gone");
3810 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
3811 "Camera service encountered error");
3812 }
3813 parent->stopInjectionImpl();
3814 return binder::Status::ok();
3815}
3816
3817// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07003818
3819static const int kDumpLockRetries = 50;
3820static const int kDumpLockSleep = 60000;
3821
3822static bool tryLock(Mutex& mutex)
3823{
3824 bool locked = false;
3825 for (int i = 0; i < kDumpLockRetries; ++i) {
3826 if (mutex.tryLock() == NO_ERROR) {
3827 locked = true;
3828 break;
3829 }
3830 usleep(kDumpLockSleep);
3831 }
3832 return locked;
3833}
3834
3835status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003836 ATRACE_CALL();
3837
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003838 if (checkCallingPermission(sDumpPermission) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003839 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07003840 CameraThreadState::getCallingPid(),
3841 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003842 return NO_ERROR;
3843 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003844 bool locked = tryLock(mServiceLock);
3845 // failed to lock - CameraService is probably deadlocked
3846 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003847 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003848 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003849
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003850 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003851 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07003852
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003853 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003854 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08003855
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003856 if (locked) mServiceLock.unlock();
3857 return NO_ERROR;
3858 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003859 dprintf(fd, "\n== Service global info: ==\n\n");
3860 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003861 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07003862 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
3863 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003864 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
3865 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
3866 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003867 String8 activeClientString = mActiveClientManager.toString();
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003868 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
3869 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003870
3871 dumpEventLog(fd);
3872
3873 bool stateLocked = tryLock(mCameraStatesLock);
3874 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003875 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003876 }
3877
Emilian Peevbd8c5032018-02-14 23:05:40 +00003878 int argSize = args.size();
3879 for (int i = 0; i < argSize; i++) {
3880 if (args[i] == TagMonitor::kMonitorOption) {
3881 if (i + 1 < argSize) {
3882 mMonitorTags = String8(args[i + 1]);
3883 }
3884 break;
3885 }
3886 }
3887
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003888 for (auto& state : mCameraStates) {
3889 String8 cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003890
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003891 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003892
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003893 CameraParameters p = state.second->getShimParams();
3894 if (!p.isEmpty()) {
3895 dprintf(fd, " Camera1 API shim is using parameters:\n ");
3896 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003897 }
3898
3899 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08003900 if (clientDescriptor != nullptr) {
3901 dprintf(fd, " Device %s is open. Client instance dump:\n",
3902 cameraId.string());
3903 dprintf(fd, " Client priority score: %d state: %d\n",
3904 clientDescriptor->getPriority().getScore(),
3905 clientDescriptor->getPriority().getState());
3906 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
3907
3908 auto client = clientDescriptor->getValue();
3909 dprintf(fd, " Client package: %s\n",
3910 String8(client->getPackageName()).string());
3911
3912 client->dumpClient(fd, args);
3913 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003914 dprintf(fd, " Device %s is closed, no client instance\n",
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003915 cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003916 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003917
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003918 }
3919
3920 if (stateLocked) mCameraStatesLock.unlock();
3921
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003922 if (locked) mServiceLock.unlock();
3923
Emilian Peevf53f66e2017-04-11 14:29:43 +01003924 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003925
3926 dprintf(fd, "\n== Vendor tags: ==\n\n");
3927
3928 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
3929 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00003930 sp<VendorTagDescriptorCache> cache =
3931 VendorTagDescriptorCache::getGlobalVendorTagCache();
3932 if (cache == NULL) {
3933 dprintf(fd, "No vendor tags.\n");
3934 } else {
3935 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
3936 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003937 } else {
3938 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
3939 }
3940
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003941 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003942 dprintf(fd, "\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003943 camera3::CameraTraces::dump(fd, args);
3944
3945 // Process dump arguments, if any
3946 int n = args.size();
3947 String16 verboseOption("-v");
3948 String16 unreachableOption("--unreachable");
3949 for (int i = 0; i < n; i++) {
3950 if (args[i] == verboseOption) {
3951 // change logging level
3952 if (i + 1 >= n) continue;
3953 String8 levelStr(args[i+1]);
3954 int level = atoi(levelStr.string());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003955 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003956 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003957 } else if (args[i] == unreachableOption) {
3958 // Dump memory analysis
3959 // TODO - should limit be an argument parameter?
3960 UnreachableMemoryInfo info;
3961 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
3962 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003963 dprintf(fd, "\n== Unable to dump unreachable memory. "
3964 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003965 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003966 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003967 std::string s = info.ToString(/*log_contents*/ true);
3968 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003969 }
3970 }
3971 }
3972 return NO_ERROR;
3973}
3974
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003975void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003976 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003977
3978 Mutex::Autolock l(mLogLock);
3979 for (const auto& msg : mEventLog) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003980 dprintf(fd, " %s\n", msg.string());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003981 }
3982
3983 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003984 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003985 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003986 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003987 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003988 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003989}
3990
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003991void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003992 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003993 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
3994 if (mTorchClientMap[i] == who) {
3995 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003996 String8 cameraId = mTorchClientMap.keyAt(i);
3997 status_t res = mFlashlight->setTorchMode(cameraId, false);
3998 if (res) {
3999 ALOGE("%s: torch client died but couldn't turn off torch: "
4000 "%s (%d)", __FUNCTION__, strerror(-res), res);
4001 return;
4002 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004003 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004004 break;
4005 }
4006 }
4007}
4008
Ruben Brunkcc776712015-02-17 20:18:47 -08004009/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07004010
Igor Murashkin294d0ec2012-10-05 10:44:57 -07004011 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07004012 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
4013 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07004014 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08004015 // PID here is approximate and can be wrong.
Jayant Chowdhary12361932018-08-27 14:46:13 -07004016 logClientDied(CameraThreadState::getCallingPid(), String8("Binder died unexpectedly"));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004017
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004018 // check torch client
4019 handleTorchClientBinderDied(who);
4020
4021 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08004022 if(!evictClientIdByRemote(who)) {
4023 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07004024 return;
4025 }
4026
Ruben Brunkcc776712015-02-17 20:18:47 -08004027 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
4028 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07004029}
4030
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004031void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004032 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08004033}
4034
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004035void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
4036 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004037 // Do not lock mServiceLock here or can get into a deadlock from
4038 // connect() -> disconnect -> updateStatus
4039
4040 auto state = getCameraState(cameraId);
4041
4042 if (state == nullptr) {
4043 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
4044 cameraId.string());
4045 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07004046 }
4047
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004048 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
4049 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
4050 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
4051 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
4052 return;
4053 }
Jayant Chowdhary90e63692019-10-25 14:13:01 -07004054 bool supportsHAL3 = false;
4055 // supportsCameraApi also holds mInterfaceMutex, we can't call it in the
4056 // HIDL onStatusChanged wrapper call (we'll hold mStatusListenerLock and
4057 // mInterfaceMutex together, which can lead to deadlocks)
4058 binder::Status sRet =
4059 supportsCameraApi(String16(cameraId), hardware::ICameraService::API_VERSION_2,
4060 &supportsHAL3);
4061 if (!sRet.isOk()) {
4062 ALOGW("%s: Failed to determine if device supports HAL3 %s, supportsCameraApi call failed",
4063 __FUNCTION__, cameraId.string());
4064 return;
4065 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004066
4067 // Collect the logical cameras without holding mStatusLock in updateStatus
4068 // as that can lead to a deadlock(b/162192331).
4069 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08004070 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08004071 // of the listeners with both the mStatusLock and mStatusListenerLock held
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004072 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind, &supportsHAL3,
4073 &logicalCameraIds]
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004074 (const String8& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004075
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004076 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004077 // Update torch status if it has a flash unit.
4078 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004079 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004080 if (getTorchStatusLocked(cameraId, &torchStatus) !=
4081 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004082 TorchModeStatus newTorchStatus =
4083 status == StatusInternal::PRESENT ?
4084 TorchModeStatus::AVAILABLE_OFF :
4085 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004086 if (torchStatus != newTorchStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07004087 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004088 }
4089 }
Ruben Brunkcc776712015-02-17 20:18:47 -08004090 }
4091
4092 Mutex::Autolock lock(mStatusListenerLock);
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004093 notifyPhysicalCameraStatusLocked(mapToInterface(status), String16(cameraId),
4094 logicalCameraIds, deviceKind);
Shuzhen Wang43858162020-01-10 13:42:15 -08004095
Ruben Brunkcc776712015-02-17 20:18:47 -08004096 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07004097 bool isVendorListener = listener->isVendorListener();
4098 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
4099 listener->getListenerPid(), listener->getListenerUid()) ||
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07004100 (isVendorListener && !supportsHAL3)) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07004101 ALOGV("Skipping discovery callback for system-only camera/HAL1 device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07004102 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08004103 continue;
4104 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07004105 listener->getListener()->onStatusChanged(mapToInterface(status),
Emilian Peev53722fa2019-02-22 17:47:20 -08004106 String16(cameraId));
Ruben Brunkcc776712015-02-17 20:18:47 -08004107 }
4108 });
Igor Murashkincba2c162013-03-20 15:56:31 -07004109}
4110
Shuzhen Wang695044d2020-03-06 09:02:23 -08004111void CameraService::updateOpenCloseStatus(const String8& cameraId, bool open,
4112 const String16& clientPackageName) {
4113 Mutex::Autolock lock(mStatusListenerLock);
4114
4115 for (const auto& it : mListenerList) {
4116 if (!it->isOpenCloseCallbackAllowed()) {
4117 continue;
4118 }
4119
4120 binder::Status ret;
4121 String16 cameraId64(cameraId);
4122 if (open) {
4123 ret = it->getListener()->onCameraOpened(cameraId64, clientPackageName);
4124 } else {
4125 ret = it->getListener()->onCameraClosed(cameraId64);
4126 }
4127 if (!ret.isOk()) {
4128 ALOGE("%s: Failed to trigger onCameraOpened/onCameraClosed callback: %d", __FUNCTION__,
4129 ret.exceptionCode());
4130 }
4131 }
4132}
4133
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004134template<class Func>
4135void CameraService::CameraState::updateStatus(StatusInternal status,
4136 const String8& cameraId,
4137 std::initializer_list<StatusInternal> rejectSourceStates,
4138 Func onStatusUpdatedLocked) {
4139 Mutex::Autolock lock(mStatusLock);
4140 StatusInternal oldStatus = mStatus;
4141 mStatus = status;
4142
4143 if (oldStatus == status) {
4144 return;
4145 }
4146
4147 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
4148 cameraId.string(), oldStatus, status);
4149
4150 if (oldStatus == StatusInternal::NOT_PRESENT &&
4151 (status != StatusInternal::PRESENT &&
4152 status != StatusInternal::ENUMERATING)) {
4153
4154 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
4155 __FUNCTION__);
4156 mStatus = oldStatus;
4157 return;
4158 }
4159
4160 /**
4161 * Sometimes we want to conditionally do a transition.
4162 * For example if a client disconnects, we want to go to PRESENT
4163 * only if we weren't already in NOT_PRESENT or ENUMERATING.
4164 */
4165 for (auto& rejectStatus : rejectSourceStates) {
4166 if (oldStatus == rejectStatus) {
4167 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
4168 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
4169 mStatus = oldStatus;
4170 return;
4171 }
4172 }
4173
4174 onStatusUpdatedLocked(cameraId, status);
4175}
4176
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004177status_t CameraService::getTorchStatusLocked(
4178 const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004179 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004180 if (!status) {
4181 return BAD_VALUE;
4182 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004183 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
4184 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004185 // invalid camera ID or the camera doesn't have a flash unit
4186 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004187 }
4188
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004189 *status = mTorchStatusMap.valueAt(index);
4190 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004191}
4192
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004193status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004194 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004195 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
4196 if (index == NAME_NOT_FOUND) {
4197 return BAD_VALUE;
4198 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004199 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004200
4201 return OK;
4202}
4203
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004204std::list<String16> CameraService::getLogicalCameras(
4205 const String8& physicalCameraId) {
4206 std::list<String16> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08004207 Mutex::Autolock lock(mCameraStatesLock);
4208 for (const auto& state : mCameraStates) {
4209 std::vector<std::string> physicalCameraIds;
4210 if (!mCameraProviderManager->isLogicalCamera(state.first.c_str(), &physicalCameraIds)) {
4211 // This is not a logical multi-camera.
4212 continue;
4213 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004214 if (std::find(physicalCameraIds.begin(), physicalCameraIds.end(), physicalCameraId.c_str())
Shuzhen Wang43858162020-01-10 13:42:15 -08004215 == physicalCameraIds.end()) {
4216 // cameraId is not a physical camera of this logical multi-camera.
4217 continue;
4218 }
4219
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004220 retList.emplace_back(String16(state.first));
4221 }
4222 return retList;
4223}
4224
4225void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
4226 const String16& physicalCameraId, const std::list<String16>& logicalCameraIds,
4227 SystemCameraKind deviceKind) {
4228 // mStatusListenerLock is expected to be locked
4229 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08004230 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004231 // Note: we check only the deviceKind of the physical camera id
4232 // since, logical camera ids and their physical camera ids are
4233 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07004234 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
4235 listener->getListenerPid(), listener->getListenerUid())) {
4236 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004237 String8(physicalCameraId).c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07004238 continue;
4239 }
Shuzhen Wang43858162020-01-10 13:42:15 -08004240 listener->getListener()->onPhysicalCameraStatusChanged(status,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004241 logicalCameraId, physicalCameraId);
Shuzhen Wang43858162020-01-10 13:42:15 -08004242 }
4243 }
4244}
4245
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004246
Svet Ganova453d0d2018-01-11 15:37:58 -08004247void CameraService::blockClientsForUid(uid_t uid) {
4248 const auto clients = mActiveClientManager.getAll();
4249 for (auto& current : clients) {
4250 if (current != nullptr) {
4251 const auto basicClient = current->getValue();
4252 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
4253 basicClient->block();
4254 }
4255 }
4256 }
4257}
4258
Michael Grooverd1d435a2018-12-18 17:39:42 -08004259void CameraService::blockAllClients() {
4260 const auto clients = mActiveClientManager.getAll();
4261 for (auto& current : clients) {
4262 if (current != nullptr) {
4263 const auto basicClient = current->getValue();
4264 if (basicClient.get() != nullptr) {
4265 basicClient->block();
4266 }
4267 }
4268 }
4269}
4270
Svet Ganova453d0d2018-01-11 15:37:58 -08004271// NOTE: This is a remote API - make sure all args are validated
4272status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
4273 if (!checkCallingPermission(sManageCameraPermission, nullptr, nullptr)) {
4274 return PERMISSION_DENIED;
4275 }
4276 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
4277 return BAD_VALUE;
4278 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004279 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004280 return handleSetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07004281 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004282 return handleResetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07004283 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004284 return handleGetUidState(args, out, err);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004285 } else if (args.size() >= 2 && args[0] == String16("set-rotate-and-crop")) {
4286 return handleSetRotateAndCrop(args);
4287 } else if (args.size() >= 1 && args[0] == String16("get-rotate-and-crop")) {
4288 return handleGetRotateAndCrop(out);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004289 } else if (args.size() >= 2 && args[0] == String16("set-image-dump-mask")) {
4290 return handleSetImageDumpMask(args);
4291 } else if (args.size() >= 1 && args[0] == String16("get-image-dump-mask")) {
4292 return handleGetImageDumpMask(out);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004293 } else if (args.size() >= 2 && args[0] == String16("set-camera-mute")) {
4294 return handleSetCameraMute(args);
Svet Ganova453d0d2018-01-11 15:37:58 -08004295 } else if (args.size() == 1 && args[0] == String16("help")) {
4296 printHelp(out);
4297 return NO_ERROR;
4298 }
4299 printHelp(err);
4300 return BAD_VALUE;
4301}
4302
4303status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004304 String16 packageName = args[1];
4305
Svet Ganova453d0d2018-01-11 15:37:58 -08004306 bool active = false;
4307 if (args[2] == String16("active")) {
4308 active = true;
4309 } else if ((args[2] != String16("idle"))) {
4310 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
4311 return BAD_VALUE;
4312 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004313
4314 int userId = 0;
4315 if (args.size() >= 5 && args[3] == String16("--user")) {
4316 userId = atoi(String8(args[4]));
4317 }
4318
4319 uid_t uid;
4320 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
4321 return BAD_VALUE;
4322 }
4323
4324 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08004325 return NO_ERROR;
4326}
4327
4328status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004329 String16 packageName = args[1];
4330
4331 int userId = 0;
4332 if (args.size() >= 4 && args[2] == String16("--user")) {
4333 userId = atoi(String8(args[3]));
4334 }
4335
4336 uid_t uid;
4337 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004338 return BAD_VALUE;
4339 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004340
4341 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08004342 return NO_ERROR;
4343}
4344
4345status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004346 String16 packageName = args[1];
4347
4348 int userId = 0;
4349 if (args.size() >= 4 && args[2] == String16("--user")) {
4350 userId = atoi(String8(args[3]));
4351 }
4352
4353 uid_t uid;
4354 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004355 return BAD_VALUE;
4356 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004357
4358 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004359 return dprintf(out, "active\n");
4360 } else {
4361 return dprintf(out, "idle\n");
4362 }
4363}
4364
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004365status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
4366 int rotateValue = atoi(String8(args[1]));
4367 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
4368 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
4369 Mutex::Autolock lock(mServiceLock);
4370
4371 mOverrideRotateAndCropMode = rotateValue;
4372
4373 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
4374
4375 const auto clients = mActiveClientManager.getAll();
4376 for (auto& current : clients) {
4377 if (current != nullptr) {
4378 const auto basicClient = current->getValue();
4379 if (basicClient.get() != nullptr) {
4380 basicClient->setRotateAndCropOverride(rotateValue);
4381 }
4382 }
4383 }
4384
4385 return OK;
4386}
4387
4388status_t CameraService::handleGetRotateAndCrop(int out) {
4389 Mutex::Autolock lock(mServiceLock);
4390
4391 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
4392}
4393
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004394status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
4395 char *endPtr;
4396 errno = 0;
4397 String8 maskString8 = String8(args[1]);
4398 long maskValue = strtol(maskString8.c_str(), &endPtr, 10);
4399
4400 if (errno != 0) return BAD_VALUE;
4401 if (endPtr != maskString8.c_str() + maskString8.size()) return BAD_VALUE;
4402 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
4403
4404 Mutex::Autolock lock(mServiceLock);
4405
4406 mImageDumpMask = maskValue;
4407
4408 return OK;
4409}
4410
4411status_t CameraService::handleGetImageDumpMask(int out) {
4412 Mutex::Autolock lock(mServiceLock);
4413
4414 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
4415}
4416
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004417status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
4418 int muteValue = strtol(String8(args[1]), nullptr, 10);
4419 if (errno != 0) return BAD_VALUE;
4420
4421 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
4422 Mutex::Autolock lock(mServiceLock);
4423
4424 mOverrideCameraMuteMode = (muteValue == 1);
4425
4426 const auto clients = mActiveClientManager.getAll();
4427 for (auto& current : clients) {
4428 if (current != nullptr) {
4429 const auto basicClient = current->getValue();
4430 if (basicClient.get() != nullptr) {
4431 if (basicClient->supportsCameraMute()) {
4432 basicClient->setCameraMute(mOverrideCameraMuteMode);
4433 }
4434 }
4435 }
4436 }
4437
4438 return OK;
4439}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004440
Svet Ganova453d0d2018-01-11 15:37:58 -08004441status_t CameraService::printHelp(int out) {
4442 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07004443 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
4444 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
4445 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004446 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
4447 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
4448 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004449 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
4450 " Valid values 0=OFF, 1=ON for JPEG\n"
4451 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004452 " set-camera-mute <0/1> enable or disable camera muting\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08004453 " help print this message\n");
4454}
4455
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004456int32_t CameraService::updateAudioRestriction() {
4457 Mutex::Autolock lock(mServiceLock);
4458 return updateAudioRestrictionLocked();
4459}
4460
4461int32_t CameraService::updateAudioRestrictionLocked() {
4462 int32_t mode = 0;
4463 // iterate through all active client
4464 for (const auto& i : mActiveClientManager.getAll()) {
4465 const auto clientSp = i->getValue();
4466 mode |= clientSp->getAudioRestriction();
4467 }
4468
4469 bool modeChanged = (mAudioRestriction != mode);
4470 mAudioRestriction = mode;
4471 if (modeChanged) {
4472 mAppOps.setCameraAudioRestriction(mode);
4473 }
4474 return mode;
4475}
4476
Cliff Wud8cae102021-03-11 01:37:42 +08004477void CameraService::stopInjectionImpl() {
4478 mInjectionStatusListener->removeListener();
4479
4480 // TODO: Implement the stop injection function.
4481}
4482
Mathias Agopian65ab4712010-07-14 17:59:35 -07004483}; // namespace android