blob: e9c941ef8e2a046dd4a6a0d5f56cca8e8bf4fb35 [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>
Ruben Brunkcc776712015-02-17 20:18:47 -080024#include <cstring>
25#include <ctime>
26#include <string>
Mathias Agopian65ab4712010-07-14 17:59:35 -070027#include <sys/types.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080028#include <inttypes.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070029#include <pthread.h>
30
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080031#include <android/hardware/ICamera.h>
32#include <android/hardware/ICameraClient.h>
33
Alex Deymo9c2a2c22016-08-25 11:59:14 -070034#include <android-base/macros.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080035#include <android-base/parseint.h>
Jayant Chowdharyb61526c2019-05-13 19:37:42 -070036#include <android-base/stringprintf.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080037#include <binder/ActivityManager.h>
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -080038#include <binder/AppOpsManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070039#include <binder/IPCThreadState.h>
40#include <binder/IServiceManager.h>
41#include <binder/MemoryBase.h>
42#include <binder/MemoryHeapBase.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080043#include <binder/PermissionController.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080044#include <binder/ProcessInfoService.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080045#include <binder/IResultReceiver.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>
Mathias Agopian65ab4712010-07-14 17:59:35 -070059#include <utils/Errors.h>
60#include <utils/Log.h>
61#include <utils/String16.h>
Svet Ganov94ec46f2018-06-08 15:03:46 -070062#include <utils/SystemClock.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080063#include <utils/Trace.h>
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080064#include <utils/CallStack.h>
Chien-Yu Chen98a668f2015-12-18 14:10:33 -080065#include <private/android_filesystem_config.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080066#include <system/camera_vendor_tags.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070067#include <system/camera_metadata.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080068
Ruben Brunkb2119af2014-05-09 19:57:56 -070069#include <system/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070070
71#include "CameraService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070072#include "api1/CameraClient.h"
73#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"
Mathias Agopian65ab4712010-07-14 17:59:35 -070078
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080079namespace {
80 const char* kPermissionServiceName = "permission";
81}; // namespace anonymous
82
Mathias Agopian65ab4712010-07-14 17:59:35 -070083namespace android {
84
Jayant Chowdharyb61526c2019-05-13 19:37:42 -070085using base::StringPrintf;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080086using binder::Status;
Jayant Chowdharybe543d42018-08-15 13:16:14 -070087using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -080088using hardware::ICamera;
89using hardware::ICameraClient;
Eino-Ville Talvalae8c96c72017-06-27 12:24:07 -070090using hardware::ICameraServiceProxy;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -080091using hardware::ICameraServiceListener;
92using hardware::camera::common::V1_0::CameraDeviceStatus;
93using hardware::camera::common::V1_0::TorchModeStatus;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080094using hardware::camera2::utils::CameraIdAndSessionConfiguration;
95using hardware::camera2::utils::ConcurrentCameraIdCombination;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080096
Mathias Agopian65ab4712010-07-14 17:59:35 -070097// ----------------------------------------------------------------------------
98// Logging support -- this is for debugging only
99// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700100volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700101
Steve Blockb8a80522011-12-20 16:23:08 +0000102#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
103#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700104
105static void setLogLevel(int level) {
106 android_atomic_write(level, &gLogLevel);
107}
108
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800109// Convenience methods for constructing binder::Status objects for error returns
110
111#define STATUS_ERROR(errorCode, errorString) \
112 binder::Status::fromServiceSpecificError(errorCode, \
113 String8::format("%s:%d: %s", __FUNCTION__, __LINE__, errorString))
114
115#define STATUS_ERROR_FMT(errorCode, errorString, ...) \
116 binder::Status::fromServiceSpecificError(errorCode, \
117 String8::format("%s:%d: " errorString, __FUNCTION__, __LINE__, \
118 __VA_ARGS__))
119
Mathias Agopian65ab4712010-07-14 17:59:35 -0700120// ----------------------------------------------------------------------------
121
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700122static const String16 sDumpPermission("android.permission.DUMP");
Svet Ganova453d0d2018-01-11 15:37:58 -0800123static const String16 sManageCameraPermission("android.permission.MANAGE_CAMERA");
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700124static const String16 sCameraPermission("android.permission.CAMERA");
125static const String16 sSystemCameraPermission("android.permission.SYSTEM_CAMERA");
126static const String16
127 sCameraSendSystemEventsPermission("android.permission.CAMERA_SEND_SYSTEM_EVENTS");
Svet Ganova453d0d2018-01-11 15:37:58 -0800128
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700129// Matches with PERCEPTIBLE_APP_ADJ in ProcessList.java
130static constexpr int32_t kVendorClientScore = 200;
131// Matches with PROCESS_STATE_PERSISTENT_UI in ActivityManager.java
132static constexpr int32_t kVendorClientState = 1;
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800133const String8 CameraService::kOfflineDevice("offline-");
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700134
Eino-Ville Talvala7d5569f2019-04-08 13:57:54 -0700135Mutex CameraService::sProxyMutex;
136sp<hardware::ICameraServiceProxy> CameraService::sCameraServiceProxy;
137
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800138CameraService::CameraService() :
139 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800140 mNumberOfCameras(0),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700141 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700142 mSoundRef(0), mInitialized(false),
143 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000144 ALOGI("CameraService started (pid=%d)", getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800145 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700146}
147
Iliyan Malchev8951a972011-04-14 16:55:59 -0700148void CameraService::onFirstRef()
149{
Ruben Brunkcc776712015-02-17 20:18:47 -0800150 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800151
Iliyan Malchev8951a972011-04-14 16:55:59 -0700152 BnCameraService::onFirstRef();
153
Ruben Brunk99e69712015-05-26 17:25:07 -0700154 // Update battery life tracking if service is restarting
155 BatteryNotifier& notifier(BatteryNotifier::getInstance());
156 notifier.noteResetCamera();
157 notifier.noteResetFlashlight();
158
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800159 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800160
Emilian Peevf53f66e2017-04-11 14:29:43 +0100161 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800162 if (res == OK) {
163 mInitialized = true;
164 }
165
Svet Ganova453d0d2018-01-11 15:37:58 -0800166 mUidPolicy = new UidPolicy(this);
167 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800168 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
169 mSensorPrivacyPolicy->registerSelf();
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700170 mAppOps.setCameraAudioRestriction(mAudioRestriction);
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700171 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
172 if (hcs->registerAsService() != android::OK) {
173 ALOGE("%s: Failed to register default android.frameworks.cameraservice.service@1.0",
174 __FUNCTION__);
175 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700176
177 // This needs to be last call in this function, so that it's as close to
178 // ServiceManager::addService() as possible.
179 CameraService::pingCameraServiceProxy();
180 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800181}
182
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800183status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800184 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100185
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800186 std::vector<std::string> deviceIds;
187 {
188 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800189
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800190 if (nullptr == mCameraProviderManager.get()) {
191 mCameraProviderManager = new CameraProviderManager();
192 res = mCameraProviderManager->initialize(this);
193 if (res != OK) {
194 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
195 __FUNCTION__, strerror(-res), res);
196 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100197 }
198 }
199
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800200
201 // Setup vendor tags before we call get_camera_info the first time
202 // because HAL might need to setup static vendor keys in get_camera_info
203 // TODO: maybe put this into CameraProviderManager::initialize()?
204 mCameraProviderManager->setUpVendorTags();
205
206 if (nullptr == mFlashlight.get()) {
207 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700208 }
209
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800210 res = mFlashlight->findFlashUnits();
211 if (res != OK) {
212 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
213 }
214
215 deviceIds = mCameraProviderManager->getCameraDeviceIds();
216 }
217
218
219 for (auto& cameraId : deviceIds) {
220 String8 id8 = String8(cameraId.c_str());
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800221 if (getCameraState(id8) == nullptr) {
222 onDeviceStatusChanged(id8, CameraDeviceStatus::PRESENT);
223 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800224 }
225
226 return OK;
227}
228
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700229sp<ICameraServiceProxy> CameraService::getCameraServiceProxy() {
Christopher Wiley92c06fc2016-02-11 15:40:05 -0800230#ifndef __BRILLO__
Eino-Ville Talvala7d5569f2019-04-08 13:57:54 -0700231 Mutex::Autolock al(sProxyMutex);
232 if (sCameraServiceProxy == nullptr) {
233 sp<IServiceManager> sm = defaultServiceManager();
234 // Use checkService because cameraserver normally starts before the
235 // system server and the proxy service. So the long timeout that getService
236 // has before giving up is inappropriate.
237 sp<IBinder> binder = sm->checkService(String16("media.camera.proxy"));
238 if (binder != nullptr) {
239 sCameraServiceProxy = interface_cast<ICameraServiceProxy>(binder);
240 }
Ruben Brunk2823ce02015-05-19 17:25:13 -0700241 }
Christopher Wiley92c06fc2016-02-11 15:40:05 -0800242#endif
Eino-Ville Talvala7d5569f2019-04-08 13:57:54 -0700243 return sCameraServiceProxy;
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700244}
245
246void CameraService::pingCameraServiceProxy() {
247 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
248 if (proxyBinder == nullptr) return;
Ruben Brunk2823ce02015-05-19 17:25:13 -0700249 proxyBinder->pingForUserUpdate();
Iliyan Malchev8951a972011-04-14 16:55:59 -0700250}
251
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800252void CameraService::broadcastTorchModeStatus(const String8& cameraId, TorchModeStatus status) {
253 Mutex::Autolock lock(mStatusListenerLock);
254
255 for (auto& i : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700256 i->getListener()->onTorchStatusChanged(mapToInterface(status), String16{cameraId});
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800257 }
258}
259
Mathias Agopian65ab4712010-07-14 17:59:35 -0700260CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800261 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800262 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800263 mSensorPrivacyPolicy->unregisterSelf();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700264}
265
Emilian Peevaee727d2017-05-04 16:35:48 +0100266void CameraService::onNewProviderRegistered() {
267 enumerateProviders();
268}
269
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700270void CameraService::filterAPI1SystemCameraLocked(
271 const std::vector<std::string> &normalDeviceIds) {
272 mNormalDeviceIdsWithoutSystemCamera.clear();
273 for (auto &deviceId : normalDeviceIds) {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700274 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
275 if (getSystemCameraKind(String8(deviceId.c_str()), &deviceKind) != OK) {
276 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, deviceId.c_str());
277 continue;
278 }
279 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700280 // All system camera ids will necessarily come after public camera
281 // device ids as per the HAL interface contract.
282 break;
283 }
284 mNormalDeviceIdsWithoutSystemCamera.push_back(deviceId);
285 }
286 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
287 mNormalDeviceIdsWithoutSystemCamera.size());
288}
289
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700290status_t CameraService::getSystemCameraKind(const String8& cameraId, SystemCameraKind *kind) const {
291 auto state = getCameraState(cameraId);
292 if (state != nullptr) {
293 *kind = state->getSystemCameraKind();
294 return OK;
295 }
296 // Hidden physical camera ids won't have CameraState
297 return mCameraProviderManager->getSystemCameraKind(cameraId.c_str(), kind);
298}
299
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800300void CameraService::updateCameraNumAndIds() {
301 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700302 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
303 // Excludes hidden secure cameras
304 mNumberOfCameras =
305 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
306 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800307 mNormalDeviceIds =
308 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700309 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800310}
311
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100312void CameraService::addStates(const String8 id) {
313 std::string cameraId(id.c_str());
314 hardware::camera::common::V1_0::CameraResourceCost cost;
315 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700316 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100317 if (res != OK) {
318 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
319 return;
320 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700321 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
322 if (res != OK) {
323 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
324 return;
325 }
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100326 std::set<String8> conflicting;
327 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
328 conflicting.emplace(String8(cost.conflictingDevices[i].c_str()));
329 }
330
331 {
332 Mutex::Autolock lock(mCameraStatesLock);
333 mCameraStates.emplace(id, std::make_shared<CameraState>(id, cost.resourceCost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700334 conflicting, deviceKind));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100335 }
336
337 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100338 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100339 mTorchStatusMap.add(id, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800340
341 broadcastTorchModeStatus(id, TorchModeStatus::AVAILABLE_OFF);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100342 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800343
344 updateCameraNumAndIds();
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100345 logDeviceAdded(id, "Device added");
346}
347
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100348void CameraService::removeStates(const String8 id) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800349 updateCameraNumAndIds();
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100350 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100351 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100352 mTorchStatusMap.removeItem(id);
353 }
354
355 {
356 Mutex::Autolock lock(mCameraStatesLock);
357 mCameraStates.erase(id);
358 }
359}
360
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800361void CameraService::onDeviceStatusChanged(const String8& id,
362 CameraDeviceStatus newHalStatus) {
363 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
364 id.string(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700365
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800366 StatusInternal newStatus = mapToInternal(newHalStatus);
367
Ruben Brunkcc776712015-02-17 20:18:47 -0800368 std::shared_ptr<CameraState> state = getCameraState(id);
369
370 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700371 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100372 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700373 __FUNCTION__, id.string());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100374
375 // First add as absent to make sure clients are notified below
376 addStates(id);
377
378 updateStatus(newStatus, id);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700379 } else {
380 ALOGE("%s: Bad camera ID %s", __FUNCTION__, id.string());
381 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700382 return;
383 }
384
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800385 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800386
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800387 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800388 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700389 return;
390 }
391
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800392 if (newStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700393 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
394 newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800395
396 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
397 // to this device until the status changes
398 updateStatus(StatusInternal::NOT_PRESENT, id);
399
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800400 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700401 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800402 // Don't do this in updateStatus to avoid deadlock over mServiceLock
403 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700404
Ruben Brunkcc776712015-02-17 20:18:47 -0800405 // Remove cached shim parameters
406 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700407
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800408 // Remove online as well as offline client from the list of active clients,
409 // if they are present
410 clientToDisconnectOnline = removeClientLocked(id);
411 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + id);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700412 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800413
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800414 disconnectClient(id, clientToDisconnectOnline);
415 disconnectClient(kOfflineDevice + id, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700416
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100417 removeStates(id);
Ruben Brunkcc776712015-02-17 20:18:47 -0800418 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800419 if (oldStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700420 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
421 newStatus));
422 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800423 updateStatus(newStatus, id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700424 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800425}
Igor Murashkincba2c162013-03-20 15:56:31 -0700426
Shuzhen Wang43858162020-01-10 13:42:15 -0800427void CameraService::onDeviceStatusChanged(const String8& id,
428 const String8& physicalId,
429 CameraDeviceStatus newHalStatus) {
430 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
431 __FUNCTION__, id.string(), physicalId.string(), newHalStatus);
432
433 StatusInternal newStatus = mapToInternal(newHalStatus);
434
435 std::shared_ptr<CameraState> state = getCameraState(id);
436
437 if (state == nullptr) {
438 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
439 __FUNCTION__, id.string(), physicalId.string());
440 return;
441 }
442
443 StatusInternal logicalCameraStatus = state->getStatus();
444 if (logicalCameraStatus != StatusInternal::PRESENT &&
445 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
446 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
447 __FUNCTION__, physicalId.string(), newHalStatus, logicalCameraStatus);
448 return;
449 }
450
451 bool updated = false;
452 if (newStatus == StatusInternal::PRESENT) {
453 updated = state->removeUnavailablePhysicalId(physicalId);
454 } else {
455 updated = state->addUnavailablePhysicalId(physicalId);
456 }
457
458 if (updated) {
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800459 String8 idCombo = id + " : " + physicalId;
460 if (newStatus == StatusInternal::PRESENT) {
461 logDeviceAdded(idCombo,
462 String8::format("Device status changed to %d", newStatus));
463 } else {
464 logDeviceRemoved(idCombo,
465 String8::format("Device status changed to %d", newStatus));
466 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800467
468 String16 id16(id), physicalId16(physicalId);
469 Mutex::Autolock lock(mStatusListenerLock);
470 for (auto& listener : mListenerList) {
471 listener->getListener()->onPhysicalCameraStatusChanged(mapToInterface(newStatus),
472 id16, physicalId16);
473 }
474 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700475}
476
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800477void CameraService::disconnectClient(const String8& id, sp<BasicClient> clientToDisconnect) {
478 if (clientToDisconnect.get() != nullptr) {
479 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
480 __FUNCTION__, id.string());
481 // Notify the client of disconnection
482 clientToDisconnect->notifyError(
483 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
484 CaptureResultExtras{});
485 // Ensure not in binder RPC so client disconnect PID checks work correctly
486 LOG_ALWAYS_FATAL_IF(CameraThreadState::getCallingPid() != getpid(),
487 "onDeviceStatusChanged must be called from the camera service process!");
488 clientToDisconnect->disconnect();
489 }
490}
491
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800492void CameraService::onTorchStatusChanged(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800493 TorchModeStatus newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800494 Mutex::Autolock al(mTorchStatusMutex);
495 onTorchStatusChangedLocked(cameraId, newStatus);
496}
497
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800498void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800499 TorchModeStatus newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800500 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
501 __FUNCTION__, cameraId.string(), newStatus);
502
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800503 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800504 status_t res = getTorchStatusLocked(cameraId, &status);
505 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700506 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
507 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800508 return;
509 }
510 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800511 return;
512 }
513
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800514 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800515 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800516 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
517 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800518 return;
519 }
520
Ruben Brunkcc776712015-02-17 20:18:47 -0800521 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700522 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700523 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700524 auto iter = mTorchUidMap.find(cameraId);
525 if (iter != mTorchUidMap.end()) {
526 int oldUid = iter->second.second;
527 int newUid = iter->second.first;
528 BatteryNotifier& notifier(BatteryNotifier::getInstance());
529 if (oldUid != newUid) {
530 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800531 if (status == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700532 notifier.noteFlashlightOff(cameraId, oldUid);
533 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800534 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700535 notifier.noteFlashlightOn(cameraId, newUid);
536 }
537 iter->second.second = newUid;
538 } else {
539 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800540 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700541 notifier.noteFlashlightOn(cameraId, oldUid);
542 } else {
543 notifier.noteFlashlightOff(cameraId, oldUid);
544 }
545 }
546 }
547 }
548
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800549 broadcastTorchModeStatus(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800550}
551
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700552static bool hasPermissionsForSystemCamera(int callingPid, int callingUid) {
553 return checkPermission(sSystemCameraPermission, callingPid, callingUid) &&
554 checkPermission(sCameraPermission, callingPid, callingUid);
555}
556
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800557Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700558 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100559 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700560 bool hasSystemCameraPermissions =
561 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
562 CameraThreadState::getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700563 switch (type) {
564 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700565 if (hasSystemCameraPermissions) {
566 *numCameras = static_cast<int>(mNormalDeviceIds.size());
567 } else {
568 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
569 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800570 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700571 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700572 if (hasSystemCameraPermissions) {
573 *numCameras = mNumberOfCameras;
574 } else {
575 *numCameras = mNumberOfCamerasWithoutSystemCamera;
576 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800577 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700578 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800579 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700580 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800581 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
582 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700583 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800584 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700585}
586
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800587Status CameraService::getCameraInfo(int cameraId,
588 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700589 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100590 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700591 std::string cameraIdStr = cameraIdIntToStrLocked(cameraId);
592 if (shouldRejectSystemCameraConnection(String8(cameraIdStr.c_str()))) {
593 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
594 "characteristics for system only device %s: ", cameraIdStr.c_str());
595 }
Emilian Peevaee727d2017-05-04 16:35:48 +0100596
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800597 if (!mInitialized) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800598 return STATUS_ERROR(ERROR_DISCONNECTED,
599 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -0700600 }
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700601 bool hasSystemCameraPermissions =
602 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
603 CameraThreadState::getCallingUid());
604 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
605 if (hasSystemCameraPermissions) {
606 cameraIdBound = mNumberOfCameras;
607 }
608 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800609 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
610 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700611 }
612
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800613 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800614 status_t err = mCameraProviderManager->getCameraInfo(
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700615 cameraIdStr.c_str(), cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100616 if (err != OK) {
617 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
618 "Error retrieving camera info from device %d: %s (%d)", cameraId,
619 strerror(-err), err);
Ruben Brunkcc776712015-02-17 20:18:47 -0800620 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100621
Ruben Brunkcc776712015-02-17 20:18:47 -0800622 return ret;
623}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700624
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800625std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700626 const std::vector<std::string> *deviceIds = &mNormalDeviceIdsWithoutSystemCamera;
627 auto callingPid = CameraThreadState::getCallingPid();
628 auto callingUid = CameraThreadState::getCallingUid();
629 if (checkPermission(sSystemCameraPermission, callingPid, callingUid) ||
630 getpid() == callingPid) {
631 deviceIds = &mNormalDeviceIds;
632 }
633 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(deviceIds->size())) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800634 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700635 __FUNCTION__, cameraIdInt, deviceIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800636 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800637 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800638
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700639 return (*deviceIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800640}
641
642String8 CameraService::cameraIdIntToStr(int cameraIdInt) {
643 Mutex::Autolock lock(mServiceLock);
644 return String8(cameraIdIntToStrLocked(cameraIdInt).c_str());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800645}
646
647Status CameraService::getCameraCharacteristics(const String16& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800648 CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700649 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700650 if (!cameraInfo) {
651 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800652 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -0700653 }
654
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800655 if (!mInitialized) {
656 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800657 return STATUS_ERROR(ERROR_DISCONNECTED,
658 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -0700659 }
660
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700661 if (shouldRejectSystemCameraConnection(String8(cameraId))) {
662 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
663 "characteristics for system only device %s: ", String8(cameraId).string());
664 }
665
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800666 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800667
Emilian Peevf53f66e2017-04-11 14:29:43 +0100668 status_t res = mCameraProviderManager->getCameraCharacteristics(
669 String8(cameraId).string(), cameraInfo);
670 if (res != OK) {
671 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
672 "characteristics for device %s: %s (%d)", String8(cameraId).string(),
673 strerror(-res), res);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700674 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700675 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
676 if (getSystemCameraKind(String8(cameraId), &deviceKind) != OK) {
677 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, String8(cameraId).string());
678 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera kind "
679 "for device %s", String8(cameraId).string());
680 }
Jayant Chowdhary12361932018-08-27 14:46:13 -0700681 int callingPid = CameraThreadState::getCallingPid();
682 int callingUid = CameraThreadState::getCallingUid();
Emilian Peeve20c6372018-08-14 18:45:53 +0100683 std::vector<int32_t> tagsRemoved;
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700684 // If it's not calling from cameraserver, check the permission only if
685 // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
686 // it would've already been checked in shouldRejectSystemCameraConnection.
Emilian Peeve20c6372018-08-14 18:45:53 +0100687 if ((callingPid != getpid()) &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700688 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700689 !checkPermission(sCameraPermission, callingPid, callingUid)) {
Emilian Peeve20c6372018-08-14 18:45:53 +0100690 res = cameraInfo->removePermissionEntries(
691 mCameraProviderManager->getProviderTagIdLocked(String8(cameraId).string()),
692 &tagsRemoved);
693 if (res != OK) {
694 cameraInfo->clear();
695 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
696 " characteristics needing camera permission for device %s: %s (%d)",
697 String8(cameraId).string(), strerror(-res), res);
698 }
699 }
700
701 if (!tagsRemoved.empty()) {
702 res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
703 tagsRemoved.data(), tagsRemoved.size());
704 if (res != OK) {
705 cameraInfo->clear();
706 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
707 "keys needing permission for device %s: %s (%d)", String8(cameraId).string(),
708 strerror(-res), res);
709 }
710 }
711
Zhijun He2b59be82013-09-25 10:14:30 -0700712 return ret;
713}
714
Ruben Brunkcc776712015-02-17 20:18:47 -0800715String8 CameraService::getFormattedCurrentTime() {
716 time_t now = time(nullptr);
717 char formattedTime[64];
718 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
719 return String8(formattedTime);
720}
721
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800722Status CameraService::getCameraVendorTagDescriptor(
723 /*out*/
724 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700725 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800726 if (!mInitialized) {
727 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800728 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800729 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -0800730 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
731 if (globalDescriptor != nullptr) {
732 *desc = *(globalDescriptor.get());
733 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800734 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800735}
736
Emilian Peev71c73a22017-03-21 16:35:51 +0000737Status CameraService::getCameraVendorTagCache(
738 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
739 ATRACE_CALL();
740 if (!mInitialized) {
741 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
742 return STATUS_ERROR(ERROR_DISCONNECTED,
743 "Camera subsystem not available");
744 }
745 sp<VendorTagDescriptorCache> globalCache =
746 VendorTagDescriptorCache::getGlobalVendorTagCache();
747 if (globalCache != nullptr) {
748 *cache = *(globalCache.get());
749 }
750 return Status::ok();
751}
752
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800753int CameraService::getDeviceVersion(const String8& cameraId, int* facing) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700754 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800755
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800756 int deviceVersion = 0;
757
Emilian Peevf53f66e2017-04-11 14:29:43 +0100758 status_t res;
759 hardware::hidl_version maxVersion{0,0};
760 res = mCameraProviderManager->getHighestSupportedVersion(cameraId.string(),
761 &maxVersion);
762 if (res != OK) return -1;
763 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800764
Emilian Peevf53f66e2017-04-11 14:29:43 +0100765 hardware::CameraInfo info;
766 if (facing) {
767 res = mCameraProviderManager->getCameraInfo(cameraId.string(), &info);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -0800768 if (res != OK) return -1;
Emilian Peevf53f66e2017-04-11 14:29:43 +0100769 *facing = info.facing;
Igor Murashkin634a5152013-02-20 17:15:11 -0800770 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100771
Igor Murashkin634a5152013-02-20 17:15:11 -0800772 return deviceVersion;
773}
774
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800775Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700776 switch(err) {
777 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800778 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800779 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800780 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
781 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800782 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800783 return STATUS_ERROR(ERROR_DISCONNECTED,
784 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700785 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800786 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
787 "Camera HAL encountered error %d: %s",
788 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700789 }
Igor Murashkinbfc99152013-02-27 12:55:20 -0800790}
791
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800792Status CameraService::makeClient(const sp<CameraService>& cameraService,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800793 const sp<IInterface>& cameraCb, const String16& packageName,
794 const std::unique_ptr<String16>& featureId, const String8& cameraId, int api1CameraId,
795 int facing, int clientPid, uid_t clientUid, int servicePid, int halVersion,
796 int deviceVersion, apiLevel effectiveApiLevel,
Ruben Brunkcc776712015-02-17 20:18:47 -0800797 /*out*/sp<BasicClient>* client) {
798
Ruben Brunkcc776712015-02-17 20:18:47 -0800799 if (halVersion < 0 || halVersion == deviceVersion) {
800 // Default path: HAL version is unspecified by caller, create CameraClient
801 // based on device version reported by the HAL.
802 switch(deviceVersion) {
803 case CAMERA_DEVICE_API_VERSION_1_0:
804 if (effectiveApiLevel == API_1) { // Camera1 API route
805 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800806 *client = new CameraClient(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800807 api1CameraId, facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700808 getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800809 } else { // Camera2 API route
810 ALOGW("Camera using old HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800811 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800812 "Camera device \"%s\" HAL version %d does not support camera2 API",
813 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800814 }
815 break;
Ruben Brunkcc776712015-02-17 20:18:47 -0800816 case CAMERA_DEVICE_API_VERSION_3_0:
817 case CAMERA_DEVICE_API_VERSION_3_1:
818 case CAMERA_DEVICE_API_VERSION_3_2:
819 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -0700820 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -0700821 case CAMERA_DEVICE_API_VERSION_3_5:
Yin-Chia Yeh56d98ba2020-01-16 16:57:14 -0800822 case CAMERA_DEVICE_API_VERSION_3_6:
Ruben Brunkcc776712015-02-17 20:18:47 -0800823 if (effectiveApiLevel == API_1) { // Camera1 API route
824 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800825 *client = new Camera2Client(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800826 cameraId, api1CameraId,
827 facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700828 servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800829 } else { // Camera2 API route
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800830 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
831 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800832 *client = new CameraDeviceClient(cameraService, tmp, packageName, featureId,
833 cameraId, facing, clientPid, clientUid, servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800834 }
835 break;
836 default:
837 // Should not be reachable
838 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800839 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800840 "Camera device \"%s\" has unknown HAL version %d",
841 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800842 }
843 } else {
844 // A particular HAL version is requested by caller. Create CameraClient
845 // based on the requested HAL version.
846 if (deviceVersion > CAMERA_DEVICE_API_VERSION_1_0 &&
847 halVersion == CAMERA_DEVICE_API_VERSION_1_0) {
848 // Only support higher HAL version device opened as HAL1.0 device.
849 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800850 *client = new CameraClient(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800851 api1CameraId, facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700852 servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800853 } else {
854 // Other combinations (e.g. HAL3.x open as HAL2.x) are not supported yet.
855 ALOGE("Invalid camera HAL version %x: HAL %x device can only be"
856 " opened as HAL %x device", halVersion, deviceVersion,
857 CAMERA_DEVICE_API_VERSION_1_0);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800858 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800859 "Camera device \"%s\" (HAL version %d) cannot be opened as HAL version %d",
860 cameraId.string(), deviceVersion, halVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800861 }
862 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800863 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800864}
865
Ruben Brunk6267b532015-04-30 17:44:07 -0700866String8 CameraService::toString(std::set<userid_t> intSet) {
867 String8 s("");
868 bool first = true;
869 for (userid_t i : intSet) {
870 if (first) {
871 s.appendFormat("%d", i);
872 first = false;
873 } else {
874 s.appendFormat(", %d", i);
875 }
876 }
877 return s;
878}
879
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800880int32_t CameraService::mapToInterface(TorchModeStatus status) {
881 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
882 switch (status) {
883 case TorchModeStatus::NOT_AVAILABLE:
884 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
885 break;
886 case TorchModeStatus::AVAILABLE_OFF:
887 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
888 break;
889 case TorchModeStatus::AVAILABLE_ON:
890 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
891 break;
892 default:
893 ALOGW("Unknown new flash status: %d", status);
894 }
895 return serviceStatus;
896}
897
898CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
899 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
900 switch (status) {
901 case CameraDeviceStatus::NOT_PRESENT:
902 serviceStatus = StatusInternal::NOT_PRESENT;
903 break;
904 case CameraDeviceStatus::PRESENT:
905 serviceStatus = StatusInternal::PRESENT;
906 break;
907 case CameraDeviceStatus::ENUMERATING:
908 serviceStatus = StatusInternal::ENUMERATING;
909 break;
910 default:
911 ALOGW("Unknown new HAL device status: %d", status);
912 }
913 return serviceStatus;
914}
915
916int32_t CameraService::mapToInterface(StatusInternal status) {
917 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
918 switch (status) {
919 case StatusInternal::NOT_PRESENT:
920 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
921 break;
922 case StatusInternal::PRESENT:
923 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
924 break;
925 case StatusInternal::ENUMERATING:
926 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
927 break;
928 case StatusInternal::NOT_AVAILABLE:
929 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
930 break;
931 case StatusInternal::UNKNOWN:
932 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
933 break;
934 default:
935 ALOGW("Unknown new internal device status: %d", status);
936 }
937 return serviceStatus;
938}
939
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800940Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -0700941 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700942
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800943 String16 internalPackageName("cameraserver");
Ruben Brunkcc776712015-02-17 20:18:47 -0800944 String8 id = String8::format("%d", cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800945 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800946 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800947 if (!(ret = connectHelper<ICameraClient,Client>(
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800948 sp<ICameraClient>{nullptr}, id, cameraId,
949 static_cast<int>(CAMERA_HAL_API_VERSION_UNSPECIFIED),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800950 internalPackageName, std::unique_ptr<String16>(), uid, USE_CALLING_PID,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700951 API_1, /*shimUpdateOnly*/ true, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800952 ).isOk()) {
953 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
Ruben Brunkb2119af2014-05-09 19:57:56 -0700954 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800955 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700956}
957
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800958Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -0700959 /*out*/
960 CameraParameters* parameters) {
961
962 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
963
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800964 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -0700965
966 if (parameters == NULL) {
967 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800968 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -0700969 }
970
Ruben Brunkcc776712015-02-17 20:18:47 -0800971 String8 id = String8::format("%d", cameraId);
972
973 // Check if we already have parameters
974 {
975 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -0700976 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -0800977 auto cameraState = getCameraState(id);
978 if (cameraState == nullptr) {
979 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800980 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
981 "Invalid camera ID: %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -0800982 }
983 CameraParameters p = cameraState->getShimParams();
984 if (!p.isEmpty()) {
985 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800986 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700987 }
988 }
989
Jayant Chowdhary12361932018-08-27 14:46:13 -0700990 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -0800991 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -0700992 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800993 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800994 // Error already logged by callee
995 return ret;
996 }
997
998 // Check for parameters again
999 {
1000 // Scope for service lock
1001 Mutex::Autolock lock(mServiceLock);
1002 auto cameraState = getCameraState(id);
1003 if (cameraState == nullptr) {
1004 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001005 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1006 "Invalid camera ID: %s", id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001007 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001008 CameraParameters p = cameraState->getShimParams();
1009 if (!p.isEmpty()) {
1010 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001011 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001012 }
1013 }
1014
Ruben Brunkcc776712015-02-17 20:18:47 -08001015 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1016 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001017 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001018}
1019
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001020// Can camera service trust the caller based on the calling UID?
1021static bool isTrustedCallingUid(uid_t uid) {
1022 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001023 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001024 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001025 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001026 return true;
1027 default:
1028 return false;
1029 }
1030}
1031
Nicholas Sauera3620332019-04-03 14:05:17 -07001032static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1033 PermissionController pc;
1034 uid = pc.getPackageUid(packageName, 0);
1035 if (uid <= 0) {
1036 ALOGE("Unknown package: '%s'", String8(packageName).string());
1037 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
1038 return BAD_VALUE;
1039 }
1040
1041 if (userId < 0) {
1042 ALOGE("Invalid user: %d", userId);
1043 dprintf(err, "Invalid user: %d\n", userId);
1044 return BAD_VALUE;
1045 }
1046
1047 uid = multiuser_get_uid(userId, uid);
1048 return NO_ERROR;
1049}
1050
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001051Status CameraService::validateConnectLocked(const String8& cameraId,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001052 const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
1053 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001054
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001055#ifdef __BRILLO__
1056 UNUSED(clientName8);
1057 UNUSED(clientUid);
1058 UNUSED(clientPid);
1059 UNUSED(originalClientPid);
1060#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001061 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1062 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001063 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001064 return allowed;
1065 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001066#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001067
Jayant Chowdhary12361932018-08-27 14:46:13 -07001068 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001069
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001070 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001071 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1072 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001073 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1074 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001075 }
1076
Ruben Brunkcc776712015-02-17 20:18:47 -08001077 if (getCameraState(cameraId) == nullptr) {
1078 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1079 cameraId.string());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001080 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1081 "No camera device with ID \"%s\" available", cameraId.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001082 }
1083
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001084 status_t err = checkIfDeviceIsUsable(cameraId);
1085 if (err != NO_ERROR) {
1086 switch(err) {
1087 case -ENODEV:
1088 case -EBUSY:
1089 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1090 "No camera device with ID \"%s\" currently available", cameraId.string());
1091 default:
1092 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1093 "Unknown error connecting to ID \"%s\"", cameraId.string());
1094 }
1095 }
1096 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001097}
1098
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001099Status CameraService::validateClientPermissionsLocked(const String8& cameraId,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001100 const String8& clientName8, int& clientUid, int& clientPid,
1101 /*out*/int& originalClientPid) const {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001102 int callingPid = CameraThreadState::getCallingPid();
1103 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001104
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001105 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001106 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001107 clientUid = callingUid;
1108 } else if (!isTrustedCallingUid(callingUid)) {
1109 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1110 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001111 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1112 "Untrusted caller (calling PID %d, UID %d) trying to "
1113 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1114 callingPid, callingUid, cameraId.string(),
1115 clientName8.string(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001116 }
1117
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001118 // Check if we can trust clientPid
1119 if (clientPid == USE_CALLING_PID) {
1120 clientPid = callingPid;
1121 } else if (!isTrustedCallingUid(callingUid)) {
1122 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1123 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001124 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1125 "Untrusted caller (calling PID %d, UID %d) trying to "
1126 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1127 callingPid, callingUid, cameraId.string(),
1128 clientName8.string(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001129 }
1130
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001131 if (shouldRejectSystemCameraConnection(cameraId)) {
1132 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1133 cameraId.c_str());
1134 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
1135 "available", cameraId.string());
1136 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001137 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1138 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1139 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
1140 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
1141 "found while trying to query device kind", cameraId.string());
1142
1143 }
1144
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001145 // If it's not calling from cameraserver, check the permission if the
1146 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1147 // android.permission.SYSTEM_CAMERA for system only camera devices).
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001148 if (callingPid != getpid() &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001149 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001150 !checkPermission(sCameraPermission, clientPid, clientUid)) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001151 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001152 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1153 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
1154 clientName8.string(), clientUid, clientPid, cameraId.string());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001155 }
1156
Svet Ganova453d0d2018-01-11 15:37:58 -08001157 // Make sure the UID is in an active state to use the camera
Svet Ganov7b4ab782018-03-25 12:48:10 -07001158 if (!mUidPolicy->isUidActive(callingUid, String16(clientName8))) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001159 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001160 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1161 clientPid, clientUid);
1162 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001163 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1164 "calling UID %d proc state %" PRId32 ")",
1165 clientName8.string(), clientUid, clientPid, cameraId.string(),
1166 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001167 }
1168
Michael Grooverd1d435a2018-12-18 17:39:42 -08001169 // If sensor privacy is enabled then prevent access to the camera
1170 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1171 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1172 return STATUS_ERROR_FMT(ERROR_DISABLED,
1173 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
1174 "is enabled", clientName8.string(), clientUid, clientPid, cameraId.string());
1175 }
1176
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001177 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1178 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001179 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001180 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001181
Ruben Brunk6267b532015-04-30 17:44:07 -07001182 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001183
Ruben Brunka8ca9152015-04-07 14:23:40 -07001184 // Only allow clients who are being used by the current foreground device user, unless calling
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001185 // from our own process OR the caller is using the cameraserver's HIDL interface.
1186 if (!hardware::IPCThreadState::self()->isServingCall() && callingPid != getpid() &&
1187 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001188 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1189 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
1190 toString(mAllowedUsers).string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001191 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1192 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
1193 clientUserId, cameraId.string());
Ruben Brunk36597b22015-03-20 22:15:57 -07001194 }
1195
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001196 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001197}
1198
1199status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
1200 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001201 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001202 if (cameraState == nullptr) {
1203 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1204 cameraId.string());
1205 return -ENODEV;
1206 }
1207
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001208 StatusInternal currentStatus = cameraState->getStatus();
1209 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001210 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
1211 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001212 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001213 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001214 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
1215 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001216 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001217 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001218
Ruben Brunkcc776712015-02-17 20:18:47 -08001219 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001220}
1221
Ruben Brunkcc776712015-02-17 20:18:47 -08001222void CameraService::finishConnectLocked(const sp<BasicClient>& client,
1223 const CameraService::DescriptorPtr& desc) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001224
Ruben Brunkcc776712015-02-17 20:18:47 -08001225 // Make a descriptor for the incoming client
1226 auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
1227 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1228
1229 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
1230 String8(client->getPackageName()));
1231
1232 if (evicted.size() > 0) {
1233 // This should never happen - clients should already have been removed in disconnect
1234 for (auto& i : evicted) {
1235 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
1236 __FUNCTION__, i->getKey().string());
1237 }
1238
1239 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1240 __FUNCTION__);
1241 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001242
1243 // And register a death notification for the client callback. Do
1244 // this last to avoid Binder policy where a nested Binder
1245 // transaction might be pre-empted to service the client death
1246 // notification if the client process dies before linkToDeath is
1247 // invoked.
1248 sp<IBinder> remoteCallback = client->getRemote();
1249 if (remoteCallback != nullptr) {
1250 remoteCallback->linkToDeath(this);
1251 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001252}
1253
1254status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
1255 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
1256 /*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],
1307 /* isVendorClient won't get copied over*/ false));
Ruben Brunkcc776712015-02-17 20:18:47 -08001308 }
1309 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001310
Ruben Brunkcc776712015-02-17 20:18:47 -08001311 // Get state for the given cameraId
1312 auto state = getCameraState(cameraId);
1313 if (state == nullptr) {
1314 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1315 clientPid, cameraId.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001316 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001317 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001318 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001319
1320 // Make descriptor for incoming client
Shuzhen Wang2db86ff2018-04-25 01:11:17 +00001321 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001322 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1323 state->getConflicting(),
Emilian Peev8131a262017-02-01 12:33:43 +00001324 priorityScores[priorityScores.size() - 1],
1325 clientPid,
1326 states[states.size() - 1]);
Ruben Brunkcc776712015-02-17 20:18:47 -08001327
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001328 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1329
Ruben Brunkcc776712015-02-17 20:18:47 -08001330 // Find clients that would be evicted
1331 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1332
1333 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1334 // background, so we cannot do evictions
1335 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1336 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1337 " priority).", clientPid);
1338
1339 sp<BasicClient> clientSp = clientDescriptor->getValue();
1340 String8 curTime = getFormattedCurrentTime();
1341 auto incompatibleClients =
1342 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1343
1344 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Emilian Peev8131a262017-02-01 12:33:43 +00001345 "(PID %d, score %d state %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001346 cameraId.string(), packageName.string(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001347 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001348
1349 for (auto& i : incompatibleClients) {
1350 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001351 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
1352 i->getKey().string(),
1353 String8{i->getValue()->getPackageName()}.string(),
1354 i->getOwnerId(), i->getPriority().getScore(),
1355 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001356 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00001357 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(),
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001358 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001359 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001360 }
1361
1362 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001363 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001364 mEventLog.add(msg);
1365
1366 return -EBUSY;
1367 }
1368
1369 for (auto& i : evicted) {
1370 sp<BasicClient> clientSp = i->getValue();
1371 if (clientSp.get() == nullptr) {
1372 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1373
1374 // TODO: Remove this
1375 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1376 __FUNCTION__);
1377 mActiveClientManager.remove(i);
1378 continue;
1379 }
1380
1381 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1382 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001383 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001384
Ruben Brunkcc776712015-02-17 20:18:47 -08001385 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001386 logEvent(String8::format("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00001387 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1388 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001389 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
Emilian Peev8131a262017-02-01 12:33:43 +00001390 i->getOwnerId(), i->getPriority().getScore(),
1391 i->getPriority().getState(), cameraId.string(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001392 packageName.string(), clientPid, clientPriority.getScore(),
1393 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08001394
1395 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001396 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001397 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001398 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001399 }
1400
Ruben Brunkcc776712015-02-17 20:18:47 -08001401 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1402 // other clients from connecting in mServiceLockWrapper if held
1403 mServiceLock.unlock();
1404
1405 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07001406 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001407
1408 // Destroy evicted clients
1409 for (auto& i : evictedClients) {
1410 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001411 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001412 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001413
Jayant Chowdhary12361932018-08-27 14:46:13 -07001414 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08001415
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001416 for (const auto& i : evictedClients) {
1417 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1418 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1419 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1420 if (ret == TIMED_OUT) {
1421 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1422 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1423 mActiveClientManager.toString().string());
1424 return -EBUSY;
1425 }
1426 if (ret != NO_ERROR) {
1427 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1428 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1429 ret, mActiveClientManager.toString().string());
1430 return ret;
1431 }
1432 }
1433
1434 evictedClients.clear();
1435
Ruben Brunkcc776712015-02-17 20:18:47 -08001436 // Once clients have been disconnected, relock
1437 mServiceLock.lock();
1438
1439 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1440 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1441 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001442 }
1443
Ruben Brunkcc776712015-02-17 20:18:47 -08001444 *partial = clientDescriptor;
1445 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001446}
1447
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001448Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001449 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001450 int api1CameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001451 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001452 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001453 int clientPid,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001454 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001455 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001456
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001457 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001458 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001459
1460 String8 id = cameraIdIntToStr(api1CameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001461 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001462 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001463 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, std::unique_ptr<String16>(),
1464 clientUid, clientPid, API_1, /*shimUpdateOnly*/ false, /*out*/client);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001465
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001466 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001467 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001468 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001469 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001470 }
1471
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001472 *device = client;
1473 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001474}
1475
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001476Status CameraService::connectLegacy(
Zhijun Heb10cdad2014-06-16 16:38:35 -07001477 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001478 int api1CameraId, int halVersion,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001479 const String16& clientPackageName,
Zhijun Heb10cdad2014-06-16 16:38:35 -07001480 int clientUid,
1481 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001482 sp<ICamera>* device) {
Zhijun Heb10cdad2014-06-16 16:38:35 -07001483
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001484 ATRACE_CALL();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001485 String8 id = cameraIdIntToStr(api1CameraId);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001486
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001487 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001488 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001489 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId, halVersion,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001490 clientPackageName, std::unique_ptr<String16>(), clientUid, USE_CALLING_PID, API_1,
1491 /*shimUpdateOnly*/ false, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001492
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001493 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001494 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001495 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001496 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001497 }
1498
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001499 *device = client;
1500 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001501}
1502
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001503bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
1504 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001505 // If the client is not a vendor client, don't add listener if
1506 // a) the camera is a publicly hidden secure camera OR
1507 // b) the camera is a system only camera and the client doesn't
1508 // have android.permission.SYSTEM_CAMERA permissions.
1509 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
1510 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1511 !hasPermissionsForSystemCamera(clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001512 return true;
1513 }
1514 return false;
1515}
1516
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001517bool CameraService::shouldRejectSystemCameraConnection(const String8& cameraId) const {
1518 // Rules for rejection:
1519 // 1) If cameraserver tries to access this camera device, accept the
1520 // connection.
1521 // 2) The camera device is a publicly hidden secure camera device AND some
1522 // component is trying to access it on a non-hwbinder thread (generally a non HAL client),
1523 // reject it.
1524 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
1525 // and the serving thread is a non hwbinder thread, the client must have
1526 // android.permission.SYSTEM_CAMERA permissions to connect.
1527
1528 int cPid = CameraThreadState::getCallingPid();
1529 int cUid = CameraThreadState::getCallingUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001530 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
1531 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
1532 ALOGE("%s: Invalid camera id %s, ", __FUNCTION__, cameraId.c_str());
1533 return true;
1534 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001535
1536 // (1) Cameraserver trying to connect, accept.
1537 if (CameraThreadState::getCallingPid() == getpid()) {
1538 return false;
1539 }
1540 // (2)
1541 if (!hardware::IPCThreadState::self()->isServingCall() &&
1542 systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
1543 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
1544 return true;
1545 }
1546 // (3) Here we only check for permissions if it is a system only camera device. This is since
1547 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
1548 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
1549 // same behavior for system camera devices.
1550 if (!hardware::IPCThreadState::self()->isServingCall() &&
1551 systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1552 !hasPermissionsForSystemCamera(cPid, cUid)) {
1553 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
1554 cameraId.c_str());
1555 return true;
1556 }
1557
1558 return false;
1559}
1560
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001561Status CameraService::connectDevice(
1562 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001563 const String16& cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001564 const String16& clientPackageName,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001565 const std::unique_ptr<String16>& clientFeatureId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001566 int clientUid,
1567 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001568 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001569
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001570 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001571 Status ret = Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001572 String8 id = String8(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001573 sp<CameraDeviceClient> client = nullptr;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001574 String16 clientPackageNameAdj = clientPackageName;
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001575
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001576 if (hardware::IPCThreadState::self()->isServingCall()) {
1577 std::string vendorClient =
1578 StringPrintf("vendor.client.pid<%d>", CameraThreadState::getCallingPid());
1579 clientPackageNameAdj = String16(vendorClient.c_str());
1580 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001581 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001582 /*api1CameraId*/-1,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001583 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageNameAdj, clientFeatureId,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001584 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08001585
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001586 if(!ret.isOk()) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001587 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageNameAdj),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001588 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001589 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001590 }
1591
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001592 *device = client;
1593 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001594}
1595
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001596template<class CALLBACK, class CLIENT>
1597Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001598 int api1CameraId, int halVersion, const String16& clientPackageName,
1599 const std::unique_ptr<String16>& clientFeatureId, int clientUid, int clientPid,
1600 apiLevel effectiveApiLevel, bool shimUpdateOnly,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001601 /*out*/sp<CLIENT>& device) {
1602 binder::Status ret = binder::Status::ok();
1603
1604 String8 clientName8(clientPackageName);
1605
1606 int originalClientPid = 0;
1607
1608 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) for HAL version %s and "
1609 "Camera API version %d", clientPid, clientName8.string(), cameraId.string(),
1610 (halVersion == -1) ? "default" : std::to_string(halVersion).c_str(),
1611 static_cast<int>(effectiveApiLevel));
1612
1613 sp<CLIENT> client = nullptr;
1614 {
1615 // Acquire mServiceLock and prevent other clients from connecting
1616 std::unique_ptr<AutoConditionLock> lock =
1617 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1618
1619 if (lock == nullptr) {
1620 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
1621 , clientPid);
1622 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1623 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
1624 cameraId.string(), clientName8.string(), clientPid);
1625 }
1626
1627 // Enforce client permissions and do basic sanity checks
1628 if(!(ret = validateConnectLocked(cameraId, clientName8,
1629 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
1630 return ret;
1631 }
1632
1633 // Check the shim parameters after acquiring lock, if they have already been updated and
1634 // we were doing a shim update, return immediately
1635 if (shimUpdateOnly) {
1636 auto cameraState = getCameraState(cameraId);
1637 if (cameraState != nullptr) {
1638 if (!cameraState->getShimParams().isEmpty()) return ret;
1639 }
1640 }
1641
1642 status_t err;
1643
1644 sp<BasicClient> clientTmp = nullptr;
1645 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
1646 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
1647 IInterface::asBinder(cameraCb), clientName8, /*out*/&clientTmp,
1648 /*out*/&partial)) != NO_ERROR) {
1649 switch (err) {
1650 case -ENODEV:
1651 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1652 "No camera device with ID \"%s\" currently available",
1653 cameraId.string());
1654 case -EBUSY:
1655 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1656 "Higher-priority client using camera, ID \"%s\" currently unavailable",
1657 cameraId.string());
1658 default:
1659 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1660 "Unexpected error %s (%d) opening camera \"%s\"",
1661 strerror(-err), err, cameraId.string());
1662 }
1663 }
1664
1665 if (clientTmp.get() != nullptr) {
1666 // Handle special case for API1 MediaRecorder where the existing client is returned
1667 device = static_cast<CLIENT*>(clientTmp.get());
1668 return ret;
1669 }
1670
1671 // give flashlight a chance to close devices if necessary.
1672 mFlashlight->prepareDeviceOpen(cameraId);
1673
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001674 int facing = -1;
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001675 int deviceVersion = getDeviceVersion(cameraId, /*out*/&facing);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08001676 if (facing == -1) {
1677 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.string());
1678 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1679 "Unable to get camera device \"%s\" facing", cameraId.string());
1680 }
1681
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001682 sp<BasicClient> tmp = nullptr;
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001683 if(!(ret = makeClient(this, cameraCb, clientPackageName, clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001684 cameraId, api1CameraId, facing,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001685 clientPid, clientUid, getpid(),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001686 halVersion, deviceVersion, effectiveApiLevel,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001687 /*out*/&tmp)).isOk()) {
1688 return ret;
1689 }
1690 client = static_cast<CLIENT*>(tmp.get());
1691
1692 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
1693 __FUNCTION__);
1694
Emilian Peevbd8c5032018-02-14 23:05:40 +00001695 err = client->initialize(mCameraProviderManager, mMonitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001696 if (err != OK) {
1697 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001698 // Errors could be from the HAL module open call or from AppOpsManager
1699 switch(err) {
1700 case BAD_VALUE:
1701 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1702 "Illegal argument to HAL module for camera \"%s\"", cameraId.string());
1703 case -EBUSY:
1704 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1705 "Camera \"%s\" is already open", cameraId.string());
1706 case -EUSERS:
1707 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1708 "Too many cameras already open, cannot open camera \"%s\"",
1709 cameraId.string());
1710 case PERMISSION_DENIED:
1711 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1712 "No permission to open camera \"%s\"", cameraId.string());
1713 case -EACCES:
1714 return STATUS_ERROR_FMT(ERROR_DISABLED,
1715 "Camera \"%s\" disabled by policy", cameraId.string());
1716 case -ENODEV:
1717 default:
1718 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1719 "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
1720 strerror(-err), err);
1721 }
1722 }
1723
1724 // Update shim paremeters for legacy clients
1725 if (effectiveApiLevel == API_1) {
1726 // Assume we have always received a Client subclass for API1
1727 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
1728 String8 rawParams = shimClient->getParameters();
1729 CameraParameters params(rawParams);
1730
1731 auto cameraState = getCameraState(cameraId);
1732 if (cameraState != nullptr) {
1733 cameraState->setShimParams(params);
1734 } else {
1735 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
1736 __FUNCTION__, cameraId.string());
1737 }
1738 }
1739
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001740 // Set rotate-and-crop override behavior
1741 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
1742 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
1743 }
1744
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001745 if (shimUpdateOnly) {
1746 // If only updating legacy shim parameters, immediately disconnect client
1747 mServiceLock.unlock();
1748 client->disconnect();
1749 mServiceLock.lock();
1750 } else {
1751 // Otherwise, add client to active clients list
1752 finishConnectLocked(client, partial);
1753 }
1754 } // lock is destroyed, allow further connect calls
1755
1756 // Important: release the mutex here so the client can call back into the service from its
1757 // destructor (can be at the end of the call)
1758 device = client;
1759 return ret;
1760}
1761
Emilian Peevb2bc5a42019-11-20 16:02:14 -08001762status_t CameraService::addOfflineClient(String8 cameraId, sp<BasicClient> offlineClient) {
1763 if (offlineClient.get() == nullptr) {
1764 return BAD_VALUE;
1765 }
1766
1767 {
1768 // Acquire mServiceLock and prevent other clients from connecting
1769 std::unique_ptr<AutoConditionLock> lock =
1770 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1771
1772 if (lock == nullptr) {
1773 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
1774 , __FUNCTION__, offlineClient->getClientPid());
1775 return TIMED_OUT;
1776 }
1777
1778 auto onlineClientDesc = mActiveClientManager.get(cameraId);
1779 if (onlineClientDesc.get() == nullptr) {
1780 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
1781 cameraId.c_str());
1782 return BAD_VALUE;
1783 }
1784
1785 // Offline clients do not evict or conflict with other online devices. Resource sharing
1786 // conflicts are handled by the camera provider which will either succeed or fail before
1787 // reaching this method.
1788 const auto& onlinePriority = onlineClientDesc->getPriority();
1789 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
1790 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
1791 /*conflictingKeys*/ std::set<String8>(), onlinePriority.getScore(),
1792 onlineClientDesc->getOwnerId(), onlinePriority.getState());
1793
1794 // Allow only one offline device per camera
1795 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
1796 if (!incompatibleClients.empty()) {
1797 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
1798 return BAD_VALUE;
1799 }
1800
1801 auto err = offlineClient->initialize(mCameraProviderManager, mMonitorTags);
1802 if (err != OK) {
1803 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
1804 return err;
1805 }
1806
1807 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
1808 if (evicted.size() > 0) {
1809 for (auto& i : evicted) {
1810 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
1811 __FUNCTION__, i->getKey().string());
1812 }
1813
1814 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
1815 "properly", __FUNCTION__);
1816
1817 return BAD_VALUE;
1818 }
1819
1820 logConnectedOffline(offlineClientDesc->getKey(),
1821 static_cast<int>(offlineClientDesc->getOwnerId()),
1822 String8(offlineClient->getPackageName()));
1823
1824 sp<IBinder> remoteCallback = offlineClient->getRemote();
1825 if (remoteCallback != nullptr) {
1826 remoteCallback->linkToDeath(this);
1827 }
1828 } // lock is destroyed, allow further connect calls
1829
1830 return OK;
1831}
1832
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001833Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001834 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001835 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001836
1837 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07001838 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001839 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001840 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1841 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001842 }
1843
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001844 String8 id = String8(cameraId.string());
Jayant Chowdhary12361932018-08-27 14:46:13 -07001845 int uid = CameraThreadState::getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001846
1847 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08001848 auto state = getCameraState(id);
1849 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001850 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001851 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1852 "Camera ID \"%s\" is a not valid camera ID", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001853 }
1854
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001855 StatusInternal cameraStatus = state->getStatus();
1856 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001857 cameraStatus != StatusInternal::NOT_AVAILABLE) {
1858 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001859 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1860 "Camera ID \"%s\" is a not valid camera ID", id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001861 }
1862
1863 {
1864 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001865 TorchModeStatus status;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001866 status_t err = getTorchStatusLocked(id, &status);
1867 if (err != OK) {
1868 if (err == NAME_NOT_FOUND) {
1869 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1870 "Camera \"%s\" does not have a flash unit", id.string());
1871 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001872 ALOGE("%s: getting current torch status failed for camera %s",
1873 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001874 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1875 "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
1876 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001877 }
1878
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001879 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001880 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001881 ALOGE("%s: torch mode of camera %s is not available because "
1882 "camera is in use", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001883 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1884 "Torch for camera \"%s\" is not available due to an existing camera user",
1885 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001886 } else {
1887 ALOGE("%s: torch mode of camera %s is not available due to "
1888 "insufficient resources", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001889 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1890 "Torch for camera \"%s\" is not available due to insufficient resources",
1891 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001892 }
1893 }
1894 }
1895
Ruben Brunk99e69712015-05-26 17:25:07 -07001896 {
1897 // Update UID map - this is used in the torch status changed callbacks, so must be done
1898 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07001899 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -07001900 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
1901 mTorchUidMap[id].first = uid;
1902 mTorchUidMap[id].second = uid;
1903 } else {
1904 // Set the pending UID
1905 mTorchUidMap[id].first = uid;
1906 }
1907 }
1908
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001909 status_t err = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07001910
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001911 if (err != OK) {
1912 int32_t errorCode;
1913 String8 msg;
1914 switch (err) {
1915 case -ENOSYS:
1916 msg = String8::format("Camera \"%s\" has no flashlight",
1917 id.string());
1918 errorCode = ERROR_ILLEGAL_ARGUMENT;
1919 break;
1920 default:
1921 msg = String8::format(
1922 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
1923 id.string(), enabled, strerror(-err), err);
1924 errorCode = ERROR_INVALID_OPERATION;
1925 }
1926 ALOGE("%s: %s", __FUNCTION__, msg.string());
1927 return STATUS_ERROR(errorCode, msg.string());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001928 }
1929
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001930 {
1931 // update the link to client's death
1932 Mutex::Autolock al(mTorchClientMapMutex);
1933 ssize_t index = mTorchClientMap.indexOfKey(id);
1934 if (enabled) {
1935 if (index == NAME_NOT_FOUND) {
1936 mTorchClientMap.add(id, clientBinder);
1937 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07001938 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001939 mTorchClientMap.replaceValueAt(index, clientBinder);
1940 }
1941 clientBinder->linkToDeath(this);
1942 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07001943 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001944 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001945 }
1946
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07001947 int clientPid = CameraThreadState::getCallingPid();
1948 const char *id_cstr = id.c_str();
1949 const char *torchState = enabled ? "on" : "off";
1950 ALOGI("Torch for camera id %s turned %s for client PID %d", id_cstr, torchState, clientPid);
1951 logTorchEvent(id_cstr, torchState , clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001952 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001953}
1954
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001955Status CameraService::notifySystemEvent(int32_t eventId,
1956 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001957 const int pid = CameraThreadState::getCallingPid();
1958 const int selfPid = getpid();
1959
1960 // Permission checks
1961 if (pid != selfPid) {
1962 // Ensure we're being called by system_server, or similar process with
1963 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001964 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001965 const int uid = CameraThreadState::getCallingUid();
1966 ALOGE("Permission Denial: cannot send updates to camera service about system"
1967 " events from pid=%d, uid=%d", pid, uid);
1968 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09001969 "No permission to send updates to camera service about system events"
1970 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001971 }
1972 }
1973
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001974 ATRACE_CALL();
1975
Ruben Brunk36597b22015-03-20 22:15:57 -07001976 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001977 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001978 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07001979 // from a system server crash
1980 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08001981 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001982 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07001983 break;
1984 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001985 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07001986 default: {
1987 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
1988 eventId);
1989 break;
1990 }
1991 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001992 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07001993}
1994
Emilian Peev53722fa2019-02-22 17:47:20 -08001995void CameraService::notifyMonitoredUids() {
1996 Mutex::Autolock lock(mStatusListenerLock);
1997
1998 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001999 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Emilian Peev53722fa2019-02-22 17:47:20 -08002000 if (!ret.isOk()) {
2001 ALOGE("%s: Failed to trigger permission callback: %d", __FUNCTION__,
2002 ret.exceptionCode());
2003 }
2004 }
2005}
2006
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002007Status CameraService::notifyDeviceStateChange(int64_t newState) {
2008 const int pid = CameraThreadState::getCallingPid();
2009 const int selfPid = getpid();
2010
2011 // Permission checks
2012 if (pid != selfPid) {
2013 // Ensure we're being called by system_server, or similar process with
2014 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002015 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002016 const int uid = CameraThreadState::getCallingUid();
2017 ALOGE("Permission Denial: cannot send updates to camera service about device"
2018 " state changes from pid=%d, uid=%d", pid, uid);
2019 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2020 "No permission to send updates to camera service about device state"
2021 " changes from pid=%d, uid=%d", pid, uid);
2022 }
2023 }
2024
2025 ATRACE_CALL();
2026
2027 using hardware::camera::provider::V2_5::DeviceState;
2028 hardware::hidl_bitfield<DeviceState> newDeviceState{};
2029 if (newState & ICameraService::DEVICE_STATE_BACK_COVERED) {
2030 newDeviceState |= DeviceState::BACK_COVERED;
2031 }
2032 if (newState & ICameraService::DEVICE_STATE_FRONT_COVERED) {
2033 newDeviceState |= DeviceState::FRONT_COVERED;
2034 }
2035 if (newState & ICameraService::DEVICE_STATE_FOLDED) {
2036 newDeviceState |= DeviceState::FOLDED;
2037 }
2038 // Only map vendor bits directly
2039 uint64_t vendorBits = static_cast<uint64_t>(newState) & 0xFFFFFFFF00000000l;
2040 newDeviceState |= vendorBits;
2041
2042 ALOGV("%s: New device state 0x%" PRIx64, __FUNCTION__, newDeviceState);
2043 Mutex::Autolock l(mServiceLock);
2044 mCameraProviderManager->notifyDeviceStateChange(newDeviceState);
2045
2046 return Status::ok();
2047}
2048
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002049 Status CameraService::getConcurrentStreamingCameraIds(
2050 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
2051 ATRACE_CALL();
2052 if (!concurrentCameraIds) {
2053 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
2054 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
2055 }
2056
2057 if (!mInitialized) {
2058 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2059 return STATUS_ERROR(ERROR_DISCONNECTED,
2060 "Camera subsystem is not available");
2061 }
2062 // First call into the provider and get the set of concurrent camera
2063 // combinations
2064 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
2065 mCameraProviderManager->getConcurrentStreamingCameraIds();
2066 for (auto &combination : concurrentCameraCombinations) {
2067 std::vector<std::string> validCombination;
2068 for (auto &cameraId : combination) {
2069 // if the camera state is not present, skip
2070 String8 cameraIdStr(cameraId.c_str());
2071 auto state = getCameraState(cameraIdStr);
2072 if (state == nullptr) {
2073 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
2074 continue;
2075 }
2076 StatusInternal status = state->getStatus();
2077 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
2078 continue;
2079 }
2080 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
2081 continue;
2082 }
2083 validCombination.push_back(cameraId);
2084 }
2085 if (validCombination.size() != 0) {
2086 concurrentCameraIds->push_back(std::move(validCombination));
2087 }
2088 }
2089 return Status::ok();
2090}
2091
2092Status CameraService::isConcurrentSessionConfigurationSupported(
2093 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
2094 /*out*/bool* isSupported) {
2095 if (!isSupported) {
2096 ALOGE("%s: isSupported is NULL", __FUNCTION__);
2097 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
2098 }
2099
2100 if (!mInitialized) {
2101 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2102 return STATUS_ERROR(ERROR_DISCONNECTED,
2103 "Camera subsystem is not available");
2104 }
2105
2106 // Check for camera permissions
2107 int callingPid = CameraThreadState::getCallingPid();
2108 int callingUid = CameraThreadState::getCallingUid();
2109 if ((callingPid != getpid()) && !checkPermission(sCameraPermission, callingPid, callingUid)) {
2110 ALOGE("%s: pid %d doesn't have camera permissions", __FUNCTION__, callingPid);
2111 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2112 "android.permission.CAMERA needed to call"
2113 "isConcurrentSessionConfigurationSupported");
2114 }
2115
2116 status_t res =
2117 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
2118 cameraIdsAndSessionConfigurations, isSupported);
2119 if (res != OK) {
2120 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
2121 "support %s (%d)", strerror(-res), res);
2122 }
2123 return Status::ok();
2124}
2125
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002126Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
2127 /*out*/
2128 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002129 return addListenerHelper(listener, cameraStatuses);
2130}
2131
2132Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
2133 /*out*/
2134 std::vector<hardware::CameraStatus> *cameraStatuses,
2135 bool isVendorListener) {
2136
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002137 ATRACE_CALL();
2138
Igor Murashkinbfc99152013-02-27 12:55:20 -08002139 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08002140
Ruben Brunk3450ba72015-06-16 11:00:37 -07002141 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002142 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002143 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002144 }
2145
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002146 auto clientUid = CameraThreadState::getCallingUid();
2147 auto clientPid = CameraThreadState::getCallingPid();
2148
Igor Murashkinbfc99152013-02-27 12:55:20 -08002149 Mutex::Autolock lock(mServiceLock);
2150
Ruben Brunkcc776712015-02-17 20:18:47 -08002151 {
2152 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08002153 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002154 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002155 ALOGW("%s: Tried to add listener %p which was already subscribed",
2156 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002157 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08002158 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002159 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002160
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002161 sp<ServiceListener> serviceListener =
2162 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08002163 auto ret = serviceListener->initialize();
2164 if (ret != NO_ERROR) {
2165 String8 msg = String8::format("Failed to initialize service listener: %s (%d)",
2166 strerror(-ret), ret);
2167 ALOGE("%s: %s", __FUNCTION__, msg.string());
2168 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
2169 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002170 // The listener still needs to be added to the list of listeners, regardless of what
2171 // permissions the listener process has / whether it is a vendor listener. Since it might be
2172 // eligible to listen to other camera ids.
2173 mListenerList.emplace_back(serviceListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08002174 mUidPolicy->registerMonitorUid(clientUid);
Igor Murashkinbfc99152013-02-27 12:55:20 -08002175 }
2176
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002177 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07002178 {
Ruben Brunkcc776712015-02-17 20:18:47 -08002179 Mutex::Autolock lock(mCameraStatesLock);
2180 for (auto& i : mCameraStates) {
Shuzhen Wang43858162020-01-10 13:42:15 -08002181 cameraStatuses->emplace_back(i.first,
2182 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds());
Igor Murashkincba2c162013-03-20 15:56:31 -07002183 }
2184 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002185 // Remove the camera statuses that should be hidden from the client, we do
2186 // this after collecting the states in order to avoid holding
2187 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
2188 // the same time.
2189 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
2190 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
2191 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
2192 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
2193 ALOGE("%s: Invalid camera id %s, skipping status update",
2194 __FUNCTION__, s.cameraId.c_str());
2195 return true;
2196 }
2197 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
2198 clientUid);}), cameraStatuses->end());
2199
Igor Murashkincba2c162013-03-20 15:56:31 -07002200
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002201 /*
2202 * Immediately signal current torch status to this listener only
2203 * This may be a subset of all the devices, so don't include it in the response directly
2204 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002205 {
2206 Mutex::Autolock al(mTorchStatusMutex);
2207 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002208 String16 id = String16(mTorchStatusMap.keyAt(i).string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002209 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002210 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002211 }
2212
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002213 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08002214}
Ruben Brunkcc776712015-02-17 20:18:47 -08002215
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002216Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002217 ATRACE_CALL();
2218
Igor Murashkinbfc99152013-02-27 12:55:20 -08002219 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
2220
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002221 if (listener == 0) {
2222 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002223 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002224 }
2225
Igor Murashkinbfc99152013-02-27 12:55:20 -08002226 Mutex::Autolock lock(mServiceLock);
2227
Ruben Brunkcc776712015-02-17 20:18:47 -08002228 {
2229 Mutex::Autolock lock(mStatusListenerLock);
2230 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002231 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
2232 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid());
2233 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08002234 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002235 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002236 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002237 }
2238 }
2239
2240 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
2241 __FUNCTION__, listener.get());
2242
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002243 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08002244}
2245
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002246Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002247
2248 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002249 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
2250
2251 if (parameters == NULL) {
2252 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002253 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07002254 }
2255
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002256 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002257
2258 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002259 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07002260 // Error logged by caller
2261 return ret;
2262 }
2263
2264 String8 shimParamsString8 = shimParams.flatten();
2265 String16 shimParamsString16 = String16(shimParamsString8);
2266
2267 *parameters = shimParamsString16;
2268
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002269 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07002270}
2271
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002272Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
2273 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002274 ATRACE_CALL();
2275
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002276 const String8 id = String8(cameraId);
2277
2278 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002279
2280 switch (apiVersion) {
2281 case API_VERSION_1:
2282 case API_VERSION_2:
2283 break;
2284 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002285 String8 msg = String8::format("Unknown API version %d", apiVersion);
2286 ALOGE("%s: %s", __FUNCTION__, msg.string());
2287 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002288 }
2289
Emilian Peev28ad2ea2017-02-07 16:14:32 +00002290 int deviceVersion = getDeviceVersion(id);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002291 switch (deviceVersion) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002292 case CAMERA_DEVICE_API_VERSION_1_0:
2293 case CAMERA_DEVICE_API_VERSION_3_0:
2294 case CAMERA_DEVICE_API_VERSION_3_1:
2295 if (apiVersion == API_VERSION_2) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002296 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without shim",
2297 __FUNCTION__, id.string(), deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002298 *isSupported = false;
2299 } else { // if (apiVersion == API_VERSION_1) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002300 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always supported",
2301 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002302 *isSupported = true;
2303 }
2304 break;
2305 case CAMERA_DEVICE_API_VERSION_3_2:
2306 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -07002307 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002308 case CAMERA_DEVICE_API_VERSION_3_5:
Yin-Chia Yeh56d98ba2020-01-16 16:57:14 -08002309 case CAMERA_DEVICE_API_VERSION_3_6:
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002310 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
2311 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002312 *isSupported = true;
2313 break;
2314 case -1: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002315 String8 msg = String8::format("Unknown camera ID %s", id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002316 ALOGE("%s: %s", __FUNCTION__, msg.string());
2317 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002318 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002319 default: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002320 String8 msg = String8::format("Unknown device version %x for device %s",
2321 deviceVersion, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002322 ALOGE("%s: %s", __FUNCTION__, msg.string());
2323 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
2324 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07002325 }
2326
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002327 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002328}
2329
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002330Status CameraService::isHiddenPhysicalCamera(const String16& cameraId,
2331 /*out*/ bool *isSupported) {
2332 ATRACE_CALL();
2333
2334 const String8 id = String8(cameraId);
2335
2336 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
2337 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(id.string());
2338
2339 return Status::ok();
2340}
2341
Ruben Brunkcc776712015-02-17 20:18:47 -08002342void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002343 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002344 for (auto& i : mActiveClientManager.getAll()) {
2345 auto clientSp = i->getValue();
2346 if (clientSp.get() == client) {
2347 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08002348 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07002349 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002350 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08002351}
2352
Ruben Brunkcc776712015-02-17 20:18:47 -08002353bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002354 bool ret = false;
2355 {
2356 // Acquire mServiceLock and prevent other clients from connecting
2357 std::unique_ptr<AutoConditionLock> lock =
2358 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08002359
Igor Murashkin634a5152013-02-20 17:15:11 -08002360
Ruben Brunkcc776712015-02-17 20:18:47 -08002361 std::vector<sp<BasicClient>> evicted;
2362 for (auto& i : mActiveClientManager.getAll()) {
2363 auto clientSp = i->getValue();
2364 if (clientSp.get() == nullptr) {
2365 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2366 mActiveClientManager.remove(i);
2367 continue;
2368 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08002369 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002370 mActiveClientManager.remove(i);
2371 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08002372
Ruben Brunkcc776712015-02-17 20:18:47 -08002373 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002374 clientSp->notifyError(
2375 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002376 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08002377 }
2378 }
2379
Ruben Brunkcc776712015-02-17 20:18:47 -08002380 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2381 // other clients from connecting in mServiceLockWrapper if held
2382 mServiceLock.unlock();
2383
Ruben Brunk36597b22015-03-20 22:15:57 -07002384 // Do not clear caller identity, remote caller should be client proccess
2385
Ruben Brunkcc776712015-02-17 20:18:47 -08002386 for (auto& i : evicted) {
2387 if (i.get() != nullptr) {
2388 i->disconnect();
2389 ret = true;
2390 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002391 }
2392
Ruben Brunkcc776712015-02-17 20:18:47 -08002393 // Reacquire mServiceLock
2394 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08002395
Ruben Brunkcc776712015-02-17 20:18:47 -08002396 } // lock is destroyed, allow further connect calls
2397
2398 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07002399}
2400
Ruben Brunkcc776712015-02-17 20:18:47 -08002401std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
2402 const String8& cameraId) const {
2403 std::shared_ptr<CameraState> state;
2404 {
2405 Mutex::Autolock lock(mCameraStatesLock);
2406 auto iter = mCameraStates.find(cameraId);
2407 if (iter != mCameraStates.end()) {
2408 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002409 }
2410 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002411 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002412}
2413
Ruben Brunkcc776712015-02-17 20:18:47 -08002414sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
2415 // Remove from active clients list
2416 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
2417 if (clientDescriptorPtr == nullptr) {
2418 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
2419 cameraId.string());
2420 return sp<BasicClient>{nullptr};
2421 }
2422
2423 return clientDescriptorPtr->getValue();
Keun young Parkd8973a72012-03-28 14:13:09 -07002424}
2425
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002426void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07002427 // Acquire mServiceLock and prevent other clients from connecting
2428 std::unique_ptr<AutoConditionLock> lock =
2429 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
2430
Ruben Brunk6267b532015-04-30 17:44:07 -07002431 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002432 for (size_t i = 0; i < newUserIds.size(); i++) {
2433 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07002434 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002435 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07002436 return;
2437 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002438 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07002439 }
2440
Ruben Brunka8ca9152015-04-07 14:23:40 -07002441
Ruben Brunk6267b532015-04-30 17:44:07 -07002442 if (newAllowedUsers == mAllowedUsers) {
2443 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
2444 return;
2445 }
2446
2447 logUserSwitch(mAllowedUsers, newAllowedUsers);
2448
2449 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07002450
2451 // Current user has switched, evict all current clients.
2452 std::vector<sp<BasicClient>> evicted;
2453 for (auto& i : mActiveClientManager.getAll()) {
2454 auto clientSp = i->getValue();
2455
2456 if (clientSp.get() == nullptr) {
2457 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2458 continue;
2459 }
2460
Ruben Brunk6267b532015-04-30 17:44:07 -07002461 // Don't evict clients that are still allowed.
2462 uid_t clientUid = clientSp->getClientUid();
2463 userid_t clientUserId = multiuser_get_user_id(clientUid);
2464 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
2465 continue;
2466 }
2467
Ruben Brunk36597b22015-03-20 22:15:57 -07002468 evicted.push_back(clientSp);
2469
2470 String8 curTime = getFormattedCurrentTime();
2471
2472 ALOGE("Evicting conflicting client for camera ID %s due to user change",
2473 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07002474
Ruben Brunk36597b22015-03-20 22:15:57 -07002475 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002476 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00002477 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
2478 " to user switch.", i->getKey().string(),
2479 String8{clientSp->getPackageName()}.string(),
2480 i->getOwnerId(), i->getPriority().getScore(),
2481 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07002482
2483 }
2484
2485 // Do not hold mServiceLock while disconnecting clients, but retain the condition
2486 // blocking other clients from connecting in mServiceLockWrapper if held.
2487 mServiceLock.unlock();
2488
2489 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07002490 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07002491
2492 for (auto& i : evicted) {
2493 i->disconnect();
2494 }
2495
Jayant Chowdhary12361932018-08-27 14:46:13 -07002496 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07002497
2498 // Reacquire mServiceLock
2499 mServiceLock.lock();
2500}
Ruben Brunkcc776712015-02-17 20:18:47 -08002501
Ruben Brunka8ca9152015-04-07 14:23:40 -07002502void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002503 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07002504 Mutex::Autolock l(mLogLock);
2505 mEventLog.add(String8::format("%s : %s", curTime.string(), event));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002506}
2507
Ruben Brunka8ca9152015-04-07 14:23:40 -07002508void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002509 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002510 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002511 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002512 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002513}
2514
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002515void CameraService::logDisconnectedOffline(const char* cameraId, int clientPid,
2516 const char* clientPackage) {
2517 // Log the clients evicted
2518 logEvent(String8::format("DISCONNECT offline device %s client for package %s (PID %d)",
2519 cameraId, clientPackage, clientPid));
2520}
2521
Ruben Brunka8ca9152015-04-07 14:23:40 -07002522void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002523 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002524 // Log the clients evicted
2525 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002526 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002527}
2528
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002529void CameraService::logConnectedOffline(const char* cameraId, int clientPid,
2530 const char* clientPackage) {
2531 // Log the clients evicted
2532 logEvent(String8::format("CONNECT offline device %s client for package %s (PID %d)", cameraId,
2533 clientPackage, clientPid));
2534}
2535
Ruben Brunka8ca9152015-04-07 14:23:40 -07002536void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002537 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002538 // Log the client rejected
2539 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002540 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002541}
2542
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002543void CameraService::logTorchEvent(const char* cameraId, const char *torchState, int clientPid) {
2544 // Log torch event
2545 logEvent(String8::format("Torch for camera id %s turned %s for client PID %d", cameraId,
2546 torchState, clientPid));
2547}
2548
Ruben Brunk6267b532015-04-30 17:44:07 -07002549void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
2550 const std::set<userid_t>& newUserIds) {
2551 String8 newUsers = toString(newUserIds);
2552 String8 oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002553 if (oldUsers.size() == 0) {
2554 oldUsers = "<None>";
2555 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07002556 // Log the new and old users
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002557 logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
Ruben Brunk6267b532015-04-30 17:44:07 -07002558 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002559}
2560
2561void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
2562 // Log the device removal
2563 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
2564}
2565
2566void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
2567 // Log the device removal
2568 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
2569}
2570
2571void CameraService::logClientDied(int clientPid, const char* reason) {
2572 // Log the device removal
2573 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07002574}
2575
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002576void CameraService::logServiceError(const char* msg, int errorCode) {
2577 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002578 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002579}
2580
Ruben Brunk36597b22015-03-20 22:15:57 -07002581status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
2582 uint32_t flags) {
2583
Mathias Agopian65ab4712010-07-14 17:59:35 -07002584 // Permission checks
2585 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002586 case SHELL_COMMAND_TRANSACTION: {
2587 int in = data.readFileDescriptor();
2588 int out = data.readFileDescriptor();
2589 int err = data.readFileDescriptor();
2590 int argc = data.readInt32();
2591 Vector<String16> args;
2592 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
2593 args.add(data.readString16());
2594 }
2595 sp<IBinder> unusedCallback;
2596 sp<IResultReceiver> resultReceiver;
2597 status_t status;
2598 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
2599 return status;
2600 }
2601 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
2602 return status;
2603 }
2604 status = shellCommand(in, out, err, args);
2605 if (resultReceiver != nullptr) {
2606 resultReceiver->send(status);
2607 }
2608 return NO_ERROR;
2609 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002610 }
2611
2612 return BnCameraService::onTransact(code, data, reply, flags);
2613}
2614
Mathias Agopian65ab4712010-07-14 17:59:35 -07002615// We share the media players for shutter and recording sound for all clients.
2616// A reference count is kept to determine when we will actually release the
2617// media players.
2618
Jaekyun Seokef498052018-03-23 13:09:44 +09002619sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
2620 sp<MediaPlayer> mp = new MediaPlayer();
2621 status_t error;
2622 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08002623 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09002624 error = mp->prepare();
2625 }
2626 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00002627 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09002628 mp->disconnect();
2629 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002630 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002631 }
2632 return mp;
2633}
2634
username5755fea2018-12-27 09:48:08 +08002635void CameraService::increaseSoundRef() {
2636 Mutex::Autolock lock(mSoundLock);
2637 mSoundRef++;
2638}
2639
2640void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002641 ATRACE_CALL();
2642
username5755fea2018-12-27 09:48:08 +08002643 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
2644 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
2645 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
2646 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
2647 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
2648 }
2649 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
2650 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
2651 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
2652 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002653 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08002654 }
2655 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
2656 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
2657 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
2658 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
2659 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002660 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002661}
2662
username5755fea2018-12-27 09:48:08 +08002663void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002664 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002665 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002666 if (--mSoundRef) return;
2667
2668 for (int i = 0; i < NUM_SOUNDS; i++) {
2669 if (mSoundPlayer[i] != 0) {
2670 mSoundPlayer[i]->disconnect();
2671 mSoundPlayer[i].clear();
2672 }
2673 }
2674}
2675
2676void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002677 ATRACE_CALL();
2678
Mathias Agopian65ab4712010-07-14 17:59:35 -07002679 LOG1("playSound(%d)", kind);
2680 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002681 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002682 sp<MediaPlayer> player = mSoundPlayer[kind];
2683 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08002684 player->seekTo(0);
2685 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002686 }
2687}
2688
2689// ----------------------------------------------------------------------------
2690
2691CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07002692 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002693 const String16& clientPackageName,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002694 const std::unique_ptr<String16>& clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002695 const String8& cameraIdStr,
2696 int api1CameraId, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002697 int clientPid, uid_t clientUid,
2698 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002699 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08002700 IInterface::asBinder(cameraClient),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002701 clientPackageName, clientFeatureId,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002702 cameraIdStr, cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002703 clientPid, clientUid,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002704 servicePid),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002705 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08002706{
Jayant Chowdhary12361932018-08-27 14:46:13 -07002707 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002708 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002709
Igor Murashkin44cfcf02013-03-01 16:22:28 -08002710 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002711
username5755fea2018-12-27 09:48:08 +08002712 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002713
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002714 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002715}
2716
Mathias Agopian65ab4712010-07-14 17:59:35 -07002717// tear down the client
2718CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002719 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08002720 mDestructionStarted = true;
2721
username5755fea2018-12-27 09:48:08 +08002722 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002723 // unconditionally disconnect. function is idempotent
2724 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002725}
2726
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002727sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
2728
Igor Murashkin634a5152013-02-20 17:15:11 -08002729CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002730 const sp<IBinder>& remoteCallback,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002731 const String16& clientPackageName, const std::unique_ptr<String16>& clientFeatureId,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002732 const String8& cameraIdStr, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002733 int clientPid, uid_t clientUid,
2734 int servicePid):
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002735 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002736 mClientPackageName(clientPackageName),
2737 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002738 mServicePid(servicePid),
2739 mDisconnected(false),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002740 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002741 mRemoteBinder(remoteCallback)
Igor Murashkin634a5152013-02-20 17:15:11 -08002742{
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002743 if (clientFeatureId) {
2744 mClientFeatureId = std::unique_ptr<String16>(new String16(*clientFeatureId));
2745 } else {
2746 mClientFeatureId = std::unique_ptr<String16>();
2747 }
2748
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002749 if (sCameraService == nullptr) {
2750 sCameraService = cameraService;
2751 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002752 mOpsActive = false;
Igor Murashkin634a5152013-02-20 17:15:11 -08002753 mDestructionStarted = false;
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08002754
2755 // In some cases the calling code has no access to the package it runs under.
2756 // For example, NDK camera API.
2757 // In this case we will get the packages for the calling UID and pick the first one
2758 // for attributing the app op. This will work correctly for runtime permissions
2759 // as for legacy apps we will toggle the app op for all packages in the UID.
2760 // The caveat is that the operation may be attributed to the wrong package and
2761 // stats based on app ops may be slightly off.
2762 if (mClientPackageName.size() <= 0) {
2763 sp<IServiceManager> sm = defaultServiceManager();
2764 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
2765 if (binder == 0) {
2766 ALOGE("Cannot get permission service");
2767 // Leave mClientPackageName unchanged (empty) and the further interaction
2768 // with camera will fail in BasicClient::startCameraOps
2769 return;
2770 }
2771
2772 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
2773 Vector<String16> packages;
2774
2775 permCtrl->getPackagesForUid(mClientUid, packages);
2776
2777 if (packages.isEmpty()) {
2778 ALOGE("No packages for calling UID");
2779 // Leave mClientPackageName unchanged (empty) and the further interaction
2780 // with camera will fail in BasicClient::startCameraOps
2781 return;
2782 }
2783 mClientPackageName = packages[0];
2784 }
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002785 if (!hardware::IPCThreadState::self()->isServingCall()) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002786 mAppOpsManager = std::make_unique<AppOpsManager>();
2787 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002788}
2789
2790CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002791 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08002792 mDestructionStarted = true;
2793}
2794
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002795binder::Status CameraService::BasicClient::disconnect() {
2796 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002797 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002798 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07002799 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07002800 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002801
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002802 sCameraService->removeByClient(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002803 sCameraService->logDisconnected(mCameraIdStr, mClientPid, String8(mClientPackageName));
Peter Kalauskasa29c1352018-10-10 12:05:42 -07002804 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
2805 mCameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002806
2807 sp<IBinder> remote = getRemote();
2808 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002809 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08002810 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002811
2812 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07002813 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002814 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
2815 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
2816 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002817
Igor Murashkincba2c162013-03-20 15:56:31 -07002818 // client shouldn't be able to call into us anymore
2819 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002820
2821 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08002822}
2823
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002824status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
2825 // No dumping of clients directly over Binder,
2826 // must go through CameraService::dump
2827 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07002828 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002829 return OK;
2830}
2831
Ruben Brunkcc776712015-02-17 20:18:47 -08002832String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002833 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08002834}
2835
2836
2837int CameraService::BasicClient::getClientPid() const {
2838 return mClientPid;
2839}
2840
Ruben Brunk6267b532015-04-30 17:44:07 -07002841uid_t CameraService::BasicClient::getClientUid() const {
2842 return mClientUid;
2843}
2844
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002845bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
2846 // Defaults to API2.
2847 return level == API_2;
2848}
2849
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002850status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002851 {
2852 Mutex::Autolock l(mAudioRestrictionLock);
2853 mAudioRestriction = mode;
2854 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002855 sCameraService->updateAudioRestriction();
2856 return OK;
2857}
2858
2859int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002860 return sCameraService->updateAudioRestriction();
2861}
2862
2863int32_t CameraService::BasicClient::getAudioRestriction() const {
2864 Mutex::Autolock l(mAudioRestrictionLock);
2865 return mAudioRestriction;
2866}
2867
2868bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
2869 switch (mode) {
2870 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
2871 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
2872 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
2873 return true;
2874 default:
2875 return false;
2876 }
2877}
2878
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002879status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002880 ATRACE_CALL();
2881
Igor Murashkine6800ce2013-03-04 17:25:57 -08002882 {
2883 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002884 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08002885 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002886 if (mAppOpsManager != nullptr) {
2887 // Notify app ops that the camera is not available
2888 mOpsCallback = new OpsCallback(this);
2889 int32_t res;
2890 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
2891 mClientPackageName, mOpsCallback);
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002892 res = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
2893 mClientPackageName, /*startIfModeDefault*/ false, mClientFeatureId,
2894 String16("start camera ") + String16(mCameraIdStr));
Igor Murashkine6800ce2013-03-04 17:25:57 -08002895
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002896 if (res == AppOpsManager::MODE_ERRORED) {
2897 ALOGI("Camera %s: Access for \"%s\" has been revoked",
2898 mCameraIdStr.string(), String8(mClientPackageName).string());
2899 return PERMISSION_DENIED;
2900 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002901
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002902 if (res == AppOpsManager::MODE_IGNORED) {
2903 ALOGI("Camera %s: Access for \"%s\" has been restricted",
2904 mCameraIdStr.string(), String8(mClientPackageName).string());
2905 // Return the same error as for device policy manager rejection
2906 return -EACCES;
2907 }
Svetoslav28e8ef72015-05-11 19:21:31 -07002908 }
2909
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002910 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002911
2912 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002913 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002914
Emilian Peev573291c2018-02-10 02:10:56 +00002915 int apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_1;
2916 if (canCastToApiClient(API_2)) {
2917 apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_2;
2918 }
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002919 // Transition device state to OPEN
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002920 sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_OPEN,
Emilian Peev573291c2018-02-10 02:10:56 +00002921 mCameraIdStr, mCameraFacing, mClientPackageName, apiLevel);
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002922
Emilian Peev53722fa2019-02-22 17:47:20 -08002923 sCameraService->mUidPolicy->registerMonitorUid(mClientUid);
2924
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002925 return OK;
2926}
2927
2928status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002929 ATRACE_CALL();
2930
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002931 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002932 if (mOpsActive) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002933 // Notify app ops that the camera is available again
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002934 if (mAppOpsManager != nullptr) {
2935 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002936 mClientPackageName, mClientFeatureId);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002937 mOpsActive = false;
2938 }
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002939 // This function is called when a client disconnects. This should
2940 // release the camera, but actually only if it was in a proper
2941 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002942 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002943 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002944
Ruben Brunkcc776712015-02-17 20:18:47 -08002945 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002946 sCameraService->updateStatus(StatusInternal::PRESENT,
2947 mCameraIdStr, rejected);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002948
Emilian Peev573291c2018-02-10 02:10:56 +00002949 int apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_1;
2950 if (canCastToApiClient(API_2)) {
2951 apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_2;
2952 }
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002953 // Transition device state to CLOSED
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002954 sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_CLOSED,
Emilian Peev573291c2018-02-10 02:10:56 +00002955 mCameraIdStr, mCameraFacing, mClientPackageName, apiLevel);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002956 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002957 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002958 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
2959 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002960 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002961 mOpsCallback.clear();
2962
Emilian Peev53722fa2019-02-22 17:47:20 -08002963 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid);
2964
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002965 return OK;
2966}
2967
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002968void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002969 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002970 if (mAppOpsManager == nullptr) {
2971 return;
2972 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002973 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002974 if (op != AppOpsManager::OP_CAMERA) {
2975 ALOGW("Unexpected app ops notification received: %d", op);
2976 return;
2977 }
2978
2979 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002980 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002981 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002982 ALOGV("checkOp returns: %d, %s ", res,
2983 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
2984 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
2985 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
2986 "UNKNOWN");
2987
2988 if (res != AppOpsManager::MODE_ALLOWED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002989 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002990 String8(mClientPackageName).string());
Svet Ganova453d0d2018-01-11 15:37:58 -08002991 block();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002992 }
2993}
2994
Svet Ganova453d0d2018-01-11 15:37:58 -08002995void CameraService::BasicClient::block() {
2996 ATRACE_CALL();
2997
2998 // Reset the client PID to allow server-initiated disconnect,
2999 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003000 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08003001 CaptureResultExtras resultExtras; // a dummy result (invalid)
3002 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
3003 disconnect();
3004}
3005
Mathias Agopian65ab4712010-07-14 17:59:35 -07003006// ----------------------------------------------------------------------------
3007
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003008void CameraService::Client::notifyError(int32_t errorCode,
Jianing Weicb0652e2014-03-12 18:29:36 -07003009 const CaptureResultExtras& resultExtras) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08003010 (void) resultExtras;
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003011 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07003012 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
3013 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
3014 api1ErrorCode = CAMERA_ERROR_DISABLED;
3015 }
3016 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003017 } else {
3018 ALOGE("mRemoteCallback is NULL!!");
3019 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003020}
3021
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003022// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003023binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003024 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003025 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08003026}
3027
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003028bool CameraService::Client::canCastToApiClient(apiLevel level) const {
3029 return level == API_1;
3030}
3031
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003032CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
3033 mClient(client) {
3034}
3035
3036void CameraService::Client::OpsCallback::opChanged(int32_t op,
3037 const String16& packageName) {
3038 sp<BasicClient> client = mClient.promote();
3039 if (client != NULL) {
3040 client->opChanged(op, packageName);
3041 }
3042}
3043
Mathias Agopian65ab4712010-07-14 17:59:35 -07003044// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08003045// UidPolicy
3046// ----------------------------------------------------------------------------
3047
3048void CameraService::UidPolicy::registerSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003049 Mutex::Autolock _l(mUidLock);
3050
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003051 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07003052 status_t res = mAm.linkToDeath(this);
3053 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08003054 | ActivityManager::UID_OBSERVER_IDLE
Emilian Peev53722fa2019-02-22 17:47:20 -08003055 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganova453d0d2018-01-11 15:37:58 -08003056 ActivityManager::PROCESS_STATE_UNKNOWN,
3057 String16("cameraserver"));
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003058 if (res == OK) {
3059 mRegistered = true;
3060 ALOGV("UidPolicy: Registered with ActivityManager");
3061 }
Svet Ganova453d0d2018-01-11 15:37:58 -08003062}
3063
3064void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003065 Mutex::Autolock _l(mUidLock);
3066
Steven Moreland2f348142019-07-02 15:59:07 -07003067 mAm.unregisterUidObserver(this);
3068 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003069 mRegistered = false;
3070 mActiveUids.clear();
3071 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08003072}
3073
3074void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
3075 onUidIdle(uid, disabled);
3076}
3077
3078void CameraService::UidPolicy::onUidActive(uid_t uid) {
3079 Mutex::Autolock _l(mUidLock);
3080 mActiveUids.insert(uid);
3081}
3082
3083void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
3084 bool deleted = false;
3085 {
3086 Mutex::Autolock _l(mUidLock);
3087 if (mActiveUids.erase(uid) > 0) {
3088 deleted = true;
3089 }
3090 }
3091 if (deleted) {
3092 sp<CameraService> service = mService.promote();
3093 if (service != nullptr) {
3094 service->blockClientsForUid(uid);
3095 }
3096 }
3097}
3098
Emilian Peev53722fa2019-02-22 17:47:20 -08003099void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07003100 int64_t procStateSeq __unused, int32_t capability __unused) {
Emilian Peev53722fa2019-02-22 17:47:20 -08003101 bool procStateChange = false;
3102 {
3103 Mutex::Autolock _l(mUidLock);
3104 if ((mMonitoredUids.find(uid) != mMonitoredUids.end()) &&
3105 (mMonitoredUids[uid].first != procState)) {
3106 mMonitoredUids[uid].first = procState;
3107 procStateChange = true;
3108 }
3109 }
3110
3111 if (procStateChange) {
3112 sp<CameraService> service = mService.promote();
3113 if (service != nullptr) {
3114 service->notifyMonitoredUids();
3115 }
3116 }
3117}
3118
3119void CameraService::UidPolicy::registerMonitorUid(uid_t uid) {
3120 Mutex::Autolock _l(mUidLock);
3121 auto it = mMonitoredUids.find(uid);
3122 if (it != mMonitoredUids.end()) {
3123 it->second.second++;
3124 } else {
3125 mMonitoredUids.emplace(
3126 std::pair<uid_t, std::pair<int32_t, size_t>> (uid,
3127 std::pair<int32_t, size_t> (ActivityManager::PROCESS_STATE_NONEXISTENT, 1)));
3128 }
3129}
3130
3131void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid) {
3132 Mutex::Autolock _l(mUidLock);
3133 auto it = mMonitoredUids.find(uid);
3134 if (it != mMonitoredUids.end()) {
3135 it->second.second--;
3136 if (it->second.second == 0) {
3137 mMonitoredUids.erase(it);
3138 }
3139 } else {
3140 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
3141 }
3142}
3143
Svet Ganov7b4ab782018-03-25 12:48:10 -07003144bool CameraService::UidPolicy::isUidActive(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003145 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003146 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003147}
3148
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003149static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
3150static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003151
Svet Ganov7b4ab782018-03-25 12:48:10 -07003152bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003153 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003154 // If activity manager is unreachable, assume everything is active
3155 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003156 return true;
3157 }
3158 auto it = mOverrideUids.find(uid);
3159 if (it != mOverrideUids.end()) {
3160 return it->second;
3161 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003162 bool active = mActiveUids.find(uid) != mActiveUids.end();
3163 if (!active) {
3164 // We want active UIDs to always access camera with their first attempt since
3165 // there is no guarantee the app is robustly written and would retry getting
3166 // the camera on failure. The inverse case is not a problem as we would take
3167 // camera away soon once we get the callback that the uid is no longer active.
3168 ActivityManager am;
3169 // Okay to access with a lock held as UID changes are dispatched without
3170 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07003171 int64_t startTimeMillis = 0;
3172 do {
3173 // TODO: Fix this b/109950150!
3174 // Okay this is a hack. There is a race between the UID turning active and
3175 // activity being resumed. The proper fix is very risky, so we temporary add
3176 // some polling which should happen pretty rarely anyway as the race is hard
3177 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003178 active = mActiveUids.find(uid) != mActiveUids.end();
3179 if (!active) active = am.isUidActive(uid, callingPackage);
Svet Ganov94ec46f2018-06-08 15:03:46 -07003180 if (active) {
3181 break;
3182 }
3183 if (startTimeMillis <= 0) {
3184 startTimeMillis = uptimeMillis();
3185 }
3186 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003187 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003188 if (remainingTimeMillis <= 0) {
3189 break;
3190 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003191 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
3192
3193 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003194 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003195 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003196 } while (true);
3197
Svet Ganov7b4ab782018-03-25 12:48:10 -07003198 if (active) {
3199 // Now that we found out the UID is actually active, cache that
3200 mActiveUids.insert(uid);
3201 }
3202 }
3203 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08003204}
3205
Varun Shahb42f1eb2019-04-16 14:45:13 -07003206int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
3207 Mutex::Autolock _l(mUidLock);
3208 return getProcStateLocked(uid);
3209}
3210
3211int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
3212 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
3213 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
3214 procState = mMonitoredUids[uid].first;
3215 }
3216 return procState;
3217}
3218
Svet Ganov7b4ab782018-03-25 12:48:10 -07003219void CameraService::UidPolicy::UidPolicy::addOverrideUid(uid_t uid,
3220 String16 callingPackage, bool active) {
3221 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08003222}
3223
Svet Ganov7b4ab782018-03-25 12:48:10 -07003224void CameraService::UidPolicy::removeOverrideUid(uid_t uid, String16 callingPackage) {
3225 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08003226}
3227
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003228void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
3229 Mutex::Autolock _l(mUidLock);
3230 ALOGV("UidPolicy: ActivityManager has died");
3231 mRegistered = false;
3232 mActiveUids.clear();
3233}
3234
Svet Ganov7b4ab782018-03-25 12:48:10 -07003235void CameraService::UidPolicy::updateOverrideUid(uid_t uid, String16 callingPackage,
3236 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003237 bool wasActive = false;
3238 bool isActive = false;
3239 {
3240 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003241 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003242 mOverrideUids.erase(uid);
3243 if (insert) {
3244 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
3245 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003246 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003247 }
3248 if (wasActive != isActive && !isActive) {
3249 sp<CameraService> service = mService.promote();
3250 if (service != nullptr) {
3251 service->blockClientsForUid(uid);
3252 }
3253 }
3254}
3255
3256// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08003257// SensorPrivacyPolicy
3258// ----------------------------------------------------------------------------
3259void CameraService::SensorPrivacyPolicy::registerSelf() {
3260 Mutex::Autolock _l(mSensorPrivacyLock);
3261 if (mRegistered) {
3262 return;
3263 }
Steven Moreland3cf67172020-01-29 11:44:22 -08003264 mSpm.addSensorPrivacyListener(this);
3265 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
3266 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003267 if (res == OK) {
3268 mRegistered = true;
3269 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
3270 }
3271}
3272
3273void CameraService::SensorPrivacyPolicy::unregisterSelf() {
3274 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08003275 mSpm.removeSensorPrivacyListener(this);
3276 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003277 mRegistered = false;
3278 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
3279}
3280
3281bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
3282 Mutex::Autolock _l(mSensorPrivacyLock);
3283 return mSensorPrivacyEnabled;
3284}
3285
3286binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
3287 {
3288 Mutex::Autolock _l(mSensorPrivacyLock);
3289 mSensorPrivacyEnabled = enabled;
3290 }
3291 // if sensor privacy is enabled then block all clients from accessing the camera
3292 if (enabled) {
3293 sp<CameraService> service = mService.promote();
3294 if (service != nullptr) {
3295 service->blockAllClients();
3296 }
3297 }
3298 return binder::Status::ok();
3299}
3300
3301void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
3302 Mutex::Autolock _l(mSensorPrivacyLock);
3303 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
3304 mRegistered = false;
3305}
3306
3307// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003308// CameraState
3309// ----------------------------------------------------------------------------
3310
3311CameraService::CameraState::CameraState(const String8& id, int cost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003312 const std::set<String8>& conflicting, SystemCameraKind systemCameraKind) : mId(id),
3313 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
3314 mSystemCameraKind(systemCameraKind) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08003315
3316CameraService::CameraState::~CameraState() {}
3317
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003318CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003319 Mutex::Autolock lock(mStatusLock);
3320 return mStatus;
3321}
3322
Shuzhen Wang43858162020-01-10 13:42:15 -08003323std::vector<String8> CameraService::CameraState::getUnavailablePhysicalIds() const {
3324 Mutex::Autolock lock(mStatusLock);
3325 std::vector<String8> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
3326 return res;
3327}
3328
Ruben Brunkcc776712015-02-17 20:18:47 -08003329CameraParameters CameraService::CameraState::getShimParams() const {
3330 return mShimParams;
3331}
3332
3333void CameraService::CameraState::setShimParams(const CameraParameters& params) {
3334 mShimParams = params;
3335}
3336
3337int CameraService::CameraState::getCost() const {
3338 return mCost;
3339}
3340
3341std::set<String8> CameraService::CameraState::getConflicting() const {
3342 return mConflicting;
3343}
3344
3345String8 CameraService::CameraState::getId() const {
3346 return mId;
3347}
3348
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003349SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
3350 return mSystemCameraKind;
3351}
3352
Shuzhen Wang43858162020-01-10 13:42:15 -08003353bool CameraService::CameraState::addUnavailablePhysicalId(const String8& physicalId) {
3354 Mutex::Autolock lock(mStatusLock);
3355 auto result = mUnavailablePhysicalIds.insert(physicalId);
3356 return result.second;
3357}
3358
3359bool CameraService::CameraState::removeUnavailablePhysicalId(const String8& physicalId) {
3360 Mutex::Autolock lock(mStatusLock);
3361 auto count = mUnavailablePhysicalIds.erase(physicalId);
3362 return count > 0;
3363}
3364
Ruben Brunkcc776712015-02-17 20:18:47 -08003365// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07003366// ClientEventListener
3367// ----------------------------------------------------------------------------
3368
3369void CameraService::ClientEventListener::onClientAdded(
3370 const resource_policy::ClientDescriptor<String8,
3371 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003372 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003373 if (basicClient.get() != nullptr) {
3374 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3375 notifier.noteStartCamera(descriptor.getKey(),
3376 static_cast<int>(basicClient->getClientUid()));
3377 }
3378}
3379
3380void CameraService::ClientEventListener::onClientRemoved(
3381 const resource_policy::ClientDescriptor<String8,
3382 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003383 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003384 if (basicClient.get() != nullptr) {
3385 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3386 notifier.noteStopCamera(descriptor.getKey(),
3387 static_cast<int>(basicClient->getClientUid()));
3388 }
3389}
3390
3391
3392// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003393// CameraClientManager
3394// ----------------------------------------------------------------------------
3395
Ruben Brunk99e69712015-05-26 17:25:07 -07003396CameraService::CameraClientManager::CameraClientManager() {
3397 setListener(std::make_shared<ClientEventListener>());
3398}
3399
Ruben Brunkcc776712015-02-17 20:18:47 -08003400CameraService::CameraClientManager::~CameraClientManager() {}
3401
3402sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
3403 const String8& id) const {
3404 auto descriptor = get(id);
3405 if (descriptor == nullptr) {
3406 return sp<BasicClient>{nullptr};
3407 }
3408 return descriptor->getValue();
3409}
3410
3411String8 CameraService::CameraClientManager::toString() const {
3412 auto all = getAll();
3413 String8 ret("[");
3414 bool hasAny = false;
3415 for (auto& i : all) {
3416 hasAny = true;
3417 String8 key = i->getKey();
3418 int32_t cost = i->getCost();
3419 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00003420 int32_t score = i->getPriority().getScore();
3421 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08003422 auto conflicting = i->getConflicting();
3423 auto clientSp = i->getValue();
3424 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07003425 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08003426 if (clientSp.get() != nullptr) {
3427 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07003428 uid_t clientUid = clientSp->getClientUid();
3429 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003430 }
Emilian Peev8131a262017-02-01 12:33:43 +00003431 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
3432 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08003433
Ruben Brunk6267b532015-04-30 17:44:07 -07003434 if (clientSp.get() != nullptr) {
3435 ret.appendFormat("User Id: %d, ", clientUserId);
3436 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003437 if (packageName.size() != 0) {
3438 ret.appendFormat("Client Package Name: %s", packageName.string());
3439 }
3440
3441 ret.append(", Conflicting Client Devices: {");
3442 for (auto& j : conflicting) {
3443 ret.appendFormat("%s, ", j.string());
3444 }
3445 ret.append("})");
3446 }
3447 if (hasAny) ret.append("\n");
3448 ret.append("]\n");
3449 return ret;
3450}
3451
3452CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3453 const String8& key, const sp<BasicClient>& value, int32_t cost,
Emilian Peev8131a262017-02-01 12:33:43 +00003454 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
3455 int32_t state) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003456
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003457 bool isVendorClient = hardware::IPCThreadState::self()->isServingCall();
3458 int32_t score_adj = isVendorClient ? kVendorClientScore : score;
3459 int32_t state_adj = isVendorClient ? kVendorClientState: state;
3460
Ruben Brunkcc776712015-02-17 20:18:47 -08003461 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003462 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj, isVendorClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08003463}
3464
3465CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3466 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
3467 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00003468 partial->getConflicting(), partial->getPriority().getScore(),
3469 partial->getOwnerId(), partial->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08003470}
3471
3472// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07003473
3474static const int kDumpLockRetries = 50;
3475static const int kDumpLockSleep = 60000;
3476
3477static bool tryLock(Mutex& mutex)
3478{
3479 bool locked = false;
3480 for (int i = 0; i < kDumpLockRetries; ++i) {
3481 if (mutex.tryLock() == NO_ERROR) {
3482 locked = true;
3483 break;
3484 }
3485 usleep(kDumpLockSleep);
3486 }
3487 return locked;
3488}
3489
3490status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003491 ATRACE_CALL();
3492
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003493 if (checkCallingPermission(sDumpPermission) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003494 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07003495 CameraThreadState::getCallingPid(),
3496 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003497 return NO_ERROR;
3498 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003499 bool locked = tryLock(mServiceLock);
3500 // failed to lock - CameraService is probably deadlocked
3501 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003502 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003503 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003504
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003505 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003506 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07003507
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003508 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003509 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08003510
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003511 if (locked) mServiceLock.unlock();
3512 return NO_ERROR;
3513 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003514 dprintf(fd, "\n== Service global info: ==\n\n");
3515 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003516 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07003517 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
3518 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003519 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
3520 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
3521 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003522 String8 activeClientString = mActiveClientManager.toString();
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003523 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
3524 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003525
3526 dumpEventLog(fd);
3527
3528 bool stateLocked = tryLock(mCameraStatesLock);
3529 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003530 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003531 }
3532
Emilian Peevbd8c5032018-02-14 23:05:40 +00003533 int argSize = args.size();
3534 for (int i = 0; i < argSize; i++) {
3535 if (args[i] == TagMonitor::kMonitorOption) {
3536 if (i + 1 < argSize) {
3537 mMonitorTags = String8(args[i + 1]);
3538 }
3539 break;
3540 }
3541 }
3542
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003543 for (auto& state : mCameraStates) {
3544 String8 cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003545
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003546 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003547
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003548 CameraParameters p = state.second->getShimParams();
3549 if (!p.isEmpty()) {
3550 dprintf(fd, " Camera1 API shim is using parameters:\n ");
3551 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003552 }
3553
3554 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08003555 if (clientDescriptor != nullptr) {
3556 dprintf(fd, " Device %s is open. Client instance dump:\n",
3557 cameraId.string());
3558 dprintf(fd, " Client priority score: %d state: %d\n",
3559 clientDescriptor->getPriority().getScore(),
3560 clientDescriptor->getPriority().getState());
3561 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
3562
3563 auto client = clientDescriptor->getValue();
3564 dprintf(fd, " Client package: %s\n",
3565 String8(client->getPackageName()).string());
3566
3567 client->dumpClient(fd, args);
3568 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003569 dprintf(fd, " Device %s is closed, no client instance\n",
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003570 cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003571 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003572
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003573 }
3574
3575 if (stateLocked) mCameraStatesLock.unlock();
3576
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003577 if (locked) mServiceLock.unlock();
3578
Emilian Peevf53f66e2017-04-11 14:29:43 +01003579 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003580
3581 dprintf(fd, "\n== Vendor tags: ==\n\n");
3582
3583 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
3584 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00003585 sp<VendorTagDescriptorCache> cache =
3586 VendorTagDescriptorCache::getGlobalVendorTagCache();
3587 if (cache == NULL) {
3588 dprintf(fd, "No vendor tags.\n");
3589 } else {
3590 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
3591 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003592 } else {
3593 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
3594 }
3595
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003596 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003597 dprintf(fd, "\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003598 camera3::CameraTraces::dump(fd, args);
3599
3600 // Process dump arguments, if any
3601 int n = args.size();
3602 String16 verboseOption("-v");
3603 String16 unreachableOption("--unreachable");
3604 for (int i = 0; i < n; i++) {
3605 if (args[i] == verboseOption) {
3606 // change logging level
3607 if (i + 1 >= n) continue;
3608 String8 levelStr(args[i+1]);
3609 int level = atoi(levelStr.string());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003610 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003611 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003612 } else if (args[i] == unreachableOption) {
3613 // Dump memory analysis
3614 // TODO - should limit be an argument parameter?
3615 UnreachableMemoryInfo info;
3616 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
3617 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003618 dprintf(fd, "\n== Unable to dump unreachable memory. "
3619 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003620 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003621 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003622 std::string s = info.ToString(/*log_contents*/ true);
3623 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003624 }
3625 }
3626 }
3627 return NO_ERROR;
3628}
3629
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003630void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003631 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003632
3633 Mutex::Autolock l(mLogLock);
3634 for (const auto& msg : mEventLog) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003635 dprintf(fd, " %s\n", msg.string());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003636 }
3637
3638 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003639 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003640 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003641 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003642 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003643 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003644}
3645
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003646void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003647 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003648 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
3649 if (mTorchClientMap[i] == who) {
3650 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003651 String8 cameraId = mTorchClientMap.keyAt(i);
3652 status_t res = mFlashlight->setTorchMode(cameraId, false);
3653 if (res) {
3654 ALOGE("%s: torch client died but couldn't turn off torch: "
3655 "%s (%d)", __FUNCTION__, strerror(-res), res);
3656 return;
3657 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003658 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003659 break;
3660 }
3661 }
3662}
3663
Ruben Brunkcc776712015-02-17 20:18:47 -08003664/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003665
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003666 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07003667 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
3668 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003669 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003670 // PID here is approximate and can be wrong.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003671 logClientDied(CameraThreadState::getCallingPid(), String8("Binder died unexpectedly"));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003672
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003673 // check torch client
3674 handleTorchClientBinderDied(who);
3675
3676 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08003677 if(!evictClientIdByRemote(who)) {
3678 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003679 return;
3680 }
3681
Ruben Brunkcc776712015-02-17 20:18:47 -08003682 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
3683 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003684}
3685
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003686void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003687 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08003688}
3689
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003690void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
3691 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003692 // Do not lock mServiceLock here or can get into a deadlock from
3693 // connect() -> disconnect -> updateStatus
3694
3695 auto state = getCameraState(cameraId);
3696
3697 if (state == nullptr) {
3698 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
3699 cameraId.string());
3700 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07003701 }
3702
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003703 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
3704 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3705 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3706 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
3707 return;
3708 }
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003709 bool supportsHAL3 = false;
3710 // supportsCameraApi also holds mInterfaceMutex, we can't call it in the
3711 // HIDL onStatusChanged wrapper call (we'll hold mStatusListenerLock and
3712 // mInterfaceMutex together, which can lead to deadlocks)
3713 binder::Status sRet =
3714 supportsCameraApi(String16(cameraId), hardware::ICameraService::API_VERSION_2,
3715 &supportsHAL3);
3716 if (!sRet.isOk()) {
3717 ALOGW("%s: Failed to determine if device supports HAL3 %s, supportsCameraApi call failed",
3718 __FUNCTION__, cameraId.string());
3719 return;
3720 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003721 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08003722 // of the listeners with both the mStatusLock and mStatusListenerLock held
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003723 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind, &supportsHAL3]
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003724 (const String8& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003725
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003726 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003727 // Update torch status if it has a flash unit.
3728 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003729 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003730 if (getTorchStatusLocked(cameraId, &torchStatus) !=
3731 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003732 TorchModeStatus newTorchStatus =
3733 status == StatusInternal::PRESENT ?
3734 TorchModeStatus::AVAILABLE_OFF :
3735 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003736 if (torchStatus != newTorchStatus) {
3737 onTorchStatusChangedLocked(cameraId, newTorchStatus);
3738 }
3739 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003740 }
3741
3742 Mutex::Autolock lock(mStatusListenerLock);
3743
Shuzhen Wang43858162020-01-10 13:42:15 -08003744 notifyPhysicalCameraStatusLocked(mapToInterface(status), cameraId);
3745
Ruben Brunkcc776712015-02-17 20:18:47 -08003746 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003747 bool isVendorListener = listener->isVendorListener();
3748 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
3749 listener->getListenerPid(), listener->getListenerUid()) ||
3750 (isVendorListener && !supportsHAL3)) {
3751 ALOGV("Skipping discovery callback for system-only camera/HAL1 device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003752 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003753 continue;
3754 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003755 listener->getListener()->onStatusChanged(mapToInterface(status),
Emilian Peev53722fa2019-02-22 17:47:20 -08003756 String16(cameraId));
Ruben Brunkcc776712015-02-17 20:18:47 -08003757 }
3758 });
Igor Murashkincba2c162013-03-20 15:56:31 -07003759}
3760
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003761template<class Func>
3762void CameraService::CameraState::updateStatus(StatusInternal status,
3763 const String8& cameraId,
3764 std::initializer_list<StatusInternal> rejectSourceStates,
3765 Func onStatusUpdatedLocked) {
3766 Mutex::Autolock lock(mStatusLock);
3767 StatusInternal oldStatus = mStatus;
3768 mStatus = status;
3769
3770 if (oldStatus == status) {
3771 return;
3772 }
3773
3774 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
3775 cameraId.string(), oldStatus, status);
3776
3777 if (oldStatus == StatusInternal::NOT_PRESENT &&
3778 (status != StatusInternal::PRESENT &&
3779 status != StatusInternal::ENUMERATING)) {
3780
3781 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
3782 __FUNCTION__);
3783 mStatus = oldStatus;
3784 return;
3785 }
3786
3787 /**
3788 * Sometimes we want to conditionally do a transition.
3789 * For example if a client disconnects, we want to go to PRESENT
3790 * only if we weren't already in NOT_PRESENT or ENUMERATING.
3791 */
3792 for (auto& rejectStatus : rejectSourceStates) {
3793 if (oldStatus == rejectStatus) {
3794 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
3795 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
3796 mStatus = oldStatus;
3797 return;
3798 }
3799 }
3800
3801 onStatusUpdatedLocked(cameraId, status);
3802}
3803
Eino-Ville Talvalae8c96c72017-06-27 12:24:07 -07003804void CameraService::updateProxyDeviceState(int newState,
Emilian Peev573291c2018-02-10 02:10:56 +00003805 const String8& cameraId, int facing, const String16& clientName, int apiLevel) {
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07003806 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
3807 if (proxyBinder == nullptr) return;
3808 String16 id(cameraId);
Emilian Peev573291c2018-02-10 02:10:56 +00003809 proxyBinder->notifyCameraState(id, newState, facing, clientName, apiLevel);
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07003810}
3811
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003812status_t CameraService::getTorchStatusLocked(
3813 const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003814 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003815 if (!status) {
3816 return BAD_VALUE;
3817 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003818 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3819 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003820 // invalid camera ID or the camera doesn't have a flash unit
3821 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003822 }
3823
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003824 *status = mTorchStatusMap.valueAt(index);
3825 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003826}
3827
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003828status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003829 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003830 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3831 if (index == NAME_NOT_FOUND) {
3832 return BAD_VALUE;
3833 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003834 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003835
3836 return OK;
3837}
3838
Shuzhen Wang43858162020-01-10 13:42:15 -08003839void CameraService::notifyPhysicalCameraStatusLocked(int32_t status, const String8& cameraId) {
3840 Mutex::Autolock lock(mCameraStatesLock);
3841 for (const auto& state : mCameraStates) {
3842 std::vector<std::string> physicalCameraIds;
3843 if (!mCameraProviderManager->isLogicalCamera(state.first.c_str(), &physicalCameraIds)) {
3844 // This is not a logical multi-camera.
3845 continue;
3846 }
3847 if (std::find(physicalCameraIds.begin(), physicalCameraIds.end(), cameraId.c_str())
3848 == physicalCameraIds.end()) {
3849 // cameraId is not a physical camera of this logical multi-camera.
3850 continue;
3851 }
3852
3853 String16 id16(state.first), physicalId16(cameraId);
3854 for (auto& listener : mListenerList) {
3855 listener->getListener()->onPhysicalCameraStatusChanged(status,
3856 id16, physicalId16);
3857 }
3858 }
3859}
3860
Svet Ganova453d0d2018-01-11 15:37:58 -08003861void CameraService::blockClientsForUid(uid_t uid) {
3862 const auto clients = mActiveClientManager.getAll();
3863 for (auto& current : clients) {
3864 if (current != nullptr) {
3865 const auto basicClient = current->getValue();
3866 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
3867 basicClient->block();
3868 }
3869 }
3870 }
3871}
3872
Michael Grooverd1d435a2018-12-18 17:39:42 -08003873void CameraService::blockAllClients() {
3874 const auto clients = mActiveClientManager.getAll();
3875 for (auto& current : clients) {
3876 if (current != nullptr) {
3877 const auto basicClient = current->getValue();
3878 if (basicClient.get() != nullptr) {
3879 basicClient->block();
3880 }
3881 }
3882 }
3883}
3884
Svet Ganova453d0d2018-01-11 15:37:58 -08003885// NOTE: This is a remote API - make sure all args are validated
3886status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
3887 if (!checkCallingPermission(sManageCameraPermission, nullptr, nullptr)) {
3888 return PERMISSION_DENIED;
3889 }
3890 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
3891 return BAD_VALUE;
3892 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003893 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003894 return handleSetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07003895 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003896 return handleResetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07003897 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003898 return handleGetUidState(args, out, err);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003899 } else if (args.size() >= 2 && args[0] == String16("set-rotate-and-crop")) {
3900 return handleSetRotateAndCrop(args);
3901 } else if (args.size() >= 1 && args[0] == String16("get-rotate-and-crop")) {
3902 return handleGetRotateAndCrop(out);
Svet Ganova453d0d2018-01-11 15:37:58 -08003903 } else if (args.size() == 1 && args[0] == String16("help")) {
3904 printHelp(out);
3905 return NO_ERROR;
3906 }
3907 printHelp(err);
3908 return BAD_VALUE;
3909}
3910
3911status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07003912 String16 packageName = args[1];
3913
Svet Ganova453d0d2018-01-11 15:37:58 -08003914 bool active = false;
3915 if (args[2] == String16("active")) {
3916 active = true;
3917 } else if ((args[2] != String16("idle"))) {
3918 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
3919 return BAD_VALUE;
3920 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003921
3922 int userId = 0;
3923 if (args.size() >= 5 && args[3] == String16("--user")) {
3924 userId = atoi(String8(args[4]));
3925 }
3926
3927 uid_t uid;
3928 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
3929 return BAD_VALUE;
3930 }
3931
3932 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08003933 return NO_ERROR;
3934}
3935
3936status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07003937 String16 packageName = args[1];
3938
3939 int userId = 0;
3940 if (args.size() >= 4 && args[2] == String16("--user")) {
3941 userId = atoi(String8(args[3]));
3942 }
3943
3944 uid_t uid;
3945 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003946 return BAD_VALUE;
3947 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003948
3949 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08003950 return NO_ERROR;
3951}
3952
3953status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07003954 String16 packageName = args[1];
3955
3956 int userId = 0;
3957 if (args.size() >= 4 && args[2] == String16("--user")) {
3958 userId = atoi(String8(args[3]));
3959 }
3960
3961 uid_t uid;
3962 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003963 return BAD_VALUE;
3964 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003965
3966 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003967 return dprintf(out, "active\n");
3968 } else {
3969 return dprintf(out, "idle\n");
3970 }
3971}
3972
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003973status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
3974 int rotateValue = atoi(String8(args[1]));
3975 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
3976 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
3977 Mutex::Autolock lock(mServiceLock);
3978
3979 mOverrideRotateAndCropMode = rotateValue;
3980
3981 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
3982
3983 const auto clients = mActiveClientManager.getAll();
3984 for (auto& current : clients) {
3985 if (current != nullptr) {
3986 const auto basicClient = current->getValue();
3987 if (basicClient.get() != nullptr) {
3988 basicClient->setRotateAndCropOverride(rotateValue);
3989 }
3990 }
3991 }
3992
3993 return OK;
3994}
3995
3996status_t CameraService::handleGetRotateAndCrop(int out) {
3997 Mutex::Autolock lock(mServiceLock);
3998
3999 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
4000}
4001
Svet Ganova453d0d2018-01-11 15:37:58 -08004002status_t CameraService::printHelp(int out) {
4003 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07004004 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
4005 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
4006 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004007 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
4008 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
4009 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08004010 " help print this message\n");
4011}
4012
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004013int32_t CameraService::updateAudioRestriction() {
4014 Mutex::Autolock lock(mServiceLock);
4015 return updateAudioRestrictionLocked();
4016}
4017
4018int32_t CameraService::updateAudioRestrictionLocked() {
4019 int32_t mode = 0;
4020 // iterate through all active client
4021 for (const auto& i : mActiveClientManager.getAll()) {
4022 const auto clientSp = i->getValue();
4023 mode |= clientSp->getAudioRestriction();
4024 }
4025
4026 bool modeChanged = (mAudioRestriction != mode);
4027 mAudioRestriction = mode;
4028 if (modeChanged) {
4029 mAppOps.setCameraAudioRestriction(mode);
4030 }
4031 return mode;
4032}
4033
Mathias Agopian65ab4712010-07-14 17:59:35 -07004034}; // namespace android