blob: 329400de89ab9ea78bd2a40f3a5339b7eca2ed3f [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
235 return OK;
236}
237
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700238void CameraService::broadcastTorchModeStatus(const String8& cameraId, TorchModeStatus status,
239 SystemCameraKind systemCameraKind) {
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800240 Mutex::Autolock lock(mStatusListenerLock);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800241 for (auto& i : mListenerList) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700242 if (shouldSkipStatusUpdates(systemCameraKind, i->isVendorListener(), i->getListenerPid(),
243 i->getListenerUid())) {
244 ALOGV("Skipping torch callback for system-only camera device %s",
245 cameraId.c_str());
246 continue;
247 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700248 i->getListener()->onTorchStatusChanged(mapToInterface(status), String16{cameraId});
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800249 }
250}
251
Mathias Agopian65ab4712010-07-14 17:59:35 -0700252CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800253 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800254 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800255 mSensorPrivacyPolicy->unregisterSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800256 mInjectionStatusListener->removeListener();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700257}
258
Emilian Peevaee727d2017-05-04 16:35:48 +0100259void CameraService::onNewProviderRegistered() {
260 enumerateProviders();
261}
262
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700263void CameraService::filterAPI1SystemCameraLocked(
264 const std::vector<std::string> &normalDeviceIds) {
265 mNormalDeviceIdsWithoutSystemCamera.clear();
266 for (auto &deviceId : normalDeviceIds) {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700267 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
268 if (getSystemCameraKind(String8(deviceId.c_str()), &deviceKind) != OK) {
269 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, deviceId.c_str());
270 continue;
271 }
272 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700273 // All system camera ids will necessarily come after public camera
274 // device ids as per the HAL interface contract.
275 break;
276 }
277 mNormalDeviceIdsWithoutSystemCamera.push_back(deviceId);
278 }
279 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
280 mNormalDeviceIdsWithoutSystemCamera.size());
281}
282
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700283status_t CameraService::getSystemCameraKind(const String8& cameraId, SystemCameraKind *kind) const {
284 auto state = getCameraState(cameraId);
285 if (state != nullptr) {
286 *kind = state->getSystemCameraKind();
287 return OK;
288 }
289 // Hidden physical camera ids won't have CameraState
290 return mCameraProviderManager->getSystemCameraKind(cameraId.c_str(), kind);
291}
292
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800293void CameraService::updateCameraNumAndIds() {
294 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700295 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
296 // Excludes hidden secure cameras
297 mNumberOfCameras =
298 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
299 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800300 mNormalDeviceIds =
301 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700302 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800303}
304
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100305void CameraService::addStates(const String8 id) {
306 std::string cameraId(id.c_str());
307 hardware::camera::common::V1_0::CameraResourceCost cost;
308 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700309 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100310 if (res != OK) {
311 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
312 return;
313 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700314 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
315 if (res != OK) {
316 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
317 return;
318 }
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100319 std::set<String8> conflicting;
320 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
321 conflicting.emplace(String8(cost.conflictingDevices[i].c_str()));
322 }
323
324 {
325 Mutex::Autolock lock(mCameraStatesLock);
326 mCameraStates.emplace(id, std::make_shared<CameraState>(id, cost.resourceCost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700327 conflicting, deviceKind));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100328 }
329
330 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100331 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100332 mTorchStatusMap.add(id, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800333
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700334 broadcastTorchModeStatus(id, TorchModeStatus::AVAILABLE_OFF, deviceKind);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100335 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800336
337 updateCameraNumAndIds();
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100338 logDeviceAdded(id, "Device added");
339}
340
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100341void CameraService::removeStates(const String8 id) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800342 updateCameraNumAndIds();
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100343 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100344 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100345 mTorchStatusMap.removeItem(id);
346 }
347
348 {
349 Mutex::Autolock lock(mCameraStatesLock);
350 mCameraStates.erase(id);
351 }
352}
353
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800354void CameraService::onDeviceStatusChanged(const String8& id,
355 CameraDeviceStatus newHalStatus) {
356 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
357 id.string(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700358
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800359 StatusInternal newStatus = mapToInternal(newHalStatus);
360
Ruben Brunkcc776712015-02-17 20:18:47 -0800361 std::shared_ptr<CameraState> state = getCameraState(id);
362
363 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700364 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100365 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700366 __FUNCTION__, id.string());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100367
368 // First add as absent to make sure clients are notified below
369 addStates(id);
370
371 updateStatus(newStatus, id);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700372 } else {
373 ALOGE("%s: Bad camera ID %s", __FUNCTION__, id.string());
374 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700375 return;
376 }
377
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800378 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800379
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800380 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800381 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700382 return;
383 }
384
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800385 if (newStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700386 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
387 newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800388
389 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
390 // to this device until the status changes
391 updateStatus(StatusInternal::NOT_PRESENT, id);
392
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800393 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700394 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800395 // Don't do this in updateStatus to avoid deadlock over mServiceLock
396 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700397
Ruben Brunkcc776712015-02-17 20:18:47 -0800398 // Remove cached shim parameters
399 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700400
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800401 // Remove online as well as offline client from the list of active clients,
402 // if they are present
403 clientToDisconnectOnline = removeClientLocked(id);
404 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + id);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700405 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800406
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800407 disconnectClient(id, clientToDisconnectOnline);
408 disconnectClient(kOfflineDevice + id, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700409
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100410 removeStates(id);
Ruben Brunkcc776712015-02-17 20:18:47 -0800411 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800412 if (oldStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700413 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
414 newStatus));
415 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800416 updateStatus(newStatus, id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700417 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800418}
Igor Murashkincba2c162013-03-20 15:56:31 -0700419
Shuzhen Wang43858162020-01-10 13:42:15 -0800420void CameraService::onDeviceStatusChanged(const String8& id,
421 const String8& physicalId,
422 CameraDeviceStatus newHalStatus) {
423 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
424 __FUNCTION__, id.string(), physicalId.string(), newHalStatus);
425
426 StatusInternal newStatus = mapToInternal(newHalStatus);
427
428 std::shared_ptr<CameraState> state = getCameraState(id);
429
430 if (state == nullptr) {
431 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
432 __FUNCTION__, id.string(), physicalId.string());
433 return;
434 }
435
436 StatusInternal logicalCameraStatus = state->getStatus();
437 if (logicalCameraStatus != StatusInternal::PRESENT &&
438 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
439 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
440 __FUNCTION__, physicalId.string(), newHalStatus, logicalCameraStatus);
441 return;
442 }
443
444 bool updated = false;
445 if (newStatus == StatusInternal::PRESENT) {
446 updated = state->removeUnavailablePhysicalId(physicalId);
447 } else {
448 updated = state->addUnavailablePhysicalId(physicalId);
449 }
450
451 if (updated) {
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800452 String8 idCombo = id + " : " + physicalId;
453 if (newStatus == StatusInternal::PRESENT) {
454 logDeviceAdded(idCombo,
455 String8::format("Device status changed to %d", newStatus));
456 } else {
457 logDeviceRemoved(idCombo,
458 String8::format("Device status changed to %d", newStatus));
459 }
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700460 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
461 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
462 if (getSystemCameraKind(id, &deviceKind) != OK) {
463 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.string());
464 return;
465 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800466 String16 id16(id), physicalId16(physicalId);
467 Mutex::Autolock lock(mStatusListenerLock);
468 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700469 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
470 listener->getListenerPid(), listener->getListenerUid())) {
471 ALOGV("Skipping discovery callback for system-only camera device %s",
472 id.c_str());
473 continue;
474 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800475 listener->getListener()->onPhysicalCameraStatusChanged(mapToInterface(newStatus),
476 id16, physicalId16);
477 }
478 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700479}
480
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800481void CameraService::disconnectClient(const String8& id, sp<BasicClient> clientToDisconnect) {
482 if (clientToDisconnect.get() != nullptr) {
483 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
484 __FUNCTION__, id.string());
485 // Notify the client of disconnection
486 clientToDisconnect->notifyError(
487 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
488 CaptureResultExtras{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800489 clientToDisconnect->disconnect();
490 }
491}
492
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800493void CameraService::onTorchStatusChanged(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800494 TorchModeStatus newStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700495 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
496 status_t res = getSystemCameraKind(cameraId, &systemCameraKind);
497 if (res != OK) {
498 ALOGE("%s: Could not get system camera kind for camera id %s", __FUNCTION__,
499 cameraId.string());
500 return;
501 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800502 Mutex::Autolock al(mTorchStatusMutex);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700503 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800504}
505
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800506void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700507 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800508 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
509 __FUNCTION__, cameraId.string(), newStatus);
510
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800511 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800512 status_t res = getTorchStatusLocked(cameraId, &status);
513 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700514 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
515 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800516 return;
517 }
518 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800519 return;
520 }
521
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800522 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800523 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800524 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
525 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800526 return;
527 }
528
Ruben Brunkcc776712015-02-17 20:18:47 -0800529 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700530 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700531 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700532 auto iter = mTorchUidMap.find(cameraId);
533 if (iter != mTorchUidMap.end()) {
534 int oldUid = iter->second.second;
535 int newUid = iter->second.first;
536 BatteryNotifier& notifier(BatteryNotifier::getInstance());
537 if (oldUid != newUid) {
538 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800539 if (status == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700540 notifier.noteFlashlightOff(cameraId, oldUid);
541 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800542 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700543 notifier.noteFlashlightOn(cameraId, newUid);
544 }
545 iter->second.second = newUid;
546 } else {
547 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800548 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700549 notifier.noteFlashlightOn(cameraId, oldUid);
550 } else {
551 notifier.noteFlashlightOff(cameraId, oldUid);
552 }
553 }
554 }
555 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700556 broadcastTorchModeStatus(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800557}
558
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700559static bool hasPermissionsForSystemCamera(int callingPid, int callingUid) {
560 return checkPermission(sSystemCameraPermission, callingPid, callingUid) &&
561 checkPermission(sCameraPermission, callingPid, callingUid);
562}
563
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800564Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700565 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100566 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700567 bool hasSystemCameraPermissions =
568 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
569 CameraThreadState::getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700570 switch (type) {
571 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700572 if (hasSystemCameraPermissions) {
573 *numCameras = static_cast<int>(mNormalDeviceIds.size());
574 } else {
575 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
576 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800577 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700578 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700579 if (hasSystemCameraPermissions) {
580 *numCameras = mNumberOfCameras;
581 } else {
582 *numCameras = mNumberOfCamerasWithoutSystemCamera;
583 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800584 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700585 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800586 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700587 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800588 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
589 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700590 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800591 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700592}
593
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800594Status CameraService::getCameraInfo(int cameraId,
595 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700596 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100597 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700598 std::string cameraIdStr = cameraIdIntToStrLocked(cameraId);
599 if (shouldRejectSystemCameraConnection(String8(cameraIdStr.c_str()))) {
600 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
601 "characteristics for system only device %s: ", cameraIdStr.c_str());
602 }
Emilian Peevaee727d2017-05-04 16:35:48 +0100603
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800604 if (!mInitialized) {
Rucha Katakward9ea6452021-05-06 11:57:16 -0700605 logServiceError(String8::format("Camera subsystem is not available"),ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800606 return STATUS_ERROR(ERROR_DISCONNECTED,
607 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -0700608 }
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700609 bool hasSystemCameraPermissions =
610 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
611 CameraThreadState::getCallingUid());
612 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
613 if (hasSystemCameraPermissions) {
614 cameraIdBound = mNumberOfCameras;
615 }
616 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800617 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
618 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700619 }
620
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800621 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800622 status_t err = mCameraProviderManager->getCameraInfo(
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700623 cameraIdStr.c_str(), cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100624 if (err != OK) {
625 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
626 "Error retrieving camera info from device %d: %s (%d)", cameraId,
627 strerror(-err), err);
Rucha Katakward9ea6452021-05-06 11:57:16 -0700628 logServiceError(String8::format("Error retrieving camera info from device %d",cameraId),
629 ERROR_INVALID_OPERATION);
Ruben Brunkcc776712015-02-17 20:18:47 -0800630 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100631
Ruben Brunkcc776712015-02-17 20:18:47 -0800632 return ret;
633}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700634
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800635std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700636 const std::vector<std::string> *deviceIds = &mNormalDeviceIdsWithoutSystemCamera;
637 auto callingPid = CameraThreadState::getCallingPid();
638 auto callingUid = CameraThreadState::getCallingUid();
639 if (checkPermission(sSystemCameraPermission, callingPid, callingUid) ||
640 getpid() == callingPid) {
641 deviceIds = &mNormalDeviceIds;
642 }
643 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(deviceIds->size())) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800644 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700645 __FUNCTION__, cameraIdInt, deviceIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800646 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800647 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800648
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700649 return (*deviceIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800650}
651
652String8 CameraService::cameraIdIntToStr(int cameraIdInt) {
653 Mutex::Autolock lock(mServiceLock);
654 return String8(cameraIdIntToStrLocked(cameraIdInt).c_str());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800655}
656
657Status CameraService::getCameraCharacteristics(const String16& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800658 CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700659 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700660 if (!cameraInfo) {
661 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800662 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -0700663 }
664
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800665 if (!mInitialized) {
666 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Rucha Katakward9ea6452021-05-06 11:57:16 -0700667 logServiceError(String8::format("Camera subsystem is not available"),ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800668 return STATUS_ERROR(ERROR_DISCONNECTED,
669 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -0700670 }
671
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700672 if (shouldRejectSystemCameraConnection(String8(cameraId))) {
673 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
674 "characteristics for system only device %s: ", String8(cameraId).string());
675 }
676
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800677 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800678
Emilian Peevf53f66e2017-04-11 14:29:43 +0100679 status_t res = mCameraProviderManager->getCameraCharacteristics(
680 String8(cameraId).string(), cameraInfo);
681 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700682 if (res == NAME_NOT_FOUND) {
683 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
684 "characteristics for unknown device %s: %s (%d)", String8(cameraId).string(),
685 strerror(-res), res);
686 } else {
Rucha Katakward9ea6452021-05-06 11:57:16 -0700687 logServiceError(String8::format("Unable to retrieve camera characteristics for "
688 "device %s.", String8(cameraId).string()),ERROR_INVALID_OPERATION);
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700689 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
690 "characteristics for device %s: %s (%d)", String8(cameraId).string(),
691 strerror(-res), res);
692 }
Ruben Brunkb2119af2014-05-09 19:57:56 -0700693 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700694 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
695 if (getSystemCameraKind(String8(cameraId), &deviceKind) != OK) {
696 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, String8(cameraId).string());
697 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera kind "
698 "for device %s", String8(cameraId).string());
699 }
Jayant Chowdhary12361932018-08-27 14:46:13 -0700700 int callingPid = CameraThreadState::getCallingPid();
701 int callingUid = CameraThreadState::getCallingUid();
Emilian Peeve20c6372018-08-14 18:45:53 +0100702 std::vector<int32_t> tagsRemoved;
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700703 // If it's not calling from cameraserver, check the permission only if
704 // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
705 // it would've already been checked in shouldRejectSystemCameraConnection.
Emilian Peeve20c6372018-08-14 18:45:53 +0100706 if ((callingPid != getpid()) &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700707 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700708 !checkPermission(sCameraPermission, callingPid, callingUid)) {
Emilian Peeve20c6372018-08-14 18:45:53 +0100709 res = cameraInfo->removePermissionEntries(
710 mCameraProviderManager->getProviderTagIdLocked(String8(cameraId).string()),
711 &tagsRemoved);
712 if (res != OK) {
713 cameraInfo->clear();
714 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
715 " characteristics needing camera permission for device %s: %s (%d)",
716 String8(cameraId).string(), strerror(-res), res);
717 }
718 }
719
720 if (!tagsRemoved.empty()) {
721 res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
722 tagsRemoved.data(), tagsRemoved.size());
723 if (res != OK) {
724 cameraInfo->clear();
725 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
726 "keys needing permission for device %s: %s (%d)", String8(cameraId).string(),
727 strerror(-res), res);
728 }
729 }
730
Zhijun He2b59be82013-09-25 10:14:30 -0700731 return ret;
732}
733
Ruben Brunkcc776712015-02-17 20:18:47 -0800734String8 CameraService::getFormattedCurrentTime() {
735 time_t now = time(nullptr);
736 char formattedTime[64];
737 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
738 return String8(formattedTime);
739}
740
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800741Status CameraService::getCameraVendorTagDescriptor(
742 /*out*/
743 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700744 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800745 if (!mInitialized) {
746 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800747 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800748 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -0800749 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
750 if (globalDescriptor != nullptr) {
751 *desc = *(globalDescriptor.get());
752 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800753 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800754}
755
Emilian Peev71c73a22017-03-21 16:35:51 +0000756Status CameraService::getCameraVendorTagCache(
757 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
758 ATRACE_CALL();
759 if (!mInitialized) {
760 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
761 return STATUS_ERROR(ERROR_DISCONNECTED,
762 "Camera subsystem not available");
763 }
764 sp<VendorTagDescriptorCache> globalCache =
765 VendorTagDescriptorCache::getGlobalVendorTagCache();
766 if (globalCache != nullptr) {
767 *cache = *(globalCache.get());
768 }
769 return Status::ok();
770}
771
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -0700772void CameraService::clearCachedVariables() {
773 BasicClient::BasicClient::sCameraService = nullptr;
774}
775
Emilian Peevb91f1802021-03-23 14:50:28 -0700776int CameraService::getDeviceVersion(const String8& cameraId, int* facing, int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700777 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800778
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800779 int deviceVersion = 0;
780
Emilian Peevf53f66e2017-04-11 14:29:43 +0100781 status_t res;
782 hardware::hidl_version maxVersion{0,0};
783 res = mCameraProviderManager->getHighestSupportedVersion(cameraId.string(),
784 &maxVersion);
785 if (res != OK) return -1;
786 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800787
Emilian Peevf53f66e2017-04-11 14:29:43 +0100788 hardware::CameraInfo info;
789 if (facing) {
790 res = mCameraProviderManager->getCameraInfo(cameraId.string(), &info);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -0800791 if (res != OK) return -1;
Emilian Peevf53f66e2017-04-11 14:29:43 +0100792 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -0700793 if (orientation) {
794 *orientation = info.orientation;
795 }
Igor Murashkin634a5152013-02-20 17:15:11 -0800796 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100797
Igor Murashkin634a5152013-02-20 17:15:11 -0800798 return deviceVersion;
799}
800
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800801Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700802 switch(err) {
803 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800804 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800805 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800806 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
807 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800808 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800809 return STATUS_ERROR(ERROR_DISCONNECTED,
810 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700811 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800812 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
813 "Camera HAL encountered error %d: %s",
814 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700815 }
Igor Murashkinbfc99152013-02-27 12:55:20 -0800816}
817
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800818Status CameraService::makeClient(const sp<CameraService>& cameraService,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800819 const sp<IInterface>& cameraCb, const String16& packageName,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700820 const std::optional<String16>& featureId, const String8& cameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -0700821 int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
822 int servicePid, int deviceVersion, apiLevel effectiveApiLevel,
Ruben Brunkcc776712015-02-17 20:18:47 -0800823 /*out*/sp<BasicClient>* client) {
824
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700825 // Create CameraClient based on device version reported by the HAL.
826 switch(deviceVersion) {
827 case CAMERA_DEVICE_API_VERSION_1_0:
828 ALOGE("Camera using old HAL version: %d", deviceVersion);
829 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
830 "Camera device \"%s\" HAL version %d no longer supported",
831 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800832 break;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700833 case CAMERA_DEVICE_API_VERSION_3_0:
834 case CAMERA_DEVICE_API_VERSION_3_1:
835 case CAMERA_DEVICE_API_VERSION_3_2:
836 case CAMERA_DEVICE_API_VERSION_3_3:
837 case CAMERA_DEVICE_API_VERSION_3_4:
838 case CAMERA_DEVICE_API_VERSION_3_5:
839 case CAMERA_DEVICE_API_VERSION_3_6:
Shuzhen Wang83bff122020-11-20 15:51:39 -0800840 case CAMERA_DEVICE_API_VERSION_3_7:
Ruben Brunkcc776712015-02-17 20:18:47 -0800841 if (effectiveApiLevel == API_1) { // Camera1 API route
842 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800843 *client = new Camera2Client(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800844 cameraId, api1CameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -0700845 facing, sensorOrientation, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700846 servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800847 } else { // Camera2 API route
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800848 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
849 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800850 *client = new CameraDeviceClient(cameraService, tmp, packageName, featureId,
Emilian Peev8b64f282021-03-25 16:49:57 -0700851 cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800852 }
853 break;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700854 default:
Ruben Brunkcc776712015-02-17 20:18:47 -0800855 // Should not be reachable
856 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800857 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800858 "Camera device \"%s\" has unknown HAL version %d",
859 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800860 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800861 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800862}
863
Ruben Brunk6267b532015-04-30 17:44:07 -0700864String8 CameraService::toString(std::set<userid_t> intSet) {
865 String8 s("");
866 bool first = true;
867 for (userid_t i : intSet) {
868 if (first) {
869 s.appendFormat("%d", i);
870 first = false;
871 } else {
872 s.appendFormat(", %d", i);
873 }
874 }
875 return s;
876}
877
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800878int32_t CameraService::mapToInterface(TorchModeStatus status) {
879 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
880 switch (status) {
881 case TorchModeStatus::NOT_AVAILABLE:
882 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
883 break;
884 case TorchModeStatus::AVAILABLE_OFF:
885 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
886 break;
887 case TorchModeStatus::AVAILABLE_ON:
888 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
889 break;
890 default:
891 ALOGW("Unknown new flash status: %d", status);
892 }
893 return serviceStatus;
894}
895
896CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
897 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
898 switch (status) {
899 case CameraDeviceStatus::NOT_PRESENT:
900 serviceStatus = StatusInternal::NOT_PRESENT;
901 break;
902 case CameraDeviceStatus::PRESENT:
903 serviceStatus = StatusInternal::PRESENT;
904 break;
905 case CameraDeviceStatus::ENUMERATING:
906 serviceStatus = StatusInternal::ENUMERATING;
907 break;
908 default:
909 ALOGW("Unknown new HAL device status: %d", status);
910 }
911 return serviceStatus;
912}
913
914int32_t CameraService::mapToInterface(StatusInternal status) {
915 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
916 switch (status) {
917 case StatusInternal::NOT_PRESENT:
918 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
919 break;
920 case StatusInternal::PRESENT:
921 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
922 break;
923 case StatusInternal::ENUMERATING:
924 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
925 break;
926 case StatusInternal::NOT_AVAILABLE:
927 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
928 break;
929 case StatusInternal::UNKNOWN:
930 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
931 break;
932 default:
933 ALOGW("Unknown new internal device status: %d", status);
934 }
935 return serviceStatus;
936}
937
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800938Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -0700939 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700940
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800941 String16 internalPackageName("cameraserver");
Ruben Brunkcc776712015-02-17 20:18:47 -0800942 String8 id = String8::format("%d", cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800943 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800944 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800945 if (!(ret = connectHelper<ICameraClient,Client>(
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800946 sp<ICameraClient>{nullptr}, id, cameraId,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +0900947 internalPackageName, {}, uid, USE_CALLING_PID,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +0000948 API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800949 ).isOk()) {
950 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
Ruben Brunkb2119af2014-05-09 19:57:56 -0700951 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800952 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700953}
954
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800955Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -0700956 /*out*/
957 CameraParameters* parameters) {
958
959 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
960
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800961 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -0700962
963 if (parameters == NULL) {
964 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800965 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -0700966 }
967
Ruben Brunkcc776712015-02-17 20:18:47 -0800968 String8 id = String8::format("%d", cameraId);
969
970 // Check if we already have parameters
971 {
972 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -0700973 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -0800974 auto cameraState = getCameraState(id);
975 if (cameraState == nullptr) {
976 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800977 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
978 "Invalid camera ID: %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -0800979 }
980 CameraParameters p = cameraState->getShimParams();
981 if (!p.isEmpty()) {
982 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800983 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700984 }
985 }
986
Jayant Chowdhary12361932018-08-27 14:46:13 -0700987 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -0800988 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -0700989 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800990 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800991 // Error already logged by callee
992 return ret;
993 }
994
995 // Check for parameters again
996 {
997 // Scope for service lock
998 Mutex::Autolock lock(mServiceLock);
999 auto cameraState = getCameraState(id);
1000 if (cameraState == nullptr) {
1001 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001002 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1003 "Invalid camera ID: %s", id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001004 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001005 CameraParameters p = cameraState->getShimParams();
1006 if (!p.isEmpty()) {
1007 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001008 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001009 }
1010 }
1011
Ruben Brunkcc776712015-02-17 20:18:47 -08001012 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1013 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001014 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001015}
1016
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001017// Can camera service trust the caller based on the calling UID?
1018static bool isTrustedCallingUid(uid_t uid) {
1019 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001020 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001021 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001022 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001023 return true;
1024 default:
1025 return false;
1026 }
1027}
1028
Nicholas Sauera3620332019-04-03 14:05:17 -07001029static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1030 PermissionController pc;
1031 uid = pc.getPackageUid(packageName, 0);
1032 if (uid <= 0) {
1033 ALOGE("Unknown package: '%s'", String8(packageName).string());
1034 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
1035 return BAD_VALUE;
1036 }
1037
1038 if (userId < 0) {
1039 ALOGE("Invalid user: %d", userId);
1040 dprintf(err, "Invalid user: %d\n", userId);
1041 return BAD_VALUE;
1042 }
1043
1044 uid = multiuser_get_uid(userId, uid);
1045 return NO_ERROR;
1046}
1047
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001048Status CameraService::validateConnectLocked(const String8& cameraId,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001049 const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
1050 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001051
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001052#ifdef __BRILLO__
1053 UNUSED(clientName8);
1054 UNUSED(clientUid);
1055 UNUSED(clientPid);
1056 UNUSED(originalClientPid);
1057#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001058 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1059 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001060 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001061 return allowed;
1062 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001063#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001064
Jayant Chowdhary12361932018-08-27 14:46:13 -07001065 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001066
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001067 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001068 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1069 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001070 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1071 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001072 }
1073
Ruben Brunkcc776712015-02-17 20:18:47 -08001074 if (getCameraState(cameraId) == nullptr) {
1075 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1076 cameraId.string());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001077 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1078 "No camera device with ID \"%s\" available", cameraId.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001079 }
1080
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001081 status_t err = checkIfDeviceIsUsable(cameraId);
1082 if (err != NO_ERROR) {
1083 switch(err) {
1084 case -ENODEV:
1085 case -EBUSY:
1086 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1087 "No camera device with ID \"%s\" currently available", cameraId.string());
1088 default:
1089 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1090 "Unknown error connecting to ID \"%s\"", cameraId.string());
1091 }
1092 }
1093 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001094}
1095
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001096Status CameraService::validateClientPermissionsLocked(const String8& cameraId,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001097 const String8& clientName8, int& clientUid, int& clientPid,
1098 /*out*/int& originalClientPid) const {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001099 int callingPid = CameraThreadState::getCallingPid();
1100 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001101
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001102 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001103 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001104 clientUid = callingUid;
1105 } else if (!isTrustedCallingUid(callingUid)) {
1106 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1107 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001108 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1109 "Untrusted caller (calling PID %d, UID %d) trying to "
1110 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1111 callingPid, callingUid, cameraId.string(),
1112 clientName8.string(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001113 }
1114
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001115 // Check if we can trust clientPid
1116 if (clientPid == USE_CALLING_PID) {
1117 clientPid = callingPid;
1118 } else if (!isTrustedCallingUid(callingUid)) {
1119 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1120 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001121 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1122 "Untrusted caller (calling PID %d, UID %d) trying to "
1123 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1124 callingPid, callingUid, cameraId.string(),
1125 clientName8.string(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001126 }
1127
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001128 if (shouldRejectSystemCameraConnection(cameraId)) {
1129 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1130 cameraId.c_str());
1131 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
1132 "available", cameraId.string());
1133 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001134 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1135 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1136 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
1137 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
1138 "found while trying to query device kind", cameraId.string());
1139
1140 }
1141
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001142 // If it's not calling from cameraserver, check the permission if the
1143 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1144 // android.permission.SYSTEM_CAMERA for system only camera devices).
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001145 if (callingPid != getpid() &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001146 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001147 !checkPermission(sCameraPermission, clientPid, clientUid)) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001148 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001149 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1150 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
1151 clientName8.string(), clientUid, clientPid, cameraId.string());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001152 }
1153
Svet Ganova453d0d2018-01-11 15:37:58 -08001154 // Make sure the UID is in an active state to use the camera
Svet Ganov7b4ab782018-03-25 12:48:10 -07001155 if (!mUidPolicy->isUidActive(callingUid, String16(clientName8))) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001156 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001157 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1158 clientPid, clientUid);
1159 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001160 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1161 "calling UID %d proc state %" PRId32 ")",
1162 clientName8.string(), clientUid, clientPid, cameraId.string(),
1163 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001164 }
1165
Michael Grooverd1d435a2018-12-18 17:39:42 -08001166 // If sensor privacy is enabled then prevent access to the camera
1167 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1168 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1169 return STATUS_ERROR_FMT(ERROR_DISABLED,
1170 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
1171 "is enabled", clientName8.string(), clientUid, clientPid, cameraId.string());
1172 }
1173
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001174 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1175 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001176 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001177 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001178
Ruben Brunk6267b532015-04-30 17:44:07 -07001179 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001180
Ruben Brunka8ca9152015-04-07 14:23:40 -07001181 // Only allow clients who are being used by the current foreground device user, unless calling
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001182 // from our own process OR the caller is using the cameraserver's HIDL interface.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001183 if (getCurrentServingCall() != BinderCallType::HWBINDER && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001184 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001185 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1186 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
1187 toString(mAllowedUsers).string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001188 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1189 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
1190 clientUserId, cameraId.string());
Ruben Brunk36597b22015-03-20 22:15:57 -07001191 }
1192
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001193 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001194}
1195
1196status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
1197 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001198 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001199 if (cameraState == nullptr) {
1200 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1201 cameraId.string());
1202 return -ENODEV;
1203 }
1204
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001205 StatusInternal currentStatus = cameraState->getStatus();
1206 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001207 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
1208 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001209 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001210 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001211 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
1212 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001213 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001214 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001215
Ruben Brunkcc776712015-02-17 20:18:47 -08001216 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001217}
1218
Ruben Brunkcc776712015-02-17 20:18:47 -08001219void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001220 const CameraService::DescriptorPtr& desc, int oomScoreOffset) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001221
Ruben Brunkcc776712015-02-17 20:18:47 -08001222 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001223 auto clientDescriptor =
1224 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
1225 oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08001226 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1227
1228 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
1229 String8(client->getPackageName()));
1230
1231 if (evicted.size() > 0) {
1232 // This should never happen - clients should already have been removed in disconnect
1233 for (auto& i : evicted) {
1234 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
1235 __FUNCTION__, i->getKey().string());
1236 }
1237
1238 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1239 __FUNCTION__);
1240 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001241
1242 // And register a death notification for the client callback. Do
1243 // this last to avoid Binder policy where a nested Binder
1244 // transaction might be pre-empted to service the client death
1245 // notification if the client process dies before linkToDeath is
1246 // invoked.
1247 sp<IBinder> remoteCallback = client->getRemote();
1248 if (remoteCallback != nullptr) {
1249 remoteCallback->linkToDeath(this);
1250 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001251}
1252
1253status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
1254 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001255 int oomScoreOffset,
Ruben Brunkcc776712015-02-17 20:18:47 -08001256 /*out*/
1257 sp<BasicClient>* client,
1258 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001259 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001260 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001261 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001262 DescriptorPtr clientDescriptor;
1263 {
1264 if (effectiveApiLevel == API_1) {
1265 // If we are using API1, any existing client for this camera ID with the same remote
1266 // should be returned rather than evicted to allow MediaRecorder to work properly.
1267
1268 auto current = mActiveClientManager.get(cameraId);
1269 if (current != nullptr) {
1270 auto clientSp = current->getValue();
1271 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001272 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
1273 ALOGW("CameraService connect called from same client, but with a different"
1274 " API level, evicting prior client...");
1275 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001276 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001277 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001278 *client = clientSp;
1279 return NO_ERROR;
1280 }
1281 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001282 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001283 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001284
Ruben Brunkcc776712015-02-17 20:18:47 -08001285 // Get current active client PIDs
1286 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1287 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001288
Emilian Peev8131a262017-02-01 12:33:43 +00001289 std::vector<int> priorityScores(ownerPids.size());
1290 std::vector<int> states(ownerPids.size());
Igor Murashkine6800ce2013-03-04 17:25:57 -08001291
Emilian Peev8131a262017-02-01 12:33:43 +00001292 // Get priority scores of all active PIDs
1293 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1294 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1295 /*out*/&priorityScores[0]);
1296 if (err != OK) {
1297 ALOGE("%s: Priority score query failed: %d",
1298 __FUNCTION__, err);
1299 return err;
1300 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001301
Ruben Brunkcc776712015-02-17 20:18:47 -08001302 // Update all active clients' priorities
Emilian Peev8131a262017-02-01 12:33:43 +00001303 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
Ruben Brunkcc776712015-02-17 20:18:47 -08001304 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
Emilian Peev8131a262017-02-01 12:33:43 +00001305 pidToPriorityMap.emplace(ownerPids[i],
Jayant Chowdharyc578a502019-05-08 10:57:54 -07001306 resource_policy::ClientPriority(priorityScores[i], states[i],
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001307 /* isVendorClient won't get copied over*/ false,
1308 /* oomScoreOffset won't get copied over*/ 0));
Ruben Brunkcc776712015-02-17 20:18:47 -08001309 }
1310 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001311
Ruben Brunkcc776712015-02-17 20:18:47 -08001312 // Get state for the given cameraId
1313 auto state = getCameraState(cameraId);
1314 if (state == nullptr) {
1315 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1316 clientPid, cameraId.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001317 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001318 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001319 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001320
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001321 int32_t actualScore = priorityScores[priorityScores.size() - 1];
1322 int32_t actualState = states[states.size() - 1];
1323
1324 // Make descriptor for incoming client. We store the oomScoreOffset
1325 // since we might need it later on new handleEvictionsLocked and
1326 // ProcessInfoService would not take that into account.
Shuzhen Wang2db86ff2018-04-25 01:11:17 +00001327 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001328 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001329 state->getConflicting(), actualScore, clientPid, actualState,
1330 oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08001331
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001332 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1333
Ruben Brunkcc776712015-02-17 20:18:47 -08001334 // Find clients that would be evicted
1335 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1336
1337 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1338 // background, so we cannot do evictions
1339 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1340 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1341 " priority).", clientPid);
1342
1343 sp<BasicClient> clientSp = clientDescriptor->getValue();
1344 String8 curTime = getFormattedCurrentTime();
1345 auto incompatibleClients =
1346 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1347
1348 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Emilian Peev8131a262017-02-01 12:33:43 +00001349 "(PID %d, score %d state %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001350 cameraId.string(), packageName.string(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001351 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001352
1353 for (auto& i : incompatibleClients) {
1354 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001355 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
1356 i->getKey().string(),
1357 String8{i->getValue()->getPackageName()}.string(),
1358 i->getOwnerId(), i->getPriority().getScore(),
1359 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001360 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00001361 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(),
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001362 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001363 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001364 }
1365
1366 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001367 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001368 mEventLog.add(msg);
1369
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001370 auto current = mActiveClientManager.get(cameraId);
1371 if (current != nullptr) {
1372 return -EBUSY; // CAMERA_IN_USE
1373 } else {
1374 return -EUSERS; // MAX_CAMERAS_IN_USE
1375 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001376 }
1377
1378 for (auto& i : evicted) {
1379 sp<BasicClient> clientSp = i->getValue();
1380 if (clientSp.get() == nullptr) {
1381 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1382
1383 // TODO: Remove this
1384 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1385 __FUNCTION__);
1386 mActiveClientManager.remove(i);
1387 continue;
1388 }
1389
1390 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1391 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001392 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001393
Ruben Brunkcc776712015-02-17 20:18:47 -08001394 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001395 logEvent(String8::format("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00001396 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1397 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001398 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
Emilian Peev8131a262017-02-01 12:33:43 +00001399 i->getOwnerId(), i->getPriority().getScore(),
1400 i->getPriority().getState(), cameraId.string(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001401 packageName.string(), clientPid, clientPriority.getScore(),
1402 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08001403
1404 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001405 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001406 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001407 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001408 }
1409
Ruben Brunkcc776712015-02-17 20:18:47 -08001410 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1411 // other clients from connecting in mServiceLockWrapper if held
1412 mServiceLock.unlock();
1413
1414 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07001415 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001416
1417 // Destroy evicted clients
1418 for (auto& i : evictedClients) {
1419 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001420 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001421 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001422
Jayant Chowdhary12361932018-08-27 14:46:13 -07001423 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08001424
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001425 for (const auto& i : evictedClients) {
1426 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1427 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1428 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1429 if (ret == TIMED_OUT) {
1430 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1431 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1432 mActiveClientManager.toString().string());
1433 return -EBUSY;
1434 }
1435 if (ret != NO_ERROR) {
1436 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1437 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1438 ret, mActiveClientManager.toString().string());
1439 return ret;
1440 }
1441 }
1442
1443 evictedClients.clear();
1444
Ruben Brunkcc776712015-02-17 20:18:47 -08001445 // Once clients have been disconnected, relock
1446 mServiceLock.lock();
1447
1448 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1449 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1450 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001451 }
1452
Ruben Brunkcc776712015-02-17 20:18:47 -08001453 *partial = clientDescriptor;
1454 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001455}
1456
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001457Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001458 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001459 int api1CameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001460 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001461 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001462 int clientPid,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001463 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001464 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001465
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001466 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001467 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001468
1469 String8 id = cameraIdIntToStr(api1CameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001470 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001471 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001472 clientPackageName, {}, clientUid, clientPid, API_1,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001473 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001474
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001475 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001476 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001477 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001478 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001479 }
1480
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001481 *device = client;
1482 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001483}
1484
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001485bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
1486 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001487 // If the client is not a vendor client, don't add listener if
1488 // a) the camera is a publicly hidden secure camera OR
1489 // b) the camera is a system only camera and the client doesn't
1490 // have android.permission.SYSTEM_CAMERA permissions.
1491 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
1492 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1493 !hasPermissionsForSystemCamera(clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001494 return true;
1495 }
1496 return false;
1497}
1498
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001499bool CameraService::shouldRejectSystemCameraConnection(const String8& cameraId) const {
1500 // Rules for rejection:
1501 // 1) If cameraserver tries to access this camera device, accept the
1502 // connection.
1503 // 2) The camera device is a publicly hidden secure camera device AND some
1504 // component is trying to access it on a non-hwbinder thread (generally a non HAL client),
1505 // reject it.
1506 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
1507 // and the serving thread is a non hwbinder thread, the client must have
1508 // android.permission.SYSTEM_CAMERA permissions to connect.
1509
1510 int cPid = CameraThreadState::getCallingPid();
1511 int cUid = CameraThreadState::getCallingUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001512 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
1513 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001514 // This isn't a known camera ID, so it's not a system camera
1515 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
1516 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001517 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001518
1519 // (1) Cameraserver trying to connect, accept.
1520 if (CameraThreadState::getCallingPid() == getpid()) {
1521 return false;
1522 }
1523 // (2)
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001524 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001525 systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
1526 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
1527 return true;
1528 }
1529 // (3) Here we only check for permissions if it is a system only camera device. This is since
1530 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
1531 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
1532 // same behavior for system camera devices.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001533 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001534 systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1535 !hasPermissionsForSystemCamera(cPid, cUid)) {
1536 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
1537 cameraId.c_str());
1538 return true;
1539 }
1540
1541 return false;
1542}
1543
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001544Status CameraService::connectDevice(
1545 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001546 const String16& cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001547 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001548 const std::optional<String16>& clientFeatureId,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001549 int clientUid, int oomScoreOffset,
Ruben Brunkcc776712015-02-17 20:18:47 -08001550 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001551 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001552
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001553 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001554 Status ret = Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001555 String8 id = String8(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001556 sp<CameraDeviceClient> client = nullptr;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001557 String16 clientPackageNameAdj = clientPackageName;
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001558 int callingPid = CameraThreadState::getCallingPid();
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001559
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001560 if (getCurrentServingCall() == BinderCallType::HWBINDER) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001561 std::string vendorClient =
1562 StringPrintf("vendor.client.pid<%d>", CameraThreadState::getCallingPid());
1563 clientPackageNameAdj = String16(vendorClient.c_str());
1564 }
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001565
1566 if (oomScoreOffset < 0) {
1567 String8 msg =
1568 String8::format("Cannot increase the priority of a client %s pid %d for "
1569 "camera id %s", String8(clientPackageNameAdj).string(), callingPid,
1570 id.string());
1571 ALOGE("%s: %s", __FUNCTION__, msg.string());
1572 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
1573 }
1574
1575 // enforce system camera permissions
1576 if (oomScoreOffset > 0 &&
1577 !hasPermissionsForSystemCamera(callingPid, CameraThreadState::getCallingUid())) {
1578 String8 msg =
1579 String8::format("Cannot change the priority of a client %s pid %d for "
1580 "camera id %s without SYSTEM_CAMERA permissions",
1581 String8(clientPackageNameAdj).string(), callingPid, id.string());
1582 ALOGE("%s: %s", __FUNCTION__, msg.string());
1583 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.string());
1584 }
1585
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001586 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001587 /*api1CameraId*/-1, clientPackageNameAdj, clientFeatureId,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001588 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, oomScoreOffset,
1589 /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08001590
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001591 if(!ret.isOk()) {
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001592 logRejected(id, callingPid, String8(clientPackageNameAdj), ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001593 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001594 }
1595
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001596 *device = client;
1597 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001598}
1599
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001600template<class CALLBACK, class CLIENT>
1601Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001602 int api1CameraId, const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001603 const std::optional<String16>& clientFeatureId, int clientUid, int clientPid,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001604 apiLevel effectiveApiLevel, bool shimUpdateOnly, int oomScoreOffset,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001605 /*out*/sp<CLIENT>& device) {
1606 binder::Status ret = binder::Status::ok();
1607
1608 String8 clientName8(clientPackageName);
1609
1610 int originalClientPid = 0;
1611
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001612 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001613 "Camera API version %d", clientPid, clientName8.string(), cameraId.string(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001614 static_cast<int>(effectiveApiLevel));
1615
Shuzhen Wang316781a2020-08-18 18:11:01 -07001616 nsecs_t openTimeNs = systemTime();
1617
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001618 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001619 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07001620 int orientation = 0;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001621 bool isNdk = (clientPackageName.size() == 0);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001622 {
1623 // Acquire mServiceLock and prevent other clients from connecting
1624 std::unique_ptr<AutoConditionLock> lock =
1625 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1626
1627 if (lock == nullptr) {
1628 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
1629 , clientPid);
1630 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1631 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
1632 cameraId.string(), clientName8.string(), clientPid);
1633 }
1634
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07001635 // Enforce client permissions and do basic validity checks
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001636 if(!(ret = validateConnectLocked(cameraId, clientName8,
1637 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
1638 return ret;
1639 }
1640
1641 // Check the shim parameters after acquiring lock, if they have already been updated and
1642 // we were doing a shim update, return immediately
1643 if (shimUpdateOnly) {
1644 auto cameraState = getCameraState(cameraId);
1645 if (cameraState != nullptr) {
1646 if (!cameraState->getShimParams().isEmpty()) return ret;
1647 }
1648 }
1649
1650 status_t err;
1651
1652 sp<BasicClient> clientTmp = nullptr;
1653 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
1654 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001655 IInterface::asBinder(cameraCb), clientName8, oomScoreOffset, /*out*/&clientTmp,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001656 /*out*/&partial)) != NO_ERROR) {
1657 switch (err) {
1658 case -ENODEV:
1659 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1660 "No camera device with ID \"%s\" currently available",
1661 cameraId.string());
1662 case -EBUSY:
1663 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1664 "Higher-priority client using camera, ID \"%s\" currently unavailable",
1665 cameraId.string());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001666 case -EUSERS:
1667 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1668 "Too many cameras already open, cannot open camera \"%s\"",
1669 cameraId.string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001670 default:
1671 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1672 "Unexpected error %s (%d) opening camera \"%s\"",
1673 strerror(-err), err, cameraId.string());
1674 }
1675 }
1676
1677 if (clientTmp.get() != nullptr) {
1678 // Handle special case for API1 MediaRecorder where the existing client is returned
1679 device = static_cast<CLIENT*>(clientTmp.get());
1680 return ret;
1681 }
1682
1683 // give flashlight a chance to close devices if necessary.
1684 mFlashlight->prepareDeviceOpen(cameraId);
1685
Emilian Peevb91f1802021-03-23 14:50:28 -07001686 int deviceVersion = getDeviceVersion(cameraId, /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08001687 if (facing == -1) {
1688 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.string());
1689 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1690 "Unable to get camera device \"%s\" facing", cameraId.string());
1691 }
1692
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001693 sp<BasicClient> tmp = nullptr;
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001694 if(!(ret = makeClient(this, cameraCb, clientPackageName, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07001695 cameraId, api1CameraId, facing, orientation,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001696 clientPid, clientUid, getpid(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001697 deviceVersion, effectiveApiLevel,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001698 /*out*/&tmp)).isOk()) {
1699 return ret;
1700 }
1701 client = static_cast<CLIENT*>(tmp.get());
1702
1703 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
1704 __FUNCTION__);
1705
Emilian Peevbd8c5032018-02-14 23:05:40 +00001706 err = client->initialize(mCameraProviderManager, mMonitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001707 if (err != OK) {
1708 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001709 // Errors could be from the HAL module open call or from AppOpsManager
1710 switch(err) {
1711 case BAD_VALUE:
1712 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1713 "Illegal argument to HAL module for camera \"%s\"", cameraId.string());
1714 case -EBUSY:
1715 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1716 "Camera \"%s\" is already open", cameraId.string());
1717 case -EUSERS:
1718 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1719 "Too many cameras already open, cannot open camera \"%s\"",
1720 cameraId.string());
1721 case PERMISSION_DENIED:
1722 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1723 "No permission to open camera \"%s\"", cameraId.string());
1724 case -EACCES:
1725 return STATUS_ERROR_FMT(ERROR_DISABLED,
1726 "Camera \"%s\" disabled by policy", cameraId.string());
1727 case -ENODEV:
1728 default:
1729 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1730 "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
1731 strerror(-err), err);
1732 }
1733 }
1734
1735 // Update shim paremeters for legacy clients
1736 if (effectiveApiLevel == API_1) {
1737 // Assume we have always received a Client subclass for API1
1738 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
1739 String8 rawParams = shimClient->getParameters();
1740 CameraParameters params(rawParams);
1741
1742 auto cameraState = getCameraState(cameraId);
1743 if (cameraState != nullptr) {
1744 cameraState->setShimParams(params);
1745 } else {
1746 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
1747 __FUNCTION__, cameraId.string());
1748 }
1749 }
1750
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001751 // Set rotate-and-crop override behavior
1752 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
1753 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
Emilian Peevb91f1802021-03-23 14:50:28 -07001754 } else if (CameraServiceProxyWrapper::isRotateAndCropOverrideNeeded(clientPackageName,
1755 orientation, facing)) {
1756 client->setRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_90);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001757 }
1758
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08001759 // Set camera muting behavior
1760 if (client->supportsCameraMute()) {
Evan Severson09ab4002021-02-10 14:15:19 -08001761 bool isCameraPrivacyEnabled =
1762 mSensorPrivacyPolicy->isCameraPrivacyEnabled(multiuser_get_user_id(clientUid));
1763 client->setCameraMute(mOverrideCameraMuteMode || isCameraPrivacyEnabled);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08001764 }
1765
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001766 if (shimUpdateOnly) {
1767 // If only updating legacy shim parameters, immediately disconnect client
1768 mServiceLock.unlock();
1769 client->disconnect();
1770 mServiceLock.lock();
1771 } else {
1772 // Otherwise, add client to active clients list
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001773 finishConnectLocked(client, partial, oomScoreOffset);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001774 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001775
1776 client->setImageDumpMask(mImageDumpMask);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001777 } // lock is destroyed, allow further connect calls
1778
1779 // Important: release the mutex here so the client can call back into the service from its
1780 // destructor (can be at the end of the call)
1781 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001782
1783 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
1784 CameraServiceProxyWrapper::logOpen(cameraId, facing, clientPackageName,
1785 effectiveApiLevel, isNdk, openLatencyMs);
1786
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001787 return ret;
1788}
1789
Emilian Peevb2bc5a42019-11-20 16:02:14 -08001790status_t CameraService::addOfflineClient(String8 cameraId, sp<BasicClient> offlineClient) {
1791 if (offlineClient.get() == nullptr) {
1792 return BAD_VALUE;
1793 }
1794
1795 {
1796 // Acquire mServiceLock and prevent other clients from connecting
1797 std::unique_ptr<AutoConditionLock> lock =
1798 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1799
1800 if (lock == nullptr) {
1801 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
1802 , __FUNCTION__, offlineClient->getClientPid());
1803 return TIMED_OUT;
1804 }
1805
1806 auto onlineClientDesc = mActiveClientManager.get(cameraId);
1807 if (onlineClientDesc.get() == nullptr) {
1808 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
1809 cameraId.c_str());
1810 return BAD_VALUE;
1811 }
1812
1813 // Offline clients do not evict or conflict with other online devices. Resource sharing
1814 // conflicts are handled by the camera provider which will either succeed or fail before
1815 // reaching this method.
1816 const auto& onlinePriority = onlineClientDesc->getPriority();
1817 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
1818 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
1819 /*conflictingKeys*/ std::set<String8>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001820 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
1821 /*ommScoreOffset*/ 0);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08001822
1823 // Allow only one offline device per camera
1824 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
1825 if (!incompatibleClients.empty()) {
1826 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
1827 return BAD_VALUE;
1828 }
1829
1830 auto err = offlineClient->initialize(mCameraProviderManager, mMonitorTags);
1831 if (err != OK) {
1832 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
1833 return err;
1834 }
1835
1836 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
1837 if (evicted.size() > 0) {
1838 for (auto& i : evicted) {
1839 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
1840 __FUNCTION__, i->getKey().string());
1841 }
1842
1843 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
1844 "properly", __FUNCTION__);
1845
1846 return BAD_VALUE;
1847 }
1848
1849 logConnectedOffline(offlineClientDesc->getKey(),
1850 static_cast<int>(offlineClientDesc->getOwnerId()),
1851 String8(offlineClient->getPackageName()));
1852
1853 sp<IBinder> remoteCallback = offlineClient->getRemote();
1854 if (remoteCallback != nullptr) {
1855 remoteCallback->linkToDeath(this);
1856 }
1857 } // lock is destroyed, allow further connect calls
1858
1859 return OK;
1860}
1861
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001862Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001863 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001864 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001865
1866 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07001867 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001868 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001869 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1870 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001871 }
1872
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001873 String8 id = String8(cameraId.string());
Jayant Chowdhary12361932018-08-27 14:46:13 -07001874 int uid = CameraThreadState::getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001875
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07001876 if (shouldRejectSystemCameraConnection(id)) {
1877 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
1878 " for system only device %s: ", id.string());
1879 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001880 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08001881 auto state = getCameraState(id);
1882 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001883 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001884 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1885 "Camera ID \"%s\" is a not valid camera ID", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001886 }
1887
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001888 StatusInternal cameraStatus = state->getStatus();
1889 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001890 cameraStatus != StatusInternal::NOT_AVAILABLE) {
1891 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001892 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1893 "Camera ID \"%s\" is a not valid camera ID", id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001894 }
1895
1896 {
1897 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001898 TorchModeStatus status;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001899 status_t err = getTorchStatusLocked(id, &status);
1900 if (err != OK) {
1901 if (err == NAME_NOT_FOUND) {
1902 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1903 "Camera \"%s\" does not have a flash unit", id.string());
1904 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001905 ALOGE("%s: getting current torch status failed for camera %s",
1906 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001907 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1908 "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
1909 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001910 }
1911
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001912 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001913 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001914 ALOGE("%s: torch mode of camera %s is not available because "
1915 "camera is in use", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001916 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1917 "Torch for camera \"%s\" is not available due to an existing camera user",
1918 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001919 } else {
1920 ALOGE("%s: torch mode of camera %s is not available due to "
1921 "insufficient resources", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001922 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1923 "Torch for camera \"%s\" is not available due to insufficient resources",
1924 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001925 }
1926 }
1927 }
1928
Ruben Brunk99e69712015-05-26 17:25:07 -07001929 {
1930 // Update UID map - this is used in the torch status changed callbacks, so must be done
1931 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07001932 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -07001933 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
1934 mTorchUidMap[id].first = uid;
1935 mTorchUidMap[id].second = uid;
1936 } else {
1937 // Set the pending UID
1938 mTorchUidMap[id].first = uid;
1939 }
1940 }
1941
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001942 status_t err = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07001943
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001944 if (err != OK) {
1945 int32_t errorCode;
1946 String8 msg;
1947 switch (err) {
1948 case -ENOSYS:
1949 msg = String8::format("Camera \"%s\" has no flashlight",
1950 id.string());
1951 errorCode = ERROR_ILLEGAL_ARGUMENT;
1952 break;
1953 default:
1954 msg = String8::format(
1955 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
1956 id.string(), enabled, strerror(-err), err);
1957 errorCode = ERROR_INVALID_OPERATION;
1958 }
1959 ALOGE("%s: %s", __FUNCTION__, msg.string());
Rucha Katakward9ea6452021-05-06 11:57:16 -07001960 logServiceError(msg,errorCode);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001961 return STATUS_ERROR(errorCode, msg.string());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001962 }
1963
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001964 {
1965 // update the link to client's death
1966 Mutex::Autolock al(mTorchClientMapMutex);
1967 ssize_t index = mTorchClientMap.indexOfKey(id);
1968 if (enabled) {
1969 if (index == NAME_NOT_FOUND) {
1970 mTorchClientMap.add(id, clientBinder);
1971 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07001972 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001973 mTorchClientMap.replaceValueAt(index, clientBinder);
1974 }
1975 clientBinder->linkToDeath(this);
1976 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07001977 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001978 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001979 }
1980
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07001981 int clientPid = CameraThreadState::getCallingPid();
1982 const char *id_cstr = id.c_str();
1983 const char *torchState = enabled ? "on" : "off";
1984 ALOGI("Torch for camera id %s turned %s for client PID %d", id_cstr, torchState, clientPid);
1985 logTorchEvent(id_cstr, torchState , clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001986 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001987}
1988
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001989Status CameraService::notifySystemEvent(int32_t eventId,
1990 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001991 const int pid = CameraThreadState::getCallingPid();
1992 const int selfPid = getpid();
1993
1994 // Permission checks
1995 if (pid != selfPid) {
1996 // Ensure we're being called by system_server, or similar process with
1997 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001998 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001999 const int uid = CameraThreadState::getCallingUid();
2000 ALOGE("Permission Denial: cannot send updates to camera service about system"
2001 " events from pid=%d, uid=%d", pid, uid);
2002 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09002003 "No permission to send updates to camera service about system events"
2004 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002005 }
2006 }
2007
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002008 ATRACE_CALL();
2009
Ruben Brunk36597b22015-03-20 22:15:57 -07002010 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002011 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08002012 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002013 // from a system server crash
2014 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08002015 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002016 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07002017 break;
2018 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002019 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07002020 default: {
2021 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
2022 eventId);
2023 break;
2024 }
2025 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002026 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002027}
2028
Emilian Peev53722fa2019-02-22 17:47:20 -08002029void CameraService::notifyMonitoredUids() {
2030 Mutex::Autolock lock(mStatusListenerLock);
2031
2032 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002033 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Emilian Peev53722fa2019-02-22 17:47:20 -08002034 if (!ret.isOk()) {
2035 ALOGE("%s: Failed to trigger permission callback: %d", __FUNCTION__,
2036 ret.exceptionCode());
2037 }
2038 }
2039}
2040
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002041Status CameraService::notifyDeviceStateChange(int64_t newState) {
2042 const int pid = CameraThreadState::getCallingPid();
2043 const int selfPid = getpid();
2044
2045 // Permission checks
2046 if (pid != selfPid) {
2047 // Ensure we're being called by system_server, or similar process with
2048 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002049 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002050 const int uid = CameraThreadState::getCallingUid();
2051 ALOGE("Permission Denial: cannot send updates to camera service about device"
2052 " state changes from pid=%d, uid=%d", pid, uid);
2053 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2054 "No permission to send updates to camera service about device state"
2055 " changes from pid=%d, uid=%d", pid, uid);
2056 }
2057 }
2058
2059 ATRACE_CALL();
2060
2061 using hardware::camera::provider::V2_5::DeviceState;
2062 hardware::hidl_bitfield<DeviceState> newDeviceState{};
2063 if (newState & ICameraService::DEVICE_STATE_BACK_COVERED) {
2064 newDeviceState |= DeviceState::BACK_COVERED;
2065 }
2066 if (newState & ICameraService::DEVICE_STATE_FRONT_COVERED) {
2067 newDeviceState |= DeviceState::FRONT_COVERED;
2068 }
2069 if (newState & ICameraService::DEVICE_STATE_FOLDED) {
2070 newDeviceState |= DeviceState::FOLDED;
2071 }
2072 // Only map vendor bits directly
2073 uint64_t vendorBits = static_cast<uint64_t>(newState) & 0xFFFFFFFF00000000l;
2074 newDeviceState |= vendorBits;
2075
2076 ALOGV("%s: New device state 0x%" PRIx64, __FUNCTION__, newDeviceState);
2077 Mutex::Autolock l(mServiceLock);
2078 mCameraProviderManager->notifyDeviceStateChange(newDeviceState);
2079
2080 return Status::ok();
2081}
2082
Emilian Peev8b64f282021-03-25 16:49:57 -07002083Status CameraService::notifyDisplayConfigurationChange() {
2084 ATRACE_CALL();
2085 const int callingPid = CameraThreadState::getCallingPid();
2086 const int selfPid = getpid();
2087
2088 // Permission checks
2089 if (callingPid != selfPid) {
2090 // Ensure we're being called by system_server, or similar process with
2091 // permissions to notify the camera service about system events
2092 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
2093 const int uid = CameraThreadState::getCallingUid();
2094 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
2095 " changes from pid=%d, uid=%d", callingPid, uid);
2096 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2097 "No permission to send updates to camera service about orientation"
2098 " changes from pid=%d, uid=%d", callingPid, uid);
2099 }
2100 }
2101
2102 Mutex::Autolock lock(mServiceLock);
2103
2104 // Don't do anything if rotate-and-crop override via cmd is active
2105 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
2106
2107 const auto clients = mActiveClientManager.getAll();
2108 for (auto& current : clients) {
2109 if (current != nullptr) {
2110 const auto basicClient = current->getValue();
2111 if (basicClient.get() != nullptr) {
2112 if (CameraServiceProxyWrapper::isRotateAndCropOverrideNeeded(
2113 basicClient->getPackageName(), basicClient->getCameraOrientation(),
2114 basicClient->getCameraFacing())) {
2115 basicClient->setRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_90);
2116 } else {
2117 basicClient->setRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE);
2118 }
2119 }
2120 }
2121 }
2122
2123 return Status::ok();
2124}
2125
2126Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002127 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
2128 ATRACE_CALL();
2129 if (!concurrentCameraIds) {
2130 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
2131 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
2132 }
2133
2134 if (!mInitialized) {
2135 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Rucha Katakward9ea6452021-05-06 11:57:16 -07002136 logServiceError(String8::format("Camera subsystem is not available"),ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002137 return STATUS_ERROR(ERROR_DISCONNECTED,
2138 "Camera subsystem is not available");
2139 }
2140 // First call into the provider and get the set of concurrent camera
2141 // combinations
2142 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07002143 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002144 for (auto &combination : concurrentCameraCombinations) {
2145 std::vector<std::string> validCombination;
2146 for (auto &cameraId : combination) {
2147 // if the camera state is not present, skip
2148 String8 cameraIdStr(cameraId.c_str());
2149 auto state = getCameraState(cameraIdStr);
2150 if (state == nullptr) {
2151 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
2152 continue;
2153 }
2154 StatusInternal status = state->getStatus();
2155 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
2156 continue;
2157 }
2158 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
2159 continue;
2160 }
2161 validCombination.push_back(cameraId);
2162 }
2163 if (validCombination.size() != 0) {
2164 concurrentCameraIds->push_back(std::move(validCombination));
2165 }
2166 }
2167 return Status::ok();
2168}
2169
2170Status CameraService::isConcurrentSessionConfigurationSupported(
2171 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
2172 /*out*/bool* isSupported) {
2173 if (!isSupported) {
2174 ALOGE("%s: isSupported is NULL", __FUNCTION__);
2175 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
2176 }
2177
2178 if (!mInitialized) {
2179 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2180 return STATUS_ERROR(ERROR_DISCONNECTED,
2181 "Camera subsystem is not available");
2182 }
2183
2184 // Check for camera permissions
2185 int callingPid = CameraThreadState::getCallingPid();
2186 int callingUid = CameraThreadState::getCallingUid();
2187 if ((callingPid != getpid()) && !checkPermission(sCameraPermission, callingPid, callingUid)) {
2188 ALOGE("%s: pid %d doesn't have camera permissions", __FUNCTION__, callingPid);
2189 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2190 "android.permission.CAMERA needed to call"
2191 "isConcurrentSessionConfigurationSupported");
2192 }
2193
2194 status_t res =
2195 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
2196 cameraIdsAndSessionConfigurations, isSupported);
2197 if (res != OK) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07002198 logServiceError(String8::format("Unable to query session configuration support"),
2199 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002200 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
2201 "support %s (%d)", strerror(-res), res);
2202 }
2203 return Status::ok();
2204}
2205
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002206Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
2207 /*out*/
2208 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002209 return addListenerHelper(listener, cameraStatuses);
2210}
2211
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002212binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
2213 std::vector<hardware::CameraStatus>* cameraStatuses) {
2214 return addListenerHelper(listener, cameraStatuses, false, true);
2215}
2216
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002217Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
2218 /*out*/
2219 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002220 bool isVendorListener, bool isProcessLocalTest) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002221
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002222 ATRACE_CALL();
2223
Igor Murashkinbfc99152013-02-27 12:55:20 -08002224 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08002225
Ruben Brunk3450ba72015-06-16 11:00:37 -07002226 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002227 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002228 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002229 }
2230
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002231 auto clientUid = CameraThreadState::getCallingUid();
2232 auto clientPid = CameraThreadState::getCallingPid();
Shuzhen Wang695044d2020-03-06 09:02:23 -08002233 bool openCloseCallbackAllowed = checkPermission(sCameraOpenCloseListenerPermission,
2234 clientPid, clientUid);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002235
Igor Murashkinbfc99152013-02-27 12:55:20 -08002236 Mutex::Autolock lock(mServiceLock);
2237
Ruben Brunkcc776712015-02-17 20:18:47 -08002238 {
2239 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08002240 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002241 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002242 ALOGW("%s: Tried to add listener %p which was already subscribed",
2243 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002244 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08002245 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002246 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002247
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002248 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08002249 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
2250 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002251 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08002252 if (ret != NO_ERROR) {
2253 String8 msg = String8::format("Failed to initialize service listener: %s (%d)",
2254 strerror(-ret), ret);
Rucha Katakward9ea6452021-05-06 11:57:16 -07002255 logServiceError(msg,ERROR_ILLEGAL_ARGUMENT);
Emilian Peev53722fa2019-02-22 17:47:20 -08002256 ALOGE("%s: %s", __FUNCTION__, msg.string());
2257 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
2258 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002259 // The listener still needs to be added to the list of listeners, regardless of what
2260 // permissions the listener process has / whether it is a vendor listener. Since it might be
2261 // eligible to listen to other camera ids.
2262 mListenerList.emplace_back(serviceListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08002263 mUidPolicy->registerMonitorUid(clientUid);
Igor Murashkinbfc99152013-02-27 12:55:20 -08002264 }
2265
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002266 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07002267 {
Ruben Brunkcc776712015-02-17 20:18:47 -08002268 Mutex::Autolock lock(mCameraStatesLock);
2269 for (auto& i : mCameraStates) {
Shuzhen Wang43858162020-01-10 13:42:15 -08002270 cameraStatuses->emplace_back(i.first,
2271 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds());
Igor Murashkincba2c162013-03-20 15:56:31 -07002272 }
2273 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002274 // Remove the camera statuses that should be hidden from the client, we do
2275 // this after collecting the states in order to avoid holding
2276 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
2277 // the same time.
2278 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
2279 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
2280 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
2281 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
2282 ALOGE("%s: Invalid camera id %s, skipping status update",
2283 __FUNCTION__, s.cameraId.c_str());
2284 return true;
2285 }
2286 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
2287 clientUid);}), cameraStatuses->end());
2288
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002289 //cameraStatuses will have non-eligible camera ids removed.
2290 std::set<String16> idsChosenForCallback;
2291 for (const auto &s : *cameraStatuses) {
2292 idsChosenForCallback.insert(String16(s.cameraId));
2293 }
Igor Murashkincba2c162013-03-20 15:56:31 -07002294
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002295 /*
2296 * Immediately signal current torch status to this listener only
2297 * This may be a subset of all the devices, so don't include it in the response directly
2298 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002299 {
2300 Mutex::Autolock al(mTorchStatusMutex);
2301 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002302 String16 id = String16(mTorchStatusMap.keyAt(i).string());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002303 // The camera id is visible to the client. Fine to send torch
2304 // callback.
2305 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
2306 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
2307 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002308 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002309 }
2310
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002311 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08002312}
Ruben Brunkcc776712015-02-17 20:18:47 -08002313
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002314Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002315 ATRACE_CALL();
2316
Igor Murashkinbfc99152013-02-27 12:55:20 -08002317 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
2318
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002319 if (listener == 0) {
2320 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002321 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002322 }
2323
Igor Murashkinbfc99152013-02-27 12:55:20 -08002324 Mutex::Autolock lock(mServiceLock);
2325
Ruben Brunkcc776712015-02-17 20:18:47 -08002326 {
2327 Mutex::Autolock lock(mStatusListenerLock);
2328 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002329 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
2330 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid());
2331 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08002332 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002333 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002334 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002335 }
2336 }
2337
2338 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
2339 __FUNCTION__, listener.get());
2340
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002341 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08002342}
2343
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002344Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002345
2346 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002347 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
2348
2349 if (parameters == NULL) {
2350 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002351 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07002352 }
2353
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002354 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002355
2356 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002357 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07002358 // Error logged by caller
2359 return ret;
2360 }
2361
2362 String8 shimParamsString8 = shimParams.flatten();
2363 String16 shimParamsString16 = String16(shimParamsString8);
2364
2365 *parameters = shimParamsString16;
2366
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002367 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07002368}
2369
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002370Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
2371 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002372 ATRACE_CALL();
2373
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002374 const String8 id = String8(cameraId);
2375
2376 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002377
2378 switch (apiVersion) {
2379 case API_VERSION_1:
2380 case API_VERSION_2:
2381 break;
2382 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002383 String8 msg = String8::format("Unknown API version %d", apiVersion);
2384 ALOGE("%s: %s", __FUNCTION__, msg.string());
2385 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002386 }
2387
Emilian Peev28ad2ea2017-02-07 16:14:32 +00002388 int deviceVersion = getDeviceVersion(id);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002389 switch (deviceVersion) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002390 case CAMERA_DEVICE_API_VERSION_1_0:
2391 case CAMERA_DEVICE_API_VERSION_3_0:
2392 case CAMERA_DEVICE_API_VERSION_3_1:
2393 if (apiVersion == API_VERSION_2) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002394 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without shim",
2395 __FUNCTION__, id.string(), deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002396 *isSupported = false;
2397 } else { // if (apiVersion == API_VERSION_1) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002398 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always supported",
2399 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002400 *isSupported = true;
2401 }
2402 break;
2403 case CAMERA_DEVICE_API_VERSION_3_2:
2404 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -07002405 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002406 case CAMERA_DEVICE_API_VERSION_3_5:
Yin-Chia Yeh56d98ba2020-01-16 16:57:14 -08002407 case CAMERA_DEVICE_API_VERSION_3_6:
Shuzhen Wang83bff122020-11-20 15:51:39 -08002408 case CAMERA_DEVICE_API_VERSION_3_7:
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002409 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
2410 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002411 *isSupported = true;
2412 break;
2413 case -1: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002414 String8 msg = String8::format("Unknown camera ID %s", id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002415 ALOGE("%s: %s", __FUNCTION__, msg.string());
2416 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002417 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002418 default: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002419 String8 msg = String8::format("Unknown device version %x for device %s",
2420 deviceVersion, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002421 ALOGE("%s: %s", __FUNCTION__, msg.string());
2422 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
2423 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07002424 }
2425
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002426 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002427}
2428
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002429Status CameraService::isHiddenPhysicalCamera(const String16& cameraId,
2430 /*out*/ bool *isSupported) {
2431 ATRACE_CALL();
2432
2433 const String8 id = String8(cameraId);
2434
2435 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
2436 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(id.string());
2437
2438 return Status::ok();
2439}
2440
Cliff Wud8cae102021-03-11 01:37:42 +08002441Status CameraService::injectCamera(
2442 const String16& packageName, const String16& internalCamId,
2443 const String16& externalCamId,
2444 const sp<ICameraInjectionCallback>& callback,
2445 /*out*/
2446 sp<hardware::camera2::ICameraInjectionSession>* cameraInjectionSession) {
2447 ATRACE_CALL();
2448
2449 if (!checkCallingPermission(sCameraInjectExternalCameraPermission)) {
2450 const int pid = CameraThreadState::getCallingPid();
2451 const int uid = CameraThreadState::getCallingUid();
2452 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
2453 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2454 "Permission Denial: no permission to inject camera");
2455 }
2456
2457 ALOGV(
2458 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
2459 "%s",
2460 __FUNCTION__, String8(packageName).string(),
2461 String8(internalCamId).string(), String8(externalCamId).string());
2462
2463 binder::Status ret = binder::Status::ok();
2464 // TODO: Implement the injection camera function.
2465 // ret = internalInjectCamera(...);
2466 // if(!ret.isOk()) {
2467 // mInjectionStatusListener->notifyInjectionError(...);
2468 // return ret;
2469 // }
2470
2471 mInjectionStatusListener->addListener(callback);
2472 *cameraInjectionSession = new CameraInjectionSession(this);
2473
2474 return ret;
2475}
2476
Ruben Brunkcc776712015-02-17 20:18:47 -08002477void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002478 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002479 for (auto& i : mActiveClientManager.getAll()) {
2480 auto clientSp = i->getValue();
2481 if (clientSp.get() == client) {
2482 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08002483 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07002484 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002485 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08002486}
2487
Ruben Brunkcc776712015-02-17 20:18:47 -08002488bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002489 bool ret = false;
2490 {
2491 // Acquire mServiceLock and prevent other clients from connecting
2492 std::unique_ptr<AutoConditionLock> lock =
2493 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08002494
Igor Murashkin634a5152013-02-20 17:15:11 -08002495
Ruben Brunkcc776712015-02-17 20:18:47 -08002496 std::vector<sp<BasicClient>> evicted;
2497 for (auto& i : mActiveClientManager.getAll()) {
2498 auto clientSp = i->getValue();
2499 if (clientSp.get() == nullptr) {
2500 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2501 mActiveClientManager.remove(i);
2502 continue;
2503 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08002504 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002505 mActiveClientManager.remove(i);
2506 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08002507
Ruben Brunkcc776712015-02-17 20:18:47 -08002508 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002509 clientSp->notifyError(
2510 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002511 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08002512 }
2513 }
2514
Ruben Brunkcc776712015-02-17 20:18:47 -08002515 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2516 // other clients from connecting in mServiceLockWrapper if held
2517 mServiceLock.unlock();
2518
Ruben Brunk36597b22015-03-20 22:15:57 -07002519 // Do not clear caller identity, remote caller should be client proccess
2520
Ruben Brunkcc776712015-02-17 20:18:47 -08002521 for (auto& i : evicted) {
2522 if (i.get() != nullptr) {
2523 i->disconnect();
2524 ret = true;
2525 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002526 }
2527
Ruben Brunkcc776712015-02-17 20:18:47 -08002528 // Reacquire mServiceLock
2529 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08002530
Ruben Brunkcc776712015-02-17 20:18:47 -08002531 } // lock is destroyed, allow further connect calls
2532
2533 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07002534}
2535
Ruben Brunkcc776712015-02-17 20:18:47 -08002536std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
2537 const String8& cameraId) const {
2538 std::shared_ptr<CameraState> state;
2539 {
2540 Mutex::Autolock lock(mCameraStatesLock);
2541 auto iter = mCameraStates.find(cameraId);
2542 if (iter != mCameraStates.end()) {
2543 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002544 }
2545 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002546 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002547}
2548
Ruben Brunkcc776712015-02-17 20:18:47 -08002549sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
2550 // Remove from active clients list
2551 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
2552 if (clientDescriptorPtr == nullptr) {
2553 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
2554 cameraId.string());
2555 return sp<BasicClient>{nullptr};
2556 }
2557
2558 return clientDescriptorPtr->getValue();
Keun young Parkd8973a72012-03-28 14:13:09 -07002559}
2560
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002561void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07002562 // Acquire mServiceLock and prevent other clients from connecting
2563 std::unique_ptr<AutoConditionLock> lock =
2564 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
2565
Ruben Brunk6267b532015-04-30 17:44:07 -07002566 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002567 for (size_t i = 0; i < newUserIds.size(); i++) {
2568 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07002569 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002570 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07002571 return;
2572 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002573 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07002574 }
2575
Ruben Brunka8ca9152015-04-07 14:23:40 -07002576
Ruben Brunk6267b532015-04-30 17:44:07 -07002577 if (newAllowedUsers == mAllowedUsers) {
2578 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
2579 return;
2580 }
2581
2582 logUserSwitch(mAllowedUsers, newAllowedUsers);
2583
2584 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07002585
2586 // Current user has switched, evict all current clients.
2587 std::vector<sp<BasicClient>> evicted;
2588 for (auto& i : mActiveClientManager.getAll()) {
2589 auto clientSp = i->getValue();
2590
2591 if (clientSp.get() == nullptr) {
2592 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2593 continue;
2594 }
2595
Ruben Brunk6267b532015-04-30 17:44:07 -07002596 // Don't evict clients that are still allowed.
2597 uid_t clientUid = clientSp->getClientUid();
2598 userid_t clientUserId = multiuser_get_user_id(clientUid);
2599 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
2600 continue;
2601 }
2602
Ruben Brunk36597b22015-03-20 22:15:57 -07002603 evicted.push_back(clientSp);
2604
2605 String8 curTime = getFormattedCurrentTime();
2606
2607 ALOGE("Evicting conflicting client for camera ID %s due to user change",
2608 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07002609
Ruben Brunk36597b22015-03-20 22:15:57 -07002610 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002611 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00002612 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
2613 " to user switch.", i->getKey().string(),
2614 String8{clientSp->getPackageName()}.string(),
2615 i->getOwnerId(), i->getPriority().getScore(),
2616 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07002617
2618 }
2619
2620 // Do not hold mServiceLock while disconnecting clients, but retain the condition
2621 // blocking other clients from connecting in mServiceLockWrapper if held.
2622 mServiceLock.unlock();
2623
2624 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07002625 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07002626
2627 for (auto& i : evicted) {
2628 i->disconnect();
2629 }
2630
Jayant Chowdhary12361932018-08-27 14:46:13 -07002631 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07002632
2633 // Reacquire mServiceLock
2634 mServiceLock.lock();
2635}
Ruben Brunkcc776712015-02-17 20:18:47 -08002636
Ruben Brunka8ca9152015-04-07 14:23:40 -07002637void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002638 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07002639 Mutex::Autolock l(mLogLock);
Rucha Katakward9ea6452021-05-06 11:57:16 -07002640 String8 msg = String8::format("%s : %s", curTime.string(), event);
2641 // For service error events, print the msg only once.
2642 if(!msg.contains("SERVICE ERROR")) {
2643 mEventLog.add(msg);
2644 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
2645 // Error event not added to the dumpsys log before
2646 mEventLog.add(msg);
2647 sServiceErrorEventSet.insert(msg);
2648 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002649}
2650
Ruben Brunka8ca9152015-04-07 14:23:40 -07002651void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002652 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002653 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002654 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002655 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002656}
2657
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002658void CameraService::logDisconnectedOffline(const char* cameraId, int clientPid,
2659 const char* clientPackage) {
2660 // Log the clients evicted
2661 logEvent(String8::format("DISCONNECT offline device %s client for package %s (PID %d)",
2662 cameraId, clientPackage, clientPid));
2663}
2664
Ruben Brunka8ca9152015-04-07 14:23:40 -07002665void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002666 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002667 // Log the clients evicted
2668 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002669 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002670}
2671
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002672void CameraService::logConnectedOffline(const char* cameraId, int clientPid,
2673 const char* clientPackage) {
2674 // Log the clients evicted
2675 logEvent(String8::format("CONNECT offline device %s client for package %s (PID %d)", cameraId,
2676 clientPackage, clientPid));
2677}
2678
Ruben Brunka8ca9152015-04-07 14:23:40 -07002679void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002680 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002681 // Log the client rejected
2682 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002683 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002684}
2685
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002686void CameraService::logTorchEvent(const char* cameraId, const char *torchState, int clientPid) {
2687 // Log torch event
2688 logEvent(String8::format("Torch for camera id %s turned %s for client PID %d", cameraId,
2689 torchState, clientPid));
2690}
2691
Ruben Brunk6267b532015-04-30 17:44:07 -07002692void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
2693 const std::set<userid_t>& newUserIds) {
2694 String8 newUsers = toString(newUserIds);
2695 String8 oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002696 if (oldUsers.size() == 0) {
2697 oldUsers = "<None>";
2698 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07002699 // Log the new and old users
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002700 logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
Ruben Brunk6267b532015-04-30 17:44:07 -07002701 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002702}
2703
2704void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
2705 // Log the device removal
2706 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
2707}
2708
2709void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
2710 // Log the device removal
2711 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
2712}
2713
2714void CameraService::logClientDied(int clientPid, const char* reason) {
2715 // Log the device removal
2716 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07002717}
2718
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002719void CameraService::logServiceError(const char* msg, int errorCode) {
2720 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002721 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002722}
2723
Ruben Brunk36597b22015-03-20 22:15:57 -07002724status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
2725 uint32_t flags) {
2726
Mathias Agopian65ab4712010-07-14 17:59:35 -07002727 // Permission checks
2728 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002729 case SHELL_COMMAND_TRANSACTION: {
2730 int in = data.readFileDescriptor();
2731 int out = data.readFileDescriptor();
2732 int err = data.readFileDescriptor();
2733 int argc = data.readInt32();
2734 Vector<String16> args;
2735 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
2736 args.add(data.readString16());
2737 }
2738 sp<IBinder> unusedCallback;
2739 sp<IResultReceiver> resultReceiver;
2740 status_t status;
2741 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
2742 return status;
2743 }
2744 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
2745 return status;
2746 }
2747 status = shellCommand(in, out, err, args);
2748 if (resultReceiver != nullptr) {
2749 resultReceiver->send(status);
2750 }
2751 return NO_ERROR;
2752 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002753 }
2754
2755 return BnCameraService::onTransact(code, data, reply, flags);
2756}
2757
Mathias Agopian65ab4712010-07-14 17:59:35 -07002758// We share the media players for shutter and recording sound for all clients.
2759// A reference count is kept to determine when we will actually release the
2760// media players.
2761
Jaekyun Seokef498052018-03-23 13:09:44 +09002762sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
2763 sp<MediaPlayer> mp = new MediaPlayer();
2764 status_t error;
2765 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08002766 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09002767 error = mp->prepare();
2768 }
2769 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00002770 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09002771 mp->disconnect();
2772 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002773 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002774 }
2775 return mp;
2776}
2777
username5755fea2018-12-27 09:48:08 +08002778void CameraService::increaseSoundRef() {
2779 Mutex::Autolock lock(mSoundLock);
2780 mSoundRef++;
2781}
2782
2783void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002784 ATRACE_CALL();
2785
username5755fea2018-12-27 09:48:08 +08002786 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
2787 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
2788 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
2789 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
2790 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
2791 }
2792 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
2793 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
2794 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
2795 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002796 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08002797 }
2798 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
2799 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
2800 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
2801 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
2802 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002803 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002804}
2805
username5755fea2018-12-27 09:48:08 +08002806void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002807 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002808 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002809 if (--mSoundRef) return;
2810
2811 for (int i = 0; i < NUM_SOUNDS; i++) {
2812 if (mSoundPlayer[i] != 0) {
2813 mSoundPlayer[i]->disconnect();
2814 mSoundPlayer[i].clear();
2815 }
2816 }
2817}
2818
2819void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002820 ATRACE_CALL();
2821
Mathias Agopian65ab4712010-07-14 17:59:35 -07002822 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07002823 if (kind < 0 || kind >= NUM_SOUNDS) {
2824 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
2825 return;
2826 }
2827
Mathias Agopian65ab4712010-07-14 17:59:35 -07002828 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002829 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002830 sp<MediaPlayer> player = mSoundPlayer[kind];
2831 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08002832 player->seekTo(0);
2833 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002834 }
2835}
2836
2837// ----------------------------------------------------------------------------
2838
2839CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07002840 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002841 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09002842 const std::optional<String16>& clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002843 const String8& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07002844 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002845 int clientPid, uid_t clientUid,
2846 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002847 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08002848 IInterface::asBinder(cameraClient),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002849 clientPackageName, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07002850 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002851 clientPid, clientUid,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002852 servicePid),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002853 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08002854{
Jayant Chowdhary12361932018-08-27 14:46:13 -07002855 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002856 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002857
Igor Murashkin44cfcf02013-03-01 16:22:28 -08002858 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002859
username5755fea2018-12-27 09:48:08 +08002860 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002861
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002862 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002863}
2864
Mathias Agopian65ab4712010-07-14 17:59:35 -07002865// tear down the client
2866CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002867 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08002868 mDestructionStarted = true;
2869
username5755fea2018-12-27 09:48:08 +08002870 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002871 // unconditionally disconnect. function is idempotent
2872 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002873}
2874
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002875sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
2876
Igor Murashkin634a5152013-02-20 17:15:11 -08002877CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002878 const sp<IBinder>& remoteCallback,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09002879 const String16& clientPackageName, const std::optional<String16>& clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07002880 const String8& cameraIdStr, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002881 int clientPid, uid_t clientUid,
2882 int servicePid):
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002883 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07002884 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09002885 mClientPackageName(clientPackageName), mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002886 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002887 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07002888 mDisconnected(false), mUidIsTrusted(false),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002889 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002890 mRemoteBinder(remoteCallback),
2891 mOpsActive(false),
2892 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08002893{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002894 if (sCameraService == nullptr) {
2895 sCameraService = cameraService;
2896 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08002897
2898 // In some cases the calling code has no access to the package it runs under.
2899 // For example, NDK camera API.
2900 // In this case we will get the packages for the calling UID and pick the first one
2901 // for attributing the app op. This will work correctly for runtime permissions
2902 // as for legacy apps we will toggle the app op for all packages in the UID.
2903 // The caveat is that the operation may be attributed to the wrong package and
2904 // stats based on app ops may be slightly off.
2905 if (mClientPackageName.size() <= 0) {
2906 sp<IServiceManager> sm = defaultServiceManager();
2907 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
2908 if (binder == 0) {
2909 ALOGE("Cannot get permission service");
2910 // Leave mClientPackageName unchanged (empty) and the further interaction
2911 // with camera will fail in BasicClient::startCameraOps
2912 return;
2913 }
2914
2915 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
2916 Vector<String16> packages;
2917
2918 permCtrl->getPackagesForUid(mClientUid, packages);
2919
2920 if (packages.isEmpty()) {
2921 ALOGE("No packages for calling UID");
2922 // Leave mClientPackageName unchanged (empty) and the further interaction
2923 // with camera will fail in BasicClient::startCameraOps
2924 return;
2925 }
2926 mClientPackageName = packages[0];
2927 }
Steven Moreland89a2c5c2020-01-31 15:02:25 -08002928 if (getCurrentServingCall() != BinderCallType::HWBINDER) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002929 mAppOpsManager = std::make_unique<AppOpsManager>();
2930 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07002931
2932 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08002933}
2934
2935CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002936 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08002937 mDestructionStarted = true;
2938}
2939
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002940binder::Status CameraService::BasicClient::disconnect() {
2941 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002942 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002943 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07002944 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07002945 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002946
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002947 sCameraService->removeByClient(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002948 sCameraService->logDisconnected(mCameraIdStr, mClientPid, String8(mClientPackageName));
Peter Kalauskasa29c1352018-10-10 12:05:42 -07002949 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
2950 mCameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002951
2952 sp<IBinder> remote = getRemote();
2953 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002954 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08002955 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002956
2957 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07002958 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002959 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
2960 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
2961 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002962
Igor Murashkincba2c162013-03-20 15:56:31 -07002963 // client shouldn't be able to call into us anymore
2964 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002965
2966 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08002967}
2968
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002969status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
2970 // No dumping of clients directly over Binder,
2971 // must go through CameraService::dump
2972 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07002973 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002974 return OK;
2975}
2976
Ruben Brunkcc776712015-02-17 20:18:47 -08002977String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002978 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08002979}
2980
Emilian Peev8b64f282021-03-25 16:49:57 -07002981int CameraService::BasicClient::getCameraFacing() const {
2982 return mCameraFacing;
2983}
2984
2985int CameraService::BasicClient::getCameraOrientation() const {
2986 return mOrientation;
2987}
Ruben Brunkcc776712015-02-17 20:18:47 -08002988
2989int CameraService::BasicClient::getClientPid() const {
2990 return mClientPid;
2991}
2992
Ruben Brunk6267b532015-04-30 17:44:07 -07002993uid_t CameraService::BasicClient::getClientUid() const {
2994 return mClientUid;
2995}
2996
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002997bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
2998 // Defaults to API2.
2999 return level == API_2;
3000}
3001
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07003002status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003003 {
3004 Mutex::Autolock l(mAudioRestrictionLock);
3005 mAudioRestriction = mode;
3006 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07003007 sCameraService->updateAudioRestriction();
3008 return OK;
3009}
3010
3011int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003012 return sCameraService->updateAudioRestriction();
3013}
3014
3015int32_t CameraService::BasicClient::getAudioRestriction() const {
3016 Mutex::Autolock l(mAudioRestrictionLock);
3017 return mAudioRestriction;
3018}
3019
3020bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
3021 switch (mode) {
3022 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
3023 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
3024 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
3025 return true;
3026 default:
3027 return false;
3028 }
3029}
3030
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003031status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
3032 if (mode == AppOpsManager::MODE_ERRORED) {
3033 ALOGI("Camera %s: Access for \"%s\" has been revoked",
3034 mCameraIdStr.string(), String8(mClientPackageName).string());
3035 return PERMISSION_DENIED;
3036 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
3037 // If the calling Uid is trusted (a native service), the AppOpsManager could
3038 // return MODE_IGNORED. Do not treat such case as error.
3039 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
3040 mClientPackageName);
3041 bool isCameraPrivacyEnabled =
3042 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled(
3043 multiuser_get_user_id(mClientUid));
3044 if (!isUidActive || !isCameraPrivacyEnabled) {
3045 ALOGI("Camera %s: Access for \"%s\" has been restricted",
3046 mCameraIdStr.string(), String8(mClientPackageName).string());
3047 // Return the same error as for device policy manager rejection
3048 return -EACCES;
3049 }
3050 }
3051 return OK;
3052}
3053
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003054status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003055 ATRACE_CALL();
3056
Igor Murashkine6800ce2013-03-04 17:25:57 -08003057 {
3058 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003059 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08003060 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003061 if (mAppOpsManager != nullptr) {
3062 // Notify app ops that the camera is not available
3063 mOpsCallback = new OpsCallback(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003064 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
3065 mClientPackageName, mOpsCallback);
Igor Murashkine6800ce2013-03-04 17:25:57 -08003066
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003067 // Just check for camera acccess here on open - delay startOp until
3068 // camera frames start streaming in startCameraStreamingOps
3069 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
3070 mClientPackageName);
3071 status_t res = handleAppOpMode(mode);
3072 if (res != OK) {
3073 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003074 }
Svetoslav28e8ef72015-05-11 19:21:31 -07003075 }
3076
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003077 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003078
3079 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003080 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003081
Emilian Peev53722fa2019-02-22 17:47:20 -08003082 sCameraService->mUidPolicy->registerMonitorUid(mClientUid);
3083
Shuzhen Wang695044d2020-03-06 09:02:23 -08003084 // Notify listeners of camera open/close status
3085 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
3086
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003087 return OK;
3088}
3089
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003090status_t CameraService::BasicClient::startCameraStreamingOps() {
3091 ATRACE_CALL();
3092
3093 if (!mOpsActive) {
3094 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
3095 return INVALID_OPERATION;
3096 }
3097 if (mOpsStreaming) {
3098 ALOGV("%s: Streaming already active!", __FUNCTION__);
3099 return OK;
3100 }
3101
3102 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
3103 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
3104
3105 if (mAppOpsManager != nullptr) {
3106 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
3107 mClientPackageName, /*startIfModeDefault*/ false, mClientFeatureId,
3108 String16("start camera ") + String16(mCameraIdStr));
3109 status_t res = handleAppOpMode(mode);
3110 if (res != OK) {
3111 return res;
3112 }
3113 }
3114
3115 mOpsStreaming = true;
3116
3117 return OK;
3118}
3119
3120status_t CameraService::BasicClient::finishCameraStreamingOps() {
3121 ATRACE_CALL();
3122
3123 if (!mOpsActive) {
3124 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
3125 return INVALID_OPERATION;
3126 }
3127 if (!mOpsStreaming) {
3128 ALOGV("%s: Streaming not active!", __FUNCTION__);
3129 return OK;
3130 }
3131
3132 if (mAppOpsManager != nullptr) {
3133 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
3134 mClientPackageName, mClientFeatureId);
3135 mOpsStreaming = false;
3136 }
3137
3138 return OK;
3139}
3140
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003141status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003142 ATRACE_CALL();
3143
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003144 if (mOpsStreaming) {
3145 // Make sure we've notified everyone about camera stopping
3146 finishCameraStreamingOps();
3147 }
3148
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003149 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003150 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003151 mOpsActive = false;
3152
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01003153 // This function is called when a client disconnects. This should
3154 // release the camera, but actually only if it was in a proper
3155 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003156 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01003157 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003158
Ruben Brunkcc776712015-02-17 20:18:47 -08003159 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003160 sCameraService->updateStatus(StatusInternal::PRESENT,
3161 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003162 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003163 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003164 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
3165 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08003166 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003167 mOpsCallback.clear();
3168
Emilian Peev53722fa2019-02-22 17:47:20 -08003169 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid);
3170
Shuzhen Wang695044d2020-03-06 09:02:23 -08003171 // Notify listeners of camera open/close status
3172 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
3173
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003174 return OK;
3175}
3176
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003177void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003178 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003179 if (mAppOpsManager == nullptr) {
3180 return;
3181 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003182 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003183 if (op != AppOpsManager::OP_CAMERA) {
3184 ALOGW("Unexpected app ops notification received: %d", op);
3185 return;
3186 }
3187
3188 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003189 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003190 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003191 ALOGV("checkOp returns: %d, %s ", res,
3192 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
3193 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
3194 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
3195 "UNKNOWN");
3196
Shuzhen Wang64900852021-02-05 09:03:29 -08003197 if (res == AppOpsManager::MODE_ERRORED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003198 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003199 String8(mClientPackageName).string());
Svet Ganova453d0d2018-01-11 15:37:58 -08003200 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08003201 } else if (res == AppOpsManager::MODE_IGNORED) {
3202 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Evan Severson09ab4002021-02-10 14:15:19 -08003203 bool isCameraPrivacyEnabled =
3204 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled(
3205 multiuser_get_user_id(mClientUid));
Shuzhen Wang64900852021-02-05 09:03:29 -08003206 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d",
3207 mCameraIdStr.string(), String8(mClientPackageName).string(),
3208 mUidIsTrusted, isUidActive);
3209 // If the calling Uid is trusted (a native service), or the client Uid is active (WAR for
3210 // b/175320666), the AppOpsManager could return MODE_IGNORED. Do not treat such cases as
3211 // error.
Evan Severson09ab4002021-02-10 14:15:19 -08003212 if (!mUidIsTrusted && isUidActive && isCameraPrivacyEnabled) {
3213 setCameraMute(true);
3214 } else if (!mUidIsTrusted && !isUidActive) {
Shuzhen Wang64900852021-02-05 09:03:29 -08003215 block();
3216 }
Evan Severson09ab4002021-02-10 14:15:19 -08003217 } else if (res == AppOpsManager::MODE_ALLOWED) {
3218 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003219 }
3220}
3221
Svet Ganova453d0d2018-01-11 15:37:58 -08003222void CameraService::BasicClient::block() {
3223 ATRACE_CALL();
3224
3225 // Reset the client PID to allow server-initiated disconnect,
3226 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003227 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08003228 CaptureResultExtras resultExtras; // a dummy result (invalid)
3229 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
3230 disconnect();
3231}
3232
Mathias Agopian65ab4712010-07-14 17:59:35 -07003233// ----------------------------------------------------------------------------
3234
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003235void CameraService::Client::notifyError(int32_t errorCode,
Jianing Weicb0652e2014-03-12 18:29:36 -07003236 const CaptureResultExtras& resultExtras) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08003237 (void) resultExtras;
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003238 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07003239 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
3240 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
3241 api1ErrorCode = CAMERA_ERROR_DISABLED;
3242 }
3243 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003244 } else {
3245 ALOGE("mRemoteCallback is NULL!!");
3246 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003247}
3248
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003249// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003250binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003251 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003252 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08003253}
3254
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003255bool CameraService::Client::canCastToApiClient(apiLevel level) const {
3256 return level == API_1;
3257}
3258
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003259CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
3260 mClient(client) {
3261}
3262
3263void CameraService::Client::OpsCallback::opChanged(int32_t op,
3264 const String16& packageName) {
3265 sp<BasicClient> client = mClient.promote();
3266 if (client != NULL) {
3267 client->opChanged(op, packageName);
3268 }
3269}
3270
Mathias Agopian65ab4712010-07-14 17:59:35 -07003271// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08003272// UidPolicy
3273// ----------------------------------------------------------------------------
3274
3275void CameraService::UidPolicy::registerSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003276 Mutex::Autolock _l(mUidLock);
3277
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003278 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07003279 status_t res = mAm.linkToDeath(this);
3280 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08003281 | ActivityManager::UID_OBSERVER_IDLE
Emilian Peev53722fa2019-02-22 17:47:20 -08003282 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganova453d0d2018-01-11 15:37:58 -08003283 ActivityManager::PROCESS_STATE_UNKNOWN,
3284 String16("cameraserver"));
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003285 if (res == OK) {
3286 mRegistered = true;
3287 ALOGV("UidPolicy: Registered with ActivityManager");
3288 }
Svet Ganova453d0d2018-01-11 15:37:58 -08003289}
3290
3291void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003292 Mutex::Autolock _l(mUidLock);
3293
Steven Moreland2f348142019-07-02 15:59:07 -07003294 mAm.unregisterUidObserver(this);
3295 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003296 mRegistered = false;
3297 mActiveUids.clear();
3298 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08003299}
3300
3301void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
3302 onUidIdle(uid, disabled);
3303}
3304
3305void CameraService::UidPolicy::onUidActive(uid_t uid) {
3306 Mutex::Autolock _l(mUidLock);
3307 mActiveUids.insert(uid);
3308}
3309
3310void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
3311 bool deleted = false;
3312 {
3313 Mutex::Autolock _l(mUidLock);
3314 if (mActiveUids.erase(uid) > 0) {
3315 deleted = true;
3316 }
3317 }
3318 if (deleted) {
3319 sp<CameraService> service = mService.promote();
3320 if (service != nullptr) {
3321 service->blockClientsForUid(uid);
3322 }
3323 }
3324}
3325
Emilian Peev53722fa2019-02-22 17:47:20 -08003326void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07003327 int64_t procStateSeq __unused, int32_t capability __unused) {
Emilian Peev53722fa2019-02-22 17:47:20 -08003328 bool procStateChange = false;
3329 {
3330 Mutex::Autolock _l(mUidLock);
3331 if ((mMonitoredUids.find(uid) != mMonitoredUids.end()) &&
3332 (mMonitoredUids[uid].first != procState)) {
3333 mMonitoredUids[uid].first = procState;
3334 procStateChange = true;
3335 }
3336 }
3337
3338 if (procStateChange) {
3339 sp<CameraService> service = mService.promote();
3340 if (service != nullptr) {
3341 service->notifyMonitoredUids();
3342 }
3343 }
3344}
3345
3346void CameraService::UidPolicy::registerMonitorUid(uid_t uid) {
3347 Mutex::Autolock _l(mUidLock);
3348 auto it = mMonitoredUids.find(uid);
3349 if (it != mMonitoredUids.end()) {
3350 it->second.second++;
3351 } else {
3352 mMonitoredUids.emplace(
3353 std::pair<uid_t, std::pair<int32_t, size_t>> (uid,
3354 std::pair<int32_t, size_t> (ActivityManager::PROCESS_STATE_NONEXISTENT, 1)));
3355 }
3356}
3357
3358void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid) {
3359 Mutex::Autolock _l(mUidLock);
3360 auto it = mMonitoredUids.find(uid);
3361 if (it != mMonitoredUids.end()) {
3362 it->second.second--;
3363 if (it->second.second == 0) {
3364 mMonitoredUids.erase(it);
3365 }
3366 } else {
3367 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
3368 }
3369}
3370
Svet Ganov7b4ab782018-03-25 12:48:10 -07003371bool CameraService::UidPolicy::isUidActive(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003372 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003373 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003374}
3375
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003376static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
3377static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003378
Svet Ganov7b4ab782018-03-25 12:48:10 -07003379bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003380 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003381 // If activity manager is unreachable, assume everything is active
3382 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003383 return true;
3384 }
3385 auto it = mOverrideUids.find(uid);
3386 if (it != mOverrideUids.end()) {
3387 return it->second;
3388 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003389 bool active = mActiveUids.find(uid) != mActiveUids.end();
3390 if (!active) {
3391 // We want active UIDs to always access camera with their first attempt since
3392 // there is no guarantee the app is robustly written and would retry getting
3393 // the camera on failure. The inverse case is not a problem as we would take
3394 // camera away soon once we get the callback that the uid is no longer active.
3395 ActivityManager am;
3396 // Okay to access with a lock held as UID changes are dispatched without
3397 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07003398 int64_t startTimeMillis = 0;
3399 do {
3400 // TODO: Fix this b/109950150!
3401 // Okay this is a hack. There is a race between the UID turning active and
3402 // activity being resumed. The proper fix is very risky, so we temporary add
3403 // some polling which should happen pretty rarely anyway as the race is hard
3404 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003405 active = mActiveUids.find(uid) != mActiveUids.end();
Hui Yu12c7ec72020-05-04 17:40:52 +00003406 if (!active) active = am.isUidActive(uid, callingPackage);
Svet Ganov94ec46f2018-06-08 15:03:46 -07003407 if (active) {
3408 break;
3409 }
3410 if (startTimeMillis <= 0) {
3411 startTimeMillis = uptimeMillis();
3412 }
3413 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003414 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003415 if (remainingTimeMillis <= 0) {
3416 break;
3417 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003418 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
3419
3420 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003421 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003422 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003423 } while (true);
3424
Svet Ganov7b4ab782018-03-25 12:48:10 -07003425 if (active) {
3426 // Now that we found out the UID is actually active, cache that
3427 mActiveUids.insert(uid);
3428 }
3429 }
3430 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08003431}
3432
Varun Shahb42f1eb2019-04-16 14:45:13 -07003433int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
3434 Mutex::Autolock _l(mUidLock);
3435 return getProcStateLocked(uid);
3436}
3437
3438int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
3439 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
3440 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
3441 procState = mMonitoredUids[uid].first;
3442 }
3443 return procState;
3444}
3445
Svet Ganov7b4ab782018-03-25 12:48:10 -07003446void CameraService::UidPolicy::UidPolicy::addOverrideUid(uid_t uid,
3447 String16 callingPackage, bool active) {
3448 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08003449}
3450
Svet Ganov7b4ab782018-03-25 12:48:10 -07003451void CameraService::UidPolicy::removeOverrideUid(uid_t uid, String16 callingPackage) {
3452 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08003453}
3454
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003455void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
3456 Mutex::Autolock _l(mUidLock);
3457 ALOGV("UidPolicy: ActivityManager has died");
3458 mRegistered = false;
3459 mActiveUids.clear();
3460}
3461
Svet Ganov7b4ab782018-03-25 12:48:10 -07003462void CameraService::UidPolicy::updateOverrideUid(uid_t uid, String16 callingPackage,
3463 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003464 bool wasActive = false;
3465 bool isActive = false;
3466 {
3467 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003468 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003469 mOverrideUids.erase(uid);
3470 if (insert) {
3471 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
3472 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003473 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003474 }
3475 if (wasActive != isActive && !isActive) {
3476 sp<CameraService> service = mService.promote();
3477 if (service != nullptr) {
3478 service->blockClientsForUid(uid);
3479 }
3480 }
3481}
3482
3483// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08003484// SensorPrivacyPolicy
3485// ----------------------------------------------------------------------------
3486void CameraService::SensorPrivacyPolicy::registerSelf() {
3487 Mutex::Autolock _l(mSensorPrivacyLock);
3488 if (mRegistered) {
3489 return;
3490 }
Evan Severson09ab4002021-02-10 14:15:19 -08003491 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08003492 mSpm.addSensorPrivacyListener(this);
3493 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
3494 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003495 if (res == OK) {
3496 mRegistered = true;
3497 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
3498 }
3499}
3500
3501void CameraService::SensorPrivacyPolicy::unregisterSelf() {
3502 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08003503 mSpm.removeSensorPrivacyListener(this);
3504 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003505 mRegistered = false;
3506 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
3507}
3508
3509bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
3510 Mutex::Autolock _l(mSensorPrivacyLock);
3511 return mSensorPrivacyEnabled;
3512}
3513
Evan Severson09ab4002021-02-10 14:15:19 -08003514bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled(userid_t userId) {
3515 if (!hasCameraPrivacyFeature()) {
3516 return false;
3517 }
3518 return mSpm.isIndividualSensorPrivacyEnabled(userId,
3519 SensorPrivacyManager::INDIVIDUAL_SENSOR_CAMERA);
3520}
3521
Michael Grooverd1d435a2018-12-18 17:39:42 -08003522binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
3523 {
3524 Mutex::Autolock _l(mSensorPrivacyLock);
3525 mSensorPrivacyEnabled = enabled;
3526 }
3527 // if sensor privacy is enabled then block all clients from accessing the camera
Evan Severson09ab4002021-02-10 14:15:19 -08003528 if (enabled) {
3529 sp<CameraService> service = mService.promote();
3530 if (service != nullptr) {
3531 service->blockAllClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08003532 }
3533 }
3534 return binder::Status::ok();
3535}
3536
3537void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
3538 Mutex::Autolock _l(mSensorPrivacyLock);
3539 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
3540 mRegistered = false;
3541}
3542
Evan Severson09ab4002021-02-10 14:15:19 -08003543bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Severson671806e2021-04-20 16:44:53 -07003544 return mSpm.supportsSensorToggle(SensorPrivacyManager::INDIVIDUAL_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08003545}
3546
Michael Grooverd1d435a2018-12-18 17:39:42 -08003547// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003548// CameraState
3549// ----------------------------------------------------------------------------
3550
3551CameraService::CameraState::CameraState(const String8& id, int cost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003552 const std::set<String8>& conflicting, SystemCameraKind systemCameraKind) : mId(id),
3553 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
3554 mSystemCameraKind(systemCameraKind) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08003555
3556CameraService::CameraState::~CameraState() {}
3557
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003558CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003559 Mutex::Autolock lock(mStatusLock);
3560 return mStatus;
3561}
3562
Shuzhen Wang43858162020-01-10 13:42:15 -08003563std::vector<String8> CameraService::CameraState::getUnavailablePhysicalIds() const {
3564 Mutex::Autolock lock(mStatusLock);
3565 std::vector<String8> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
3566 return res;
3567}
3568
Ruben Brunkcc776712015-02-17 20:18:47 -08003569CameraParameters CameraService::CameraState::getShimParams() const {
3570 return mShimParams;
3571}
3572
3573void CameraService::CameraState::setShimParams(const CameraParameters& params) {
3574 mShimParams = params;
3575}
3576
3577int CameraService::CameraState::getCost() const {
3578 return mCost;
3579}
3580
3581std::set<String8> CameraService::CameraState::getConflicting() const {
3582 return mConflicting;
3583}
3584
3585String8 CameraService::CameraState::getId() const {
3586 return mId;
3587}
3588
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003589SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
3590 return mSystemCameraKind;
3591}
3592
Shuzhen Wang43858162020-01-10 13:42:15 -08003593bool CameraService::CameraState::addUnavailablePhysicalId(const String8& physicalId) {
3594 Mutex::Autolock lock(mStatusLock);
3595 auto result = mUnavailablePhysicalIds.insert(physicalId);
3596 return result.second;
3597}
3598
3599bool CameraService::CameraState::removeUnavailablePhysicalId(const String8& physicalId) {
3600 Mutex::Autolock lock(mStatusLock);
3601 auto count = mUnavailablePhysicalIds.erase(physicalId);
3602 return count > 0;
3603}
3604
Ruben Brunkcc776712015-02-17 20:18:47 -08003605// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07003606// ClientEventListener
3607// ----------------------------------------------------------------------------
3608
3609void CameraService::ClientEventListener::onClientAdded(
3610 const resource_policy::ClientDescriptor<String8,
3611 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003612 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003613 if (basicClient.get() != nullptr) {
3614 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3615 notifier.noteStartCamera(descriptor.getKey(),
3616 static_cast<int>(basicClient->getClientUid()));
3617 }
3618}
3619
3620void CameraService::ClientEventListener::onClientRemoved(
3621 const resource_policy::ClientDescriptor<String8,
3622 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003623 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003624 if (basicClient.get() != nullptr) {
3625 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3626 notifier.noteStopCamera(descriptor.getKey(),
3627 static_cast<int>(basicClient->getClientUid()));
3628 }
3629}
3630
3631
3632// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003633// CameraClientManager
3634// ----------------------------------------------------------------------------
3635
Ruben Brunk99e69712015-05-26 17:25:07 -07003636CameraService::CameraClientManager::CameraClientManager() {
3637 setListener(std::make_shared<ClientEventListener>());
3638}
3639
Ruben Brunkcc776712015-02-17 20:18:47 -08003640CameraService::CameraClientManager::~CameraClientManager() {}
3641
3642sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
3643 const String8& id) const {
3644 auto descriptor = get(id);
3645 if (descriptor == nullptr) {
3646 return sp<BasicClient>{nullptr};
3647 }
3648 return descriptor->getValue();
3649}
3650
3651String8 CameraService::CameraClientManager::toString() const {
3652 auto all = getAll();
3653 String8 ret("[");
3654 bool hasAny = false;
3655 for (auto& i : all) {
3656 hasAny = true;
3657 String8 key = i->getKey();
3658 int32_t cost = i->getCost();
3659 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00003660 int32_t score = i->getPriority().getScore();
3661 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08003662 auto conflicting = i->getConflicting();
3663 auto clientSp = i->getValue();
3664 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07003665 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08003666 if (clientSp.get() != nullptr) {
3667 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07003668 uid_t clientUid = clientSp->getClientUid();
3669 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003670 }
Emilian Peev8131a262017-02-01 12:33:43 +00003671 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
3672 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08003673
Ruben Brunk6267b532015-04-30 17:44:07 -07003674 if (clientSp.get() != nullptr) {
3675 ret.appendFormat("User Id: %d, ", clientUserId);
3676 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003677 if (packageName.size() != 0) {
3678 ret.appendFormat("Client Package Name: %s", packageName.string());
3679 }
3680
3681 ret.append(", Conflicting Client Devices: {");
3682 for (auto& j : conflicting) {
3683 ret.appendFormat("%s, ", j.string());
3684 }
3685 ret.append("})");
3686 }
3687 if (hasAny) ret.append("\n");
3688 ret.append("]\n");
3689 return ret;
3690}
3691
3692CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3693 const String8& key, const sp<BasicClient>& value, int32_t cost,
Emilian Peev8131a262017-02-01 12:33:43 +00003694 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00003695 int32_t state, int32_t oomScoreOffset) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003696
Steven Moreland89a2c5c2020-01-31 15:02:25 -08003697 bool isVendorClient = getCurrentServingCall() == BinderCallType::HWBINDER;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003698 int32_t score_adj = isVendorClient ? kVendorClientScore : score;
3699 int32_t state_adj = isVendorClient ? kVendorClientState: state;
3700
Ruben Brunkcc776712015-02-17 20:18:47 -08003701 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00003702 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj, isVendorClient,
3703 oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08003704}
3705
3706CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00003707 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
3708 int32_t oomScoreOffset) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003709 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00003710 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00003711 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08003712}
3713
3714// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08003715// InjectionStatusListener
3716// ----------------------------------------------------------------------------
3717
3718void CameraService::InjectionStatusListener::addListener(
3719 const sp<ICameraInjectionCallback>& callback) {
3720 Mutex::Autolock lock(mListenerLock);
3721 if (mCameraInjectionCallback) return;
3722 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
3723 if (res == OK) {
3724 mCameraInjectionCallback = callback;
3725 }
3726}
3727
3728void CameraService::InjectionStatusListener::removeListener() {
3729 Mutex::Autolock lock(mListenerLock);
3730 if (mCameraInjectionCallback == nullptr) {
3731 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
3732 return;
3733 }
3734 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
3735 mCameraInjectionCallback = nullptr;
3736}
3737
3738void CameraService::InjectionStatusListener::notifyInjectionError(
3739 int errorCode) {
3740 Mutex::Autolock lock(mListenerLock);
3741 if (mCameraInjectionCallback == nullptr) {
3742 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
3743 return;
3744 }
3745 mCameraInjectionCallback->onInjectionError(errorCode);
3746}
3747
3748void CameraService::InjectionStatusListener::binderDied(
3749 const wp<IBinder>& /*who*/) {
3750 Mutex::Autolock lock(mListenerLock);
3751 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
3752 auto parent = mParent.promote();
3753 if (parent != nullptr) {
3754 parent->stopInjectionImpl();
3755 }
3756}
3757
3758// ----------------------------------------------------------------------------
3759// CameraInjectionSession
3760// ----------------------------------------------------------------------------
3761
3762binder::Status CameraService::CameraInjectionSession::stopInjection() {
3763 Mutex::Autolock lock(mInjectionSessionLock);
3764 auto parent = mParent.promote();
3765 if (parent == nullptr) {
3766 ALOGE("CameraInjectionSession: Parent is gone");
3767 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
3768 "Camera service encountered error");
3769 }
3770 parent->stopInjectionImpl();
3771 return binder::Status::ok();
3772}
3773
3774// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07003775
3776static const int kDumpLockRetries = 50;
3777static const int kDumpLockSleep = 60000;
3778
3779static bool tryLock(Mutex& mutex)
3780{
3781 bool locked = false;
3782 for (int i = 0; i < kDumpLockRetries; ++i) {
3783 if (mutex.tryLock() == NO_ERROR) {
3784 locked = true;
3785 break;
3786 }
3787 usleep(kDumpLockSleep);
3788 }
3789 return locked;
3790}
3791
3792status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003793 ATRACE_CALL();
3794
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003795 if (checkCallingPermission(sDumpPermission) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003796 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07003797 CameraThreadState::getCallingPid(),
3798 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003799 return NO_ERROR;
3800 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003801 bool locked = tryLock(mServiceLock);
3802 // failed to lock - CameraService is probably deadlocked
3803 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003804 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003805 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003806
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003807 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003808 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07003809
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003810 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003811 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08003812
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003813 if (locked) mServiceLock.unlock();
3814 return NO_ERROR;
3815 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003816 dprintf(fd, "\n== Service global info: ==\n\n");
3817 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003818 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07003819 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
3820 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003821 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
3822 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
3823 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003824 String8 activeClientString = mActiveClientManager.toString();
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003825 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
3826 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003827
3828 dumpEventLog(fd);
3829
3830 bool stateLocked = tryLock(mCameraStatesLock);
3831 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003832 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003833 }
3834
Emilian Peevbd8c5032018-02-14 23:05:40 +00003835 int argSize = args.size();
3836 for (int i = 0; i < argSize; i++) {
3837 if (args[i] == TagMonitor::kMonitorOption) {
3838 if (i + 1 < argSize) {
3839 mMonitorTags = String8(args[i + 1]);
3840 }
3841 break;
3842 }
3843 }
3844
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003845 for (auto& state : mCameraStates) {
3846 String8 cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003847
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003848 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003849
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003850 CameraParameters p = state.second->getShimParams();
3851 if (!p.isEmpty()) {
3852 dprintf(fd, " Camera1 API shim is using parameters:\n ");
3853 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003854 }
3855
3856 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08003857 if (clientDescriptor != nullptr) {
3858 dprintf(fd, " Device %s is open. Client instance dump:\n",
3859 cameraId.string());
3860 dprintf(fd, " Client priority score: %d state: %d\n",
3861 clientDescriptor->getPriority().getScore(),
3862 clientDescriptor->getPriority().getState());
3863 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
3864
3865 auto client = clientDescriptor->getValue();
3866 dprintf(fd, " Client package: %s\n",
3867 String8(client->getPackageName()).string());
3868
3869 client->dumpClient(fd, args);
3870 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003871 dprintf(fd, " Device %s is closed, no client instance\n",
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003872 cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003873 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003874
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003875 }
3876
3877 if (stateLocked) mCameraStatesLock.unlock();
3878
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003879 if (locked) mServiceLock.unlock();
3880
Emilian Peevf53f66e2017-04-11 14:29:43 +01003881 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003882
3883 dprintf(fd, "\n== Vendor tags: ==\n\n");
3884
3885 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
3886 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00003887 sp<VendorTagDescriptorCache> cache =
3888 VendorTagDescriptorCache::getGlobalVendorTagCache();
3889 if (cache == NULL) {
3890 dprintf(fd, "No vendor tags.\n");
3891 } else {
3892 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
3893 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003894 } else {
3895 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
3896 }
3897
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003898 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003899 dprintf(fd, "\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003900 camera3::CameraTraces::dump(fd, args);
3901
3902 // Process dump arguments, if any
3903 int n = args.size();
3904 String16 verboseOption("-v");
3905 String16 unreachableOption("--unreachable");
3906 for (int i = 0; i < n; i++) {
3907 if (args[i] == verboseOption) {
3908 // change logging level
3909 if (i + 1 >= n) continue;
3910 String8 levelStr(args[i+1]);
3911 int level = atoi(levelStr.string());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003912 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003913 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003914 } else if (args[i] == unreachableOption) {
3915 // Dump memory analysis
3916 // TODO - should limit be an argument parameter?
3917 UnreachableMemoryInfo info;
3918 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
3919 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003920 dprintf(fd, "\n== Unable to dump unreachable memory. "
3921 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003922 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003923 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003924 std::string s = info.ToString(/*log_contents*/ true);
3925 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003926 }
3927 }
3928 }
3929 return NO_ERROR;
3930}
3931
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003932void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003933 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003934
3935 Mutex::Autolock l(mLogLock);
3936 for (const auto& msg : mEventLog) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003937 dprintf(fd, " %s\n", msg.string());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003938 }
3939
3940 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003941 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003942 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003943 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003944 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003945 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003946}
3947
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003948void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003949 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003950 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
3951 if (mTorchClientMap[i] == who) {
3952 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003953 String8 cameraId = mTorchClientMap.keyAt(i);
3954 status_t res = mFlashlight->setTorchMode(cameraId, false);
3955 if (res) {
3956 ALOGE("%s: torch client died but couldn't turn off torch: "
3957 "%s (%d)", __FUNCTION__, strerror(-res), res);
3958 return;
3959 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003960 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003961 break;
3962 }
3963 }
3964}
3965
Ruben Brunkcc776712015-02-17 20:18:47 -08003966/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003967
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003968 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07003969 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
3970 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003971 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003972 // PID here is approximate and can be wrong.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003973 logClientDied(CameraThreadState::getCallingPid(), String8("Binder died unexpectedly"));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003974
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003975 // check torch client
3976 handleTorchClientBinderDied(who);
3977
3978 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08003979 if(!evictClientIdByRemote(who)) {
3980 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003981 return;
3982 }
3983
Ruben Brunkcc776712015-02-17 20:18:47 -08003984 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
3985 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003986}
3987
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003988void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003989 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08003990}
3991
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003992void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
3993 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003994 // Do not lock mServiceLock here or can get into a deadlock from
3995 // connect() -> disconnect -> updateStatus
3996
3997 auto state = getCameraState(cameraId);
3998
3999 if (state == nullptr) {
4000 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
4001 cameraId.string());
4002 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07004003 }
4004
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004005 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
4006 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
4007 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
4008 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
4009 return;
4010 }
Jayant Chowdhary90e63692019-10-25 14:13:01 -07004011 bool supportsHAL3 = false;
4012 // supportsCameraApi also holds mInterfaceMutex, we can't call it in the
4013 // HIDL onStatusChanged wrapper call (we'll hold mStatusListenerLock and
4014 // mInterfaceMutex together, which can lead to deadlocks)
4015 binder::Status sRet =
4016 supportsCameraApi(String16(cameraId), hardware::ICameraService::API_VERSION_2,
4017 &supportsHAL3);
4018 if (!sRet.isOk()) {
4019 ALOGW("%s: Failed to determine if device supports HAL3 %s, supportsCameraApi call failed",
4020 __FUNCTION__, cameraId.string());
4021 return;
4022 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004023
4024 // Collect the logical cameras without holding mStatusLock in updateStatus
4025 // as that can lead to a deadlock(b/162192331).
4026 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08004027 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08004028 // of the listeners with both the mStatusLock and mStatusListenerLock held
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004029 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind, &supportsHAL3,
4030 &logicalCameraIds]
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004031 (const String8& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004032
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004033 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004034 // Update torch status if it has a flash unit.
4035 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004036 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004037 if (getTorchStatusLocked(cameraId, &torchStatus) !=
4038 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004039 TorchModeStatus newTorchStatus =
4040 status == StatusInternal::PRESENT ?
4041 TorchModeStatus::AVAILABLE_OFF :
4042 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004043 if (torchStatus != newTorchStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07004044 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004045 }
4046 }
Ruben Brunkcc776712015-02-17 20:18:47 -08004047 }
4048
4049 Mutex::Autolock lock(mStatusListenerLock);
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004050 notifyPhysicalCameraStatusLocked(mapToInterface(status), String16(cameraId),
4051 logicalCameraIds, deviceKind);
Shuzhen Wang43858162020-01-10 13:42:15 -08004052
Ruben Brunkcc776712015-02-17 20:18:47 -08004053 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07004054 bool isVendorListener = listener->isVendorListener();
4055 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
4056 listener->getListenerPid(), listener->getListenerUid()) ||
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07004057 (isVendorListener && !supportsHAL3)) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07004058 ALOGV("Skipping discovery callback for system-only camera/HAL1 device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07004059 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08004060 continue;
4061 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07004062 listener->getListener()->onStatusChanged(mapToInterface(status),
Emilian Peev53722fa2019-02-22 17:47:20 -08004063 String16(cameraId));
Ruben Brunkcc776712015-02-17 20:18:47 -08004064 }
4065 });
Igor Murashkincba2c162013-03-20 15:56:31 -07004066}
4067
Shuzhen Wang695044d2020-03-06 09:02:23 -08004068void CameraService::updateOpenCloseStatus(const String8& cameraId, bool open,
4069 const String16& clientPackageName) {
4070 Mutex::Autolock lock(mStatusListenerLock);
4071
4072 for (const auto& it : mListenerList) {
4073 if (!it->isOpenCloseCallbackAllowed()) {
4074 continue;
4075 }
4076
4077 binder::Status ret;
4078 String16 cameraId64(cameraId);
4079 if (open) {
4080 ret = it->getListener()->onCameraOpened(cameraId64, clientPackageName);
4081 } else {
4082 ret = it->getListener()->onCameraClosed(cameraId64);
4083 }
4084 if (!ret.isOk()) {
4085 ALOGE("%s: Failed to trigger onCameraOpened/onCameraClosed callback: %d", __FUNCTION__,
4086 ret.exceptionCode());
4087 }
4088 }
4089}
4090
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004091template<class Func>
4092void CameraService::CameraState::updateStatus(StatusInternal status,
4093 const String8& cameraId,
4094 std::initializer_list<StatusInternal> rejectSourceStates,
4095 Func onStatusUpdatedLocked) {
4096 Mutex::Autolock lock(mStatusLock);
4097 StatusInternal oldStatus = mStatus;
4098 mStatus = status;
4099
4100 if (oldStatus == status) {
4101 return;
4102 }
4103
4104 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
4105 cameraId.string(), oldStatus, status);
4106
4107 if (oldStatus == StatusInternal::NOT_PRESENT &&
4108 (status != StatusInternal::PRESENT &&
4109 status != StatusInternal::ENUMERATING)) {
4110
4111 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
4112 __FUNCTION__);
4113 mStatus = oldStatus;
4114 return;
4115 }
4116
4117 /**
4118 * Sometimes we want to conditionally do a transition.
4119 * For example if a client disconnects, we want to go to PRESENT
4120 * only if we weren't already in NOT_PRESENT or ENUMERATING.
4121 */
4122 for (auto& rejectStatus : rejectSourceStates) {
4123 if (oldStatus == rejectStatus) {
4124 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
4125 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
4126 mStatus = oldStatus;
4127 return;
4128 }
4129 }
4130
4131 onStatusUpdatedLocked(cameraId, status);
4132}
4133
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004134status_t CameraService::getTorchStatusLocked(
4135 const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004136 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004137 if (!status) {
4138 return BAD_VALUE;
4139 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004140 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
4141 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004142 // invalid camera ID or the camera doesn't have a flash unit
4143 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004144 }
4145
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004146 *status = mTorchStatusMap.valueAt(index);
4147 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004148}
4149
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004150status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004151 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004152 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
4153 if (index == NAME_NOT_FOUND) {
4154 return BAD_VALUE;
4155 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004156 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004157
4158 return OK;
4159}
4160
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004161std::list<String16> CameraService::getLogicalCameras(
4162 const String8& physicalCameraId) {
4163 std::list<String16> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08004164 Mutex::Autolock lock(mCameraStatesLock);
4165 for (const auto& state : mCameraStates) {
4166 std::vector<std::string> physicalCameraIds;
4167 if (!mCameraProviderManager->isLogicalCamera(state.first.c_str(), &physicalCameraIds)) {
4168 // This is not a logical multi-camera.
4169 continue;
4170 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004171 if (std::find(physicalCameraIds.begin(), physicalCameraIds.end(), physicalCameraId.c_str())
Shuzhen Wang43858162020-01-10 13:42:15 -08004172 == physicalCameraIds.end()) {
4173 // cameraId is not a physical camera of this logical multi-camera.
4174 continue;
4175 }
4176
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004177 retList.emplace_back(String16(state.first));
4178 }
4179 return retList;
4180}
4181
4182void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
4183 const String16& physicalCameraId, const std::list<String16>& logicalCameraIds,
4184 SystemCameraKind deviceKind) {
4185 // mStatusListenerLock is expected to be locked
4186 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08004187 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004188 // Note: we check only the deviceKind of the physical camera id
4189 // since, logical camera ids and their physical camera ids are
4190 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07004191 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
4192 listener->getListenerPid(), listener->getListenerUid())) {
4193 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004194 String8(physicalCameraId).c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07004195 continue;
4196 }
Shuzhen Wang43858162020-01-10 13:42:15 -08004197 listener->getListener()->onPhysicalCameraStatusChanged(status,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004198 logicalCameraId, physicalCameraId);
Shuzhen Wang43858162020-01-10 13:42:15 -08004199 }
4200 }
4201}
4202
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004203
Svet Ganova453d0d2018-01-11 15:37:58 -08004204void CameraService::blockClientsForUid(uid_t uid) {
4205 const auto clients = mActiveClientManager.getAll();
4206 for (auto& current : clients) {
4207 if (current != nullptr) {
4208 const auto basicClient = current->getValue();
4209 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
4210 basicClient->block();
4211 }
4212 }
4213 }
4214}
4215
Michael Grooverd1d435a2018-12-18 17:39:42 -08004216void CameraService::blockAllClients() {
4217 const auto clients = mActiveClientManager.getAll();
4218 for (auto& current : clients) {
4219 if (current != nullptr) {
4220 const auto basicClient = current->getValue();
4221 if (basicClient.get() != nullptr) {
4222 basicClient->block();
4223 }
4224 }
4225 }
4226}
4227
Svet Ganova453d0d2018-01-11 15:37:58 -08004228// NOTE: This is a remote API - make sure all args are validated
4229status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
4230 if (!checkCallingPermission(sManageCameraPermission, nullptr, nullptr)) {
4231 return PERMISSION_DENIED;
4232 }
4233 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
4234 return BAD_VALUE;
4235 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004236 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004237 return handleSetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07004238 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004239 return handleResetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07004240 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004241 return handleGetUidState(args, out, err);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004242 } else if (args.size() >= 2 && args[0] == String16("set-rotate-and-crop")) {
4243 return handleSetRotateAndCrop(args);
4244 } else if (args.size() >= 1 && args[0] == String16("get-rotate-and-crop")) {
4245 return handleGetRotateAndCrop(out);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004246 } else if (args.size() >= 2 && args[0] == String16("set-image-dump-mask")) {
4247 return handleSetImageDumpMask(args);
4248 } else if (args.size() >= 1 && args[0] == String16("get-image-dump-mask")) {
4249 return handleGetImageDumpMask(out);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004250 } else if (args.size() >= 2 && args[0] == String16("set-camera-mute")) {
4251 return handleSetCameraMute(args);
Svet Ganova453d0d2018-01-11 15:37:58 -08004252 } else if (args.size() == 1 && args[0] == String16("help")) {
4253 printHelp(out);
4254 return NO_ERROR;
4255 }
4256 printHelp(err);
4257 return BAD_VALUE;
4258}
4259
4260status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004261 String16 packageName = args[1];
4262
Svet Ganova453d0d2018-01-11 15:37:58 -08004263 bool active = false;
4264 if (args[2] == String16("active")) {
4265 active = true;
4266 } else if ((args[2] != String16("idle"))) {
4267 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
4268 return BAD_VALUE;
4269 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004270
4271 int userId = 0;
4272 if (args.size() >= 5 && args[3] == String16("--user")) {
4273 userId = atoi(String8(args[4]));
4274 }
4275
4276 uid_t uid;
4277 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
4278 return BAD_VALUE;
4279 }
4280
4281 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08004282 return NO_ERROR;
4283}
4284
4285status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004286 String16 packageName = args[1];
4287
4288 int userId = 0;
4289 if (args.size() >= 4 && args[2] == String16("--user")) {
4290 userId = atoi(String8(args[3]));
4291 }
4292
4293 uid_t uid;
4294 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004295 return BAD_VALUE;
4296 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004297
4298 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08004299 return NO_ERROR;
4300}
4301
4302status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004303 String16 packageName = args[1];
4304
4305 int userId = 0;
4306 if (args.size() >= 4 && args[2] == String16("--user")) {
4307 userId = atoi(String8(args[3]));
4308 }
4309
4310 uid_t uid;
4311 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004312 return BAD_VALUE;
4313 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004314
4315 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004316 return dprintf(out, "active\n");
4317 } else {
4318 return dprintf(out, "idle\n");
4319 }
4320}
4321
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004322status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
4323 int rotateValue = atoi(String8(args[1]));
4324 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
4325 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
4326 Mutex::Autolock lock(mServiceLock);
4327
4328 mOverrideRotateAndCropMode = rotateValue;
4329
4330 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
4331
4332 const auto clients = mActiveClientManager.getAll();
4333 for (auto& current : clients) {
4334 if (current != nullptr) {
4335 const auto basicClient = current->getValue();
4336 if (basicClient.get() != nullptr) {
4337 basicClient->setRotateAndCropOverride(rotateValue);
4338 }
4339 }
4340 }
4341
4342 return OK;
4343}
4344
4345status_t CameraService::handleGetRotateAndCrop(int out) {
4346 Mutex::Autolock lock(mServiceLock);
4347
4348 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
4349}
4350
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004351status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
4352 char *endPtr;
4353 errno = 0;
4354 String8 maskString8 = String8(args[1]);
4355 long maskValue = strtol(maskString8.c_str(), &endPtr, 10);
4356
4357 if (errno != 0) return BAD_VALUE;
4358 if (endPtr != maskString8.c_str() + maskString8.size()) return BAD_VALUE;
4359 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
4360
4361 Mutex::Autolock lock(mServiceLock);
4362
4363 mImageDumpMask = maskValue;
4364
4365 return OK;
4366}
4367
4368status_t CameraService::handleGetImageDumpMask(int out) {
4369 Mutex::Autolock lock(mServiceLock);
4370
4371 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
4372}
4373
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004374status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
4375 int muteValue = strtol(String8(args[1]), nullptr, 10);
4376 if (errno != 0) return BAD_VALUE;
4377
4378 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
4379 Mutex::Autolock lock(mServiceLock);
4380
4381 mOverrideCameraMuteMode = (muteValue == 1);
4382
4383 const auto clients = mActiveClientManager.getAll();
4384 for (auto& current : clients) {
4385 if (current != nullptr) {
4386 const auto basicClient = current->getValue();
4387 if (basicClient.get() != nullptr) {
4388 if (basicClient->supportsCameraMute()) {
4389 basicClient->setCameraMute(mOverrideCameraMuteMode);
4390 }
4391 }
4392 }
4393 }
4394
4395 return OK;
4396}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004397
Svet Ganova453d0d2018-01-11 15:37:58 -08004398status_t CameraService::printHelp(int out) {
4399 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07004400 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
4401 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
4402 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004403 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
4404 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
4405 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004406 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
4407 " Valid values 0=OFF, 1=ON for JPEG\n"
4408 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004409 " set-camera-mute <0/1> enable or disable camera muting\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08004410 " help print this message\n");
4411}
4412
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004413int32_t CameraService::updateAudioRestriction() {
4414 Mutex::Autolock lock(mServiceLock);
4415 return updateAudioRestrictionLocked();
4416}
4417
4418int32_t CameraService::updateAudioRestrictionLocked() {
4419 int32_t mode = 0;
4420 // iterate through all active client
4421 for (const auto& i : mActiveClientManager.getAll()) {
4422 const auto clientSp = i->getValue();
4423 mode |= clientSp->getAudioRestriction();
4424 }
4425
4426 bool modeChanged = (mAudioRestriction != mode);
4427 mAudioRestriction = mode;
4428 if (modeChanged) {
4429 mAppOps.setCameraAudioRestriction(mode);
4430 }
4431 return mode;
4432}
4433
Cliff Wud8cae102021-03-11 01:37:42 +08004434void CameraService::stopInjectionImpl() {
4435 mInjectionStatusListener->removeListener();
4436
4437 // TODO: Implement the stop injection function.
4438}
4439
Mathias Agopian65ab4712010-07-14 17:59:35 -07004440}; // namespace android