blob: 535830777947edb031a5eaeb0d43965b797579c8 [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) {
459 logDeviceRemoved(id, String8::format("Device %s-%s availability changed from %d to %d",
460 id.string(), physicalId.string(),
461 newStatus != StatusInternal::PRESENT,
462 newStatus == StatusInternal::PRESENT));
463
464 String16 id16(id), physicalId16(physicalId);
465 Mutex::Autolock lock(mStatusListenerLock);
466 for (auto& listener : mListenerList) {
467 listener->getListener()->onPhysicalCameraStatusChanged(mapToInterface(newStatus),
468 id16, physicalId16);
469 }
470 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700471}
472
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800473void CameraService::disconnectClient(const String8& id, sp<BasicClient> clientToDisconnect) {
474 if (clientToDisconnect.get() != nullptr) {
475 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
476 __FUNCTION__, id.string());
477 // Notify the client of disconnection
478 clientToDisconnect->notifyError(
479 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
480 CaptureResultExtras{});
481 // Ensure not in binder RPC so client disconnect PID checks work correctly
482 LOG_ALWAYS_FATAL_IF(CameraThreadState::getCallingPid() != getpid(),
483 "onDeviceStatusChanged must be called from the camera service process!");
484 clientToDisconnect->disconnect();
485 }
486}
487
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800488void CameraService::onTorchStatusChanged(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800489 TorchModeStatus newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800490 Mutex::Autolock al(mTorchStatusMutex);
491 onTorchStatusChangedLocked(cameraId, newStatus);
492}
493
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800494void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800495 TorchModeStatus newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800496 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
497 __FUNCTION__, cameraId.string(), newStatus);
498
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800499 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800500 status_t res = getTorchStatusLocked(cameraId, &status);
501 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700502 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
503 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800504 return;
505 }
506 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800507 return;
508 }
509
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800510 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800511 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800512 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
513 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800514 return;
515 }
516
Ruben Brunkcc776712015-02-17 20:18:47 -0800517 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700518 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700519 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700520 auto iter = mTorchUidMap.find(cameraId);
521 if (iter != mTorchUidMap.end()) {
522 int oldUid = iter->second.second;
523 int newUid = iter->second.first;
524 BatteryNotifier& notifier(BatteryNotifier::getInstance());
525 if (oldUid != newUid) {
526 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800527 if (status == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700528 notifier.noteFlashlightOff(cameraId, oldUid);
529 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800530 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700531 notifier.noteFlashlightOn(cameraId, newUid);
532 }
533 iter->second.second = newUid;
534 } else {
535 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800536 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700537 notifier.noteFlashlightOn(cameraId, oldUid);
538 } else {
539 notifier.noteFlashlightOff(cameraId, oldUid);
540 }
541 }
542 }
543 }
544
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800545 broadcastTorchModeStatus(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800546}
547
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700548static bool hasPermissionsForSystemCamera(int callingPid, int callingUid) {
549 return checkPermission(sSystemCameraPermission, callingPid, callingUid) &&
550 checkPermission(sCameraPermission, callingPid, callingUid);
551}
552
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800553Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700554 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100555 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700556 bool hasSystemCameraPermissions =
557 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
558 CameraThreadState::getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700559 switch (type) {
560 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700561 if (hasSystemCameraPermissions) {
562 *numCameras = static_cast<int>(mNormalDeviceIds.size());
563 } else {
564 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
565 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800566 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700567 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700568 if (hasSystemCameraPermissions) {
569 *numCameras = mNumberOfCameras;
570 } else {
571 *numCameras = mNumberOfCamerasWithoutSystemCamera;
572 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800573 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700574 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800575 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700576 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800577 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
578 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700579 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800580 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700581}
582
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800583Status CameraService::getCameraInfo(int cameraId,
584 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700585 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100586 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700587 std::string cameraIdStr = cameraIdIntToStrLocked(cameraId);
588 if (shouldRejectSystemCameraConnection(String8(cameraIdStr.c_str()))) {
589 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
590 "characteristics for system only device %s: ", cameraIdStr.c_str());
591 }
Emilian Peevaee727d2017-05-04 16:35:48 +0100592
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800593 if (!mInitialized) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800594 return STATUS_ERROR(ERROR_DISCONNECTED,
595 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -0700596 }
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700597 bool hasSystemCameraPermissions =
598 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
599 CameraThreadState::getCallingUid());
600 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
601 if (hasSystemCameraPermissions) {
602 cameraIdBound = mNumberOfCameras;
603 }
604 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800605 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
606 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700607 }
608
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800609 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800610 status_t err = mCameraProviderManager->getCameraInfo(
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700611 cameraIdStr.c_str(), cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100612 if (err != OK) {
613 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
614 "Error retrieving camera info from device %d: %s (%d)", cameraId,
615 strerror(-err), err);
Ruben Brunkcc776712015-02-17 20:18:47 -0800616 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100617
Ruben Brunkcc776712015-02-17 20:18:47 -0800618 return ret;
619}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700620
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800621std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700622 const std::vector<std::string> *deviceIds = &mNormalDeviceIdsWithoutSystemCamera;
623 auto callingPid = CameraThreadState::getCallingPid();
624 auto callingUid = CameraThreadState::getCallingUid();
625 if (checkPermission(sSystemCameraPermission, callingPid, callingUid) ||
626 getpid() == callingPid) {
627 deviceIds = &mNormalDeviceIds;
628 }
629 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(deviceIds->size())) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800630 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700631 __FUNCTION__, cameraIdInt, deviceIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800632 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800633 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800634
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700635 return (*deviceIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800636}
637
638String8 CameraService::cameraIdIntToStr(int cameraIdInt) {
639 Mutex::Autolock lock(mServiceLock);
640 return String8(cameraIdIntToStrLocked(cameraIdInt).c_str());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800641}
642
643Status CameraService::getCameraCharacteristics(const String16& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800644 CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700645 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700646 if (!cameraInfo) {
647 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800648 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -0700649 }
650
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800651 if (!mInitialized) {
652 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800653 return STATUS_ERROR(ERROR_DISCONNECTED,
654 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -0700655 }
656
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700657 if (shouldRejectSystemCameraConnection(String8(cameraId))) {
658 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
659 "characteristics for system only device %s: ", String8(cameraId).string());
660 }
661
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800662 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800663
Emilian Peevf53f66e2017-04-11 14:29:43 +0100664 status_t res = mCameraProviderManager->getCameraCharacteristics(
665 String8(cameraId).string(), cameraInfo);
666 if (res != OK) {
667 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
668 "characteristics for device %s: %s (%d)", String8(cameraId).string(),
669 strerror(-res), res);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700670 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700671 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
672 if (getSystemCameraKind(String8(cameraId), &deviceKind) != OK) {
673 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, String8(cameraId).string());
674 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera kind "
675 "for device %s", String8(cameraId).string());
676 }
Jayant Chowdhary12361932018-08-27 14:46:13 -0700677 int callingPid = CameraThreadState::getCallingPid();
678 int callingUid = CameraThreadState::getCallingUid();
Emilian Peeve20c6372018-08-14 18:45:53 +0100679 std::vector<int32_t> tagsRemoved;
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700680 // If it's not calling from cameraserver, check the permission only if
681 // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
682 // it would've already been checked in shouldRejectSystemCameraConnection.
Emilian Peeve20c6372018-08-14 18:45:53 +0100683 if ((callingPid != getpid()) &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700684 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700685 !checkPermission(sCameraPermission, callingPid, callingUid)) {
Emilian Peeve20c6372018-08-14 18:45:53 +0100686 res = cameraInfo->removePermissionEntries(
687 mCameraProviderManager->getProviderTagIdLocked(String8(cameraId).string()),
688 &tagsRemoved);
689 if (res != OK) {
690 cameraInfo->clear();
691 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
692 " characteristics needing camera permission for device %s: %s (%d)",
693 String8(cameraId).string(), strerror(-res), res);
694 }
695 }
696
697 if (!tagsRemoved.empty()) {
698 res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
699 tagsRemoved.data(), tagsRemoved.size());
700 if (res != OK) {
701 cameraInfo->clear();
702 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
703 "keys needing permission for device %s: %s (%d)", String8(cameraId).string(),
704 strerror(-res), res);
705 }
706 }
707
Zhijun He2b59be82013-09-25 10:14:30 -0700708 return ret;
709}
710
Ruben Brunkcc776712015-02-17 20:18:47 -0800711String8 CameraService::getFormattedCurrentTime() {
712 time_t now = time(nullptr);
713 char formattedTime[64];
714 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
715 return String8(formattedTime);
716}
717
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800718Status CameraService::getCameraVendorTagDescriptor(
719 /*out*/
720 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700721 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800722 if (!mInitialized) {
723 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800724 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800725 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -0800726 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
727 if (globalDescriptor != nullptr) {
728 *desc = *(globalDescriptor.get());
729 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800730 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800731}
732
Emilian Peev71c73a22017-03-21 16:35:51 +0000733Status CameraService::getCameraVendorTagCache(
734 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
735 ATRACE_CALL();
736 if (!mInitialized) {
737 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
738 return STATUS_ERROR(ERROR_DISCONNECTED,
739 "Camera subsystem not available");
740 }
741 sp<VendorTagDescriptorCache> globalCache =
742 VendorTagDescriptorCache::getGlobalVendorTagCache();
743 if (globalCache != nullptr) {
744 *cache = *(globalCache.get());
745 }
746 return Status::ok();
747}
748
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800749int CameraService::getDeviceVersion(const String8& cameraId, int* facing) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700750 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800751
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800752 int deviceVersion = 0;
753
Emilian Peevf53f66e2017-04-11 14:29:43 +0100754 status_t res;
755 hardware::hidl_version maxVersion{0,0};
756 res = mCameraProviderManager->getHighestSupportedVersion(cameraId.string(),
757 &maxVersion);
758 if (res != OK) return -1;
759 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800760
Emilian Peevf53f66e2017-04-11 14:29:43 +0100761 hardware::CameraInfo info;
762 if (facing) {
763 res = mCameraProviderManager->getCameraInfo(cameraId.string(), &info);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -0800764 if (res != OK) return -1;
Emilian Peevf53f66e2017-04-11 14:29:43 +0100765 *facing = info.facing;
Igor Murashkin634a5152013-02-20 17:15:11 -0800766 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100767
Igor Murashkin634a5152013-02-20 17:15:11 -0800768 return deviceVersion;
769}
770
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800771Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700772 switch(err) {
773 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800774 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800775 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800776 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
777 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800778 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800779 return STATUS_ERROR(ERROR_DISCONNECTED,
780 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700781 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800782 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
783 "Camera HAL encountered error %d: %s",
784 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700785 }
Igor Murashkinbfc99152013-02-27 12:55:20 -0800786}
787
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800788Status CameraService::makeClient(const sp<CameraService>& cameraService,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800789 const sp<IInterface>& cameraCb, const String16& packageName,
790 const std::unique_ptr<String16>& featureId, const String8& cameraId, int api1CameraId,
791 int facing, int clientPid, uid_t clientUid, int servicePid, int halVersion,
792 int deviceVersion, apiLevel effectiveApiLevel,
Ruben Brunkcc776712015-02-17 20:18:47 -0800793 /*out*/sp<BasicClient>* client) {
794
Ruben Brunkcc776712015-02-17 20:18:47 -0800795 if (halVersion < 0 || halVersion == deviceVersion) {
796 // Default path: HAL version is unspecified by caller, create CameraClient
797 // based on device version reported by the HAL.
798 switch(deviceVersion) {
799 case CAMERA_DEVICE_API_VERSION_1_0:
800 if (effectiveApiLevel == API_1) { // Camera1 API route
801 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800802 *client = new CameraClient(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800803 api1CameraId, facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700804 getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800805 } else { // Camera2 API route
806 ALOGW("Camera using old HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800807 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800808 "Camera device \"%s\" HAL version %d does not support camera2 API",
809 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800810 }
811 break;
Ruben Brunkcc776712015-02-17 20:18:47 -0800812 case CAMERA_DEVICE_API_VERSION_3_0:
813 case CAMERA_DEVICE_API_VERSION_3_1:
814 case CAMERA_DEVICE_API_VERSION_3_2:
815 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -0700816 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -0700817 case CAMERA_DEVICE_API_VERSION_3_5:
Yin-Chia Yeh56d98ba2020-01-16 16:57:14 -0800818 case CAMERA_DEVICE_API_VERSION_3_6:
Ruben Brunkcc776712015-02-17 20:18:47 -0800819 if (effectiveApiLevel == API_1) { // Camera1 API route
820 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800821 *client = new Camera2Client(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800822 cameraId, api1CameraId,
823 facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700824 servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800825 } else { // Camera2 API route
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800826 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
827 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800828 *client = new CameraDeviceClient(cameraService, tmp, packageName, featureId,
829 cameraId, facing, clientPid, clientUid, servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800830 }
831 break;
832 default:
833 // Should not be reachable
834 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800835 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800836 "Camera device \"%s\" has unknown HAL version %d",
837 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800838 }
839 } else {
840 // A particular HAL version is requested by caller. Create CameraClient
841 // based on the requested HAL version.
842 if (deviceVersion > CAMERA_DEVICE_API_VERSION_1_0 &&
843 halVersion == CAMERA_DEVICE_API_VERSION_1_0) {
844 // Only support higher HAL version device opened as HAL1.0 device.
845 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800846 *client = new CameraClient(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800847 api1CameraId, facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700848 servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800849 } else {
850 // Other combinations (e.g. HAL3.x open as HAL2.x) are not supported yet.
851 ALOGE("Invalid camera HAL version %x: HAL %x device can only be"
852 " opened as HAL %x device", halVersion, deviceVersion,
853 CAMERA_DEVICE_API_VERSION_1_0);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800854 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800855 "Camera device \"%s\" (HAL version %d) cannot be opened as HAL version %d",
856 cameraId.string(), deviceVersion, halVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800857 }
858 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800859 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800860}
861
Ruben Brunk6267b532015-04-30 17:44:07 -0700862String8 CameraService::toString(std::set<userid_t> intSet) {
863 String8 s("");
864 bool first = true;
865 for (userid_t i : intSet) {
866 if (first) {
867 s.appendFormat("%d", i);
868 first = false;
869 } else {
870 s.appendFormat(", %d", i);
871 }
872 }
873 return s;
874}
875
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800876int32_t CameraService::mapToInterface(TorchModeStatus status) {
877 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
878 switch (status) {
879 case TorchModeStatus::NOT_AVAILABLE:
880 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
881 break;
882 case TorchModeStatus::AVAILABLE_OFF:
883 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
884 break;
885 case TorchModeStatus::AVAILABLE_ON:
886 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
887 break;
888 default:
889 ALOGW("Unknown new flash status: %d", status);
890 }
891 return serviceStatus;
892}
893
894CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
895 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
896 switch (status) {
897 case CameraDeviceStatus::NOT_PRESENT:
898 serviceStatus = StatusInternal::NOT_PRESENT;
899 break;
900 case CameraDeviceStatus::PRESENT:
901 serviceStatus = StatusInternal::PRESENT;
902 break;
903 case CameraDeviceStatus::ENUMERATING:
904 serviceStatus = StatusInternal::ENUMERATING;
905 break;
906 default:
907 ALOGW("Unknown new HAL device status: %d", status);
908 }
909 return serviceStatus;
910}
911
912int32_t CameraService::mapToInterface(StatusInternal status) {
913 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
914 switch (status) {
915 case StatusInternal::NOT_PRESENT:
916 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
917 break;
918 case StatusInternal::PRESENT:
919 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
920 break;
921 case StatusInternal::ENUMERATING:
922 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
923 break;
924 case StatusInternal::NOT_AVAILABLE:
925 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
926 break;
927 case StatusInternal::UNKNOWN:
928 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
929 break;
930 default:
931 ALOGW("Unknown new internal device status: %d", status);
932 }
933 return serviceStatus;
934}
935
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800936Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -0700937 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700938
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800939 String16 internalPackageName("cameraserver");
Ruben Brunkcc776712015-02-17 20:18:47 -0800940 String8 id = String8::format("%d", cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800941 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800942 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800943 if (!(ret = connectHelper<ICameraClient,Client>(
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800944 sp<ICameraClient>{nullptr}, id, cameraId,
945 static_cast<int>(CAMERA_HAL_API_VERSION_UNSPECIFIED),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800946 internalPackageName, std::unique_ptr<String16>(), uid, USE_CALLING_PID,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700947 API_1, /*shimUpdateOnly*/ true, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800948 ).isOk()) {
949 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
Ruben Brunkb2119af2014-05-09 19:57:56 -0700950 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800951 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700952}
953
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800954Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -0700955 /*out*/
956 CameraParameters* parameters) {
957
958 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
959
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800960 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -0700961
962 if (parameters == NULL) {
963 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800964 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -0700965 }
966
Ruben Brunkcc776712015-02-17 20:18:47 -0800967 String8 id = String8::format("%d", cameraId);
968
969 // Check if we already have parameters
970 {
971 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -0700972 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -0800973 auto cameraState = getCameraState(id);
974 if (cameraState == nullptr) {
975 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800976 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
977 "Invalid camera ID: %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -0800978 }
979 CameraParameters p = cameraState->getShimParams();
980 if (!p.isEmpty()) {
981 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800982 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700983 }
984 }
985
Jayant Chowdhary12361932018-08-27 14:46:13 -0700986 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -0800987 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -0700988 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800989 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800990 // Error already logged by callee
991 return ret;
992 }
993
994 // Check for parameters again
995 {
996 // Scope for service lock
997 Mutex::Autolock lock(mServiceLock);
998 auto cameraState = getCameraState(id);
999 if (cameraState == nullptr) {
1000 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001001 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1002 "Invalid camera ID: %s", id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001003 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001004 CameraParameters p = cameraState->getShimParams();
1005 if (!p.isEmpty()) {
1006 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001007 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001008 }
1009 }
1010
Ruben Brunkcc776712015-02-17 20:18:47 -08001011 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1012 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001013 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001014}
1015
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001016// Can camera service trust the caller based on the calling UID?
1017static bool isTrustedCallingUid(uid_t uid) {
1018 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001019 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001020 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001021 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001022 return true;
1023 default:
1024 return false;
1025 }
1026}
1027
Nicholas Sauera3620332019-04-03 14:05:17 -07001028static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1029 PermissionController pc;
1030 uid = pc.getPackageUid(packageName, 0);
1031 if (uid <= 0) {
1032 ALOGE("Unknown package: '%s'", String8(packageName).string());
1033 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
1034 return BAD_VALUE;
1035 }
1036
1037 if (userId < 0) {
1038 ALOGE("Invalid user: %d", userId);
1039 dprintf(err, "Invalid user: %d\n", userId);
1040 return BAD_VALUE;
1041 }
1042
1043 uid = multiuser_get_uid(userId, uid);
1044 return NO_ERROR;
1045}
1046
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001047Status CameraService::validateConnectLocked(const String8& cameraId,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001048 const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
1049 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001050
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001051#ifdef __BRILLO__
1052 UNUSED(clientName8);
1053 UNUSED(clientUid);
1054 UNUSED(clientPid);
1055 UNUSED(originalClientPid);
1056#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001057 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1058 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001059 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001060 return allowed;
1061 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001062#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001063
Jayant Chowdhary12361932018-08-27 14:46:13 -07001064 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001065
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001066 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001067 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1068 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001069 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1070 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001071 }
1072
Ruben Brunkcc776712015-02-17 20:18:47 -08001073 if (getCameraState(cameraId) == nullptr) {
1074 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1075 cameraId.string());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001076 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1077 "No camera device with ID \"%s\" available", cameraId.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001078 }
1079
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001080 status_t err = checkIfDeviceIsUsable(cameraId);
1081 if (err != NO_ERROR) {
1082 switch(err) {
1083 case -ENODEV:
1084 case -EBUSY:
1085 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1086 "No camera device with ID \"%s\" currently available", cameraId.string());
1087 default:
1088 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1089 "Unknown error connecting to ID \"%s\"", cameraId.string());
1090 }
1091 }
1092 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001093}
1094
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001095Status CameraService::validateClientPermissionsLocked(const String8& cameraId,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001096 const String8& clientName8, int& clientUid, int& clientPid,
1097 /*out*/int& originalClientPid) const {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001098 int callingPid = CameraThreadState::getCallingPid();
1099 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001100
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001101 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001102 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001103 clientUid = callingUid;
1104 } else if (!isTrustedCallingUid(callingUid)) {
1105 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1106 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001107 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1108 "Untrusted caller (calling PID %d, UID %d) trying to "
1109 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1110 callingPid, callingUid, cameraId.string(),
1111 clientName8.string(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001112 }
1113
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001114 // Check if we can trust clientPid
1115 if (clientPid == USE_CALLING_PID) {
1116 clientPid = callingPid;
1117 } else if (!isTrustedCallingUid(callingUid)) {
1118 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1119 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001120 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1121 "Untrusted caller (calling PID %d, UID %d) trying to "
1122 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1123 callingPid, callingUid, cameraId.string(),
1124 clientName8.string(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001125 }
1126
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001127 if (shouldRejectSystemCameraConnection(cameraId)) {
1128 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1129 cameraId.c_str());
1130 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
1131 "available", cameraId.string());
1132 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001133 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1134 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1135 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
1136 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
1137 "found while trying to query device kind", cameraId.string());
1138
1139 }
1140
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001141 // If it's not calling from cameraserver, check the permission if the
1142 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1143 // android.permission.SYSTEM_CAMERA for system only camera devices).
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001144 if (callingPid != getpid() &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001145 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001146 !checkPermission(sCameraPermission, clientPid, clientUid)) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001147 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001148 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1149 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
1150 clientName8.string(), clientUid, clientPid, cameraId.string());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001151 }
1152
Svet Ganova453d0d2018-01-11 15:37:58 -08001153 // Make sure the UID is in an active state to use the camera
Svet Ganov7b4ab782018-03-25 12:48:10 -07001154 if (!mUidPolicy->isUidActive(callingUid, String16(clientName8))) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001155 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001156 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1157 clientPid, clientUid);
1158 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001159 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1160 "calling UID %d proc state %" PRId32 ")",
1161 clientName8.string(), clientUid, clientPid, cameraId.string(),
1162 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001163 }
1164
Michael Grooverd1d435a2018-12-18 17:39:42 -08001165 // If sensor privacy is enabled then prevent access to the camera
1166 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1167 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1168 return STATUS_ERROR_FMT(ERROR_DISABLED,
1169 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
1170 "is enabled", clientName8.string(), clientUid, clientPid, cameraId.string());
1171 }
1172
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001173 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1174 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001175 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001176 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001177
Ruben Brunk6267b532015-04-30 17:44:07 -07001178 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001179
Ruben Brunka8ca9152015-04-07 14:23:40 -07001180 // Only allow clients who are being used by the current foreground device user, unless calling
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001181 // from our own process OR the caller is using the cameraserver's HIDL interface.
1182 if (!hardware::IPCThreadState::self()->isServingCall() && callingPid != getpid() &&
1183 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001184 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1185 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
1186 toString(mAllowedUsers).string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001187 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1188 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
1189 clientUserId, cameraId.string());
Ruben Brunk36597b22015-03-20 22:15:57 -07001190 }
1191
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001192 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001193}
1194
1195status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
1196 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001197 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001198 if (cameraState == nullptr) {
1199 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1200 cameraId.string());
1201 return -ENODEV;
1202 }
1203
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001204 StatusInternal currentStatus = cameraState->getStatus();
1205 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001206 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
1207 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001208 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001209 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001210 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
1211 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001212 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001213 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001214
Ruben Brunkcc776712015-02-17 20:18:47 -08001215 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001216}
1217
Ruben Brunkcc776712015-02-17 20:18:47 -08001218void CameraService::finishConnectLocked(const sp<BasicClient>& client,
1219 const CameraService::DescriptorPtr& desc) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001220
Ruben Brunkcc776712015-02-17 20:18:47 -08001221 // Make a descriptor for the incoming client
1222 auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
1223 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1224
1225 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
1226 String8(client->getPackageName()));
1227
1228 if (evicted.size() > 0) {
1229 // This should never happen - clients should already have been removed in disconnect
1230 for (auto& i : evicted) {
1231 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
1232 __FUNCTION__, i->getKey().string());
1233 }
1234
1235 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1236 __FUNCTION__);
1237 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001238
1239 // And register a death notification for the client callback. Do
1240 // this last to avoid Binder policy where a nested Binder
1241 // transaction might be pre-empted to service the client death
1242 // notification if the client process dies before linkToDeath is
1243 // invoked.
1244 sp<IBinder> remoteCallback = client->getRemote();
1245 if (remoteCallback != nullptr) {
1246 remoteCallback->linkToDeath(this);
1247 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001248}
1249
1250status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
1251 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
1252 /*out*/
1253 sp<BasicClient>* client,
1254 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001255 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001256 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001257 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001258 DescriptorPtr clientDescriptor;
1259 {
1260 if (effectiveApiLevel == API_1) {
1261 // If we are using API1, any existing client for this camera ID with the same remote
1262 // should be returned rather than evicted to allow MediaRecorder to work properly.
1263
1264 auto current = mActiveClientManager.get(cameraId);
1265 if (current != nullptr) {
1266 auto clientSp = current->getValue();
1267 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001268 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
1269 ALOGW("CameraService connect called from same client, but with a different"
1270 " API level, evicting prior client...");
1271 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001272 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001273 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001274 *client = clientSp;
1275 return NO_ERROR;
1276 }
1277 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001278 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001279 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001280
Ruben Brunkcc776712015-02-17 20:18:47 -08001281 // Get current active client PIDs
1282 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1283 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001284
Emilian Peev8131a262017-02-01 12:33:43 +00001285 std::vector<int> priorityScores(ownerPids.size());
1286 std::vector<int> states(ownerPids.size());
Igor Murashkine6800ce2013-03-04 17:25:57 -08001287
Emilian Peev8131a262017-02-01 12:33:43 +00001288 // Get priority scores of all active PIDs
1289 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1290 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1291 /*out*/&priorityScores[0]);
1292 if (err != OK) {
1293 ALOGE("%s: Priority score query failed: %d",
1294 __FUNCTION__, err);
1295 return err;
1296 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001297
Ruben Brunkcc776712015-02-17 20:18:47 -08001298 // Update all active clients' priorities
Emilian Peev8131a262017-02-01 12:33:43 +00001299 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
Ruben Brunkcc776712015-02-17 20:18:47 -08001300 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
Emilian Peev8131a262017-02-01 12:33:43 +00001301 pidToPriorityMap.emplace(ownerPids[i],
Jayant Chowdharyc578a502019-05-08 10:57:54 -07001302 resource_policy::ClientPriority(priorityScores[i], states[i],
1303 /* isVendorClient won't get copied over*/ false));
Ruben Brunkcc776712015-02-17 20:18:47 -08001304 }
1305 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001306
Ruben Brunkcc776712015-02-17 20:18:47 -08001307 // Get state for the given cameraId
1308 auto state = getCameraState(cameraId);
1309 if (state == nullptr) {
1310 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1311 clientPid, cameraId.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001312 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001313 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001314 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001315
1316 // Make descriptor for incoming client
Shuzhen Wang2db86ff2018-04-25 01:11:17 +00001317 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001318 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1319 state->getConflicting(),
Emilian Peev8131a262017-02-01 12:33:43 +00001320 priorityScores[priorityScores.size() - 1],
1321 clientPid,
1322 states[states.size() - 1]);
Ruben Brunkcc776712015-02-17 20:18:47 -08001323
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001324 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1325
Ruben Brunkcc776712015-02-17 20:18:47 -08001326 // Find clients that would be evicted
1327 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1328
1329 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1330 // background, so we cannot do evictions
1331 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1332 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1333 " priority).", clientPid);
1334
1335 sp<BasicClient> clientSp = clientDescriptor->getValue();
1336 String8 curTime = getFormattedCurrentTime();
1337 auto incompatibleClients =
1338 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1339
1340 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Emilian Peev8131a262017-02-01 12:33:43 +00001341 "(PID %d, score %d state %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001342 cameraId.string(), packageName.string(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001343 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001344
1345 for (auto& i : incompatibleClients) {
1346 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001347 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
1348 i->getKey().string(),
1349 String8{i->getValue()->getPackageName()}.string(),
1350 i->getOwnerId(), i->getPriority().getScore(),
1351 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001352 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00001353 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(),
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001354 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001355 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001356 }
1357
1358 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001359 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001360 mEventLog.add(msg);
1361
1362 return -EBUSY;
1363 }
1364
1365 for (auto& i : evicted) {
1366 sp<BasicClient> clientSp = i->getValue();
1367 if (clientSp.get() == nullptr) {
1368 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1369
1370 // TODO: Remove this
1371 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1372 __FUNCTION__);
1373 mActiveClientManager.remove(i);
1374 continue;
1375 }
1376
1377 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1378 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001379 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001380
Ruben Brunkcc776712015-02-17 20:18:47 -08001381 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001382 logEvent(String8::format("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00001383 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1384 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001385 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
Emilian Peev8131a262017-02-01 12:33:43 +00001386 i->getOwnerId(), i->getPriority().getScore(),
1387 i->getPriority().getState(), cameraId.string(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001388 packageName.string(), clientPid, clientPriority.getScore(),
1389 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08001390
1391 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001392 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001393 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001394 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001395 }
1396
Ruben Brunkcc776712015-02-17 20:18:47 -08001397 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1398 // other clients from connecting in mServiceLockWrapper if held
1399 mServiceLock.unlock();
1400
1401 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07001402 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001403
1404 // Destroy evicted clients
1405 for (auto& i : evictedClients) {
1406 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001407 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001408 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001409
Jayant Chowdhary12361932018-08-27 14:46:13 -07001410 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08001411
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001412 for (const auto& i : evictedClients) {
1413 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1414 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1415 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1416 if (ret == TIMED_OUT) {
1417 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1418 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1419 mActiveClientManager.toString().string());
1420 return -EBUSY;
1421 }
1422 if (ret != NO_ERROR) {
1423 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1424 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1425 ret, mActiveClientManager.toString().string());
1426 return ret;
1427 }
1428 }
1429
1430 evictedClients.clear();
1431
Ruben Brunkcc776712015-02-17 20:18:47 -08001432 // Once clients have been disconnected, relock
1433 mServiceLock.lock();
1434
1435 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1436 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1437 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001438 }
1439
Ruben Brunkcc776712015-02-17 20:18:47 -08001440 *partial = clientDescriptor;
1441 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001442}
1443
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001444Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001445 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001446 int api1CameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001447 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001448 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001449 int clientPid,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001450 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001451 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001452
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001453 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001454 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001455
1456 String8 id = cameraIdIntToStr(api1CameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001457 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001458 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001459 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, std::unique_ptr<String16>(),
1460 clientUid, clientPid, API_1, /*shimUpdateOnly*/ false, /*out*/client);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001461
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001462 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001463 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001464 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001465 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001466 }
1467
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001468 *device = client;
1469 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001470}
1471
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001472Status CameraService::connectLegacy(
Zhijun Heb10cdad2014-06-16 16:38:35 -07001473 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001474 int api1CameraId, int halVersion,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001475 const String16& clientPackageName,
Zhijun Heb10cdad2014-06-16 16:38:35 -07001476 int clientUid,
1477 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001478 sp<ICamera>* device) {
Zhijun Heb10cdad2014-06-16 16:38:35 -07001479
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001480 ATRACE_CALL();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001481 String8 id = cameraIdIntToStr(api1CameraId);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001482
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001483 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001484 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001485 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId, halVersion,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001486 clientPackageName, std::unique_ptr<String16>(), clientUid, USE_CALLING_PID, API_1,
1487 /*shimUpdateOnly*/ false, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001488
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001489 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001490 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001491 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001492 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001493 }
1494
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001495 *device = client;
1496 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001497}
1498
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001499bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
1500 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001501 // If the client is not a vendor client, don't add listener if
1502 // a) the camera is a publicly hidden secure camera OR
1503 // b) the camera is a system only camera and the client doesn't
1504 // have android.permission.SYSTEM_CAMERA permissions.
1505 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
1506 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1507 !hasPermissionsForSystemCamera(clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001508 return true;
1509 }
1510 return false;
1511}
1512
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001513bool CameraService::shouldRejectSystemCameraConnection(const String8& cameraId) const {
1514 // Rules for rejection:
1515 // 1) If cameraserver tries to access this camera device, accept the
1516 // connection.
1517 // 2) The camera device is a publicly hidden secure camera device AND some
1518 // component is trying to access it on a non-hwbinder thread (generally a non HAL client),
1519 // reject it.
1520 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
1521 // and the serving thread is a non hwbinder thread, the client must have
1522 // android.permission.SYSTEM_CAMERA permissions to connect.
1523
1524 int cPid = CameraThreadState::getCallingPid();
1525 int cUid = CameraThreadState::getCallingUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001526 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
1527 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
1528 ALOGE("%s: Invalid camera id %s, ", __FUNCTION__, cameraId.c_str());
1529 return true;
1530 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001531
1532 // (1) Cameraserver trying to connect, accept.
1533 if (CameraThreadState::getCallingPid() == getpid()) {
1534 return false;
1535 }
1536 // (2)
1537 if (!hardware::IPCThreadState::self()->isServingCall() &&
1538 systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
1539 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
1540 return true;
1541 }
1542 // (3) Here we only check for permissions if it is a system only camera device. This is since
1543 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
1544 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
1545 // same behavior for system camera devices.
1546 if (!hardware::IPCThreadState::self()->isServingCall() &&
1547 systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1548 !hasPermissionsForSystemCamera(cPid, cUid)) {
1549 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
1550 cameraId.c_str());
1551 return true;
1552 }
1553
1554 return false;
1555}
1556
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001557Status CameraService::connectDevice(
1558 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001559 const String16& cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001560 const String16& clientPackageName,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001561 const std::unique_ptr<String16>& clientFeatureId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001562 int clientUid,
1563 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001564 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001565
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001566 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001567 Status ret = Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001568 String8 id = String8(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001569 sp<CameraDeviceClient> client = nullptr;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001570 String16 clientPackageNameAdj = clientPackageName;
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001571
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001572 if (hardware::IPCThreadState::self()->isServingCall()) {
1573 std::string vendorClient =
1574 StringPrintf("vendor.client.pid<%d>", CameraThreadState::getCallingPid());
1575 clientPackageNameAdj = String16(vendorClient.c_str());
1576 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001577 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001578 /*api1CameraId*/-1,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001579 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageNameAdj, clientFeatureId,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001580 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08001581
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001582 if(!ret.isOk()) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001583 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageNameAdj),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001584 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001585 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001586 }
1587
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001588 *device = client;
1589 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001590}
1591
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001592template<class CALLBACK, class CLIENT>
1593Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001594 int api1CameraId, int halVersion, const String16& clientPackageName,
1595 const std::unique_ptr<String16>& clientFeatureId, int clientUid, int clientPid,
1596 apiLevel effectiveApiLevel, bool shimUpdateOnly,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001597 /*out*/sp<CLIENT>& device) {
1598 binder::Status ret = binder::Status::ok();
1599
1600 String8 clientName8(clientPackageName);
1601
1602 int originalClientPid = 0;
1603
1604 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) for HAL version %s and "
1605 "Camera API version %d", clientPid, clientName8.string(), cameraId.string(),
1606 (halVersion == -1) ? "default" : std::to_string(halVersion).c_str(),
1607 static_cast<int>(effectiveApiLevel));
1608
1609 sp<CLIENT> client = nullptr;
1610 {
1611 // Acquire mServiceLock and prevent other clients from connecting
1612 std::unique_ptr<AutoConditionLock> lock =
1613 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1614
1615 if (lock == nullptr) {
1616 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
1617 , clientPid);
1618 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1619 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
1620 cameraId.string(), clientName8.string(), clientPid);
1621 }
1622
1623 // Enforce client permissions and do basic sanity checks
1624 if(!(ret = validateConnectLocked(cameraId, clientName8,
1625 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
1626 return ret;
1627 }
1628
1629 // Check the shim parameters after acquiring lock, if they have already been updated and
1630 // we were doing a shim update, return immediately
1631 if (shimUpdateOnly) {
1632 auto cameraState = getCameraState(cameraId);
1633 if (cameraState != nullptr) {
1634 if (!cameraState->getShimParams().isEmpty()) return ret;
1635 }
1636 }
1637
1638 status_t err;
1639
1640 sp<BasicClient> clientTmp = nullptr;
1641 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
1642 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
1643 IInterface::asBinder(cameraCb), clientName8, /*out*/&clientTmp,
1644 /*out*/&partial)) != NO_ERROR) {
1645 switch (err) {
1646 case -ENODEV:
1647 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1648 "No camera device with ID \"%s\" currently available",
1649 cameraId.string());
1650 case -EBUSY:
1651 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1652 "Higher-priority client using camera, ID \"%s\" currently unavailable",
1653 cameraId.string());
1654 default:
1655 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1656 "Unexpected error %s (%d) opening camera \"%s\"",
1657 strerror(-err), err, cameraId.string());
1658 }
1659 }
1660
1661 if (clientTmp.get() != nullptr) {
1662 // Handle special case for API1 MediaRecorder where the existing client is returned
1663 device = static_cast<CLIENT*>(clientTmp.get());
1664 return ret;
1665 }
1666
1667 // give flashlight a chance to close devices if necessary.
1668 mFlashlight->prepareDeviceOpen(cameraId);
1669
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001670 int facing = -1;
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001671 int deviceVersion = getDeviceVersion(cameraId, /*out*/&facing);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08001672 if (facing == -1) {
1673 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.string());
1674 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1675 "Unable to get camera device \"%s\" facing", cameraId.string());
1676 }
1677
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001678 sp<BasicClient> tmp = nullptr;
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001679 if(!(ret = makeClient(this, cameraCb, clientPackageName, clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001680 cameraId, api1CameraId, facing,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001681 clientPid, clientUid, getpid(),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001682 halVersion, deviceVersion, effectiveApiLevel,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001683 /*out*/&tmp)).isOk()) {
1684 return ret;
1685 }
1686 client = static_cast<CLIENT*>(tmp.get());
1687
1688 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
1689 __FUNCTION__);
1690
Emilian Peevbd8c5032018-02-14 23:05:40 +00001691 err = client->initialize(mCameraProviderManager, mMonitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001692 if (err != OK) {
1693 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001694 // Errors could be from the HAL module open call or from AppOpsManager
1695 switch(err) {
1696 case BAD_VALUE:
1697 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1698 "Illegal argument to HAL module for camera \"%s\"", cameraId.string());
1699 case -EBUSY:
1700 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1701 "Camera \"%s\" is already open", cameraId.string());
1702 case -EUSERS:
1703 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1704 "Too many cameras already open, cannot open camera \"%s\"",
1705 cameraId.string());
1706 case PERMISSION_DENIED:
1707 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1708 "No permission to open camera \"%s\"", cameraId.string());
1709 case -EACCES:
1710 return STATUS_ERROR_FMT(ERROR_DISABLED,
1711 "Camera \"%s\" disabled by policy", cameraId.string());
1712 case -ENODEV:
1713 default:
1714 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1715 "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
1716 strerror(-err), err);
1717 }
1718 }
1719
1720 // Update shim paremeters for legacy clients
1721 if (effectiveApiLevel == API_1) {
1722 // Assume we have always received a Client subclass for API1
1723 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
1724 String8 rawParams = shimClient->getParameters();
1725 CameraParameters params(rawParams);
1726
1727 auto cameraState = getCameraState(cameraId);
1728 if (cameraState != nullptr) {
1729 cameraState->setShimParams(params);
1730 } else {
1731 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
1732 __FUNCTION__, cameraId.string());
1733 }
1734 }
1735
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001736 // Set rotate-and-crop override behavior
1737 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
1738 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
1739 }
1740
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001741 if (shimUpdateOnly) {
1742 // If only updating legacy shim parameters, immediately disconnect client
1743 mServiceLock.unlock();
1744 client->disconnect();
1745 mServiceLock.lock();
1746 } else {
1747 // Otherwise, add client to active clients list
1748 finishConnectLocked(client, partial);
1749 }
1750 } // lock is destroyed, allow further connect calls
1751
1752 // Important: release the mutex here so the client can call back into the service from its
1753 // destructor (can be at the end of the call)
1754 device = client;
1755 return ret;
1756}
1757
Emilian Peevb2bc5a42019-11-20 16:02:14 -08001758status_t CameraService::addOfflineClient(String8 cameraId, sp<BasicClient> offlineClient) {
1759 if (offlineClient.get() == nullptr) {
1760 return BAD_VALUE;
1761 }
1762
1763 {
1764 // Acquire mServiceLock and prevent other clients from connecting
1765 std::unique_ptr<AutoConditionLock> lock =
1766 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1767
1768 if (lock == nullptr) {
1769 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
1770 , __FUNCTION__, offlineClient->getClientPid());
1771 return TIMED_OUT;
1772 }
1773
1774 auto onlineClientDesc = mActiveClientManager.get(cameraId);
1775 if (onlineClientDesc.get() == nullptr) {
1776 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
1777 cameraId.c_str());
1778 return BAD_VALUE;
1779 }
1780
1781 // Offline clients do not evict or conflict with other online devices. Resource sharing
1782 // conflicts are handled by the camera provider which will either succeed or fail before
1783 // reaching this method.
1784 const auto& onlinePriority = onlineClientDesc->getPriority();
1785 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
1786 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
1787 /*conflictingKeys*/ std::set<String8>(), onlinePriority.getScore(),
1788 onlineClientDesc->getOwnerId(), onlinePriority.getState());
1789
1790 // Allow only one offline device per camera
1791 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
1792 if (!incompatibleClients.empty()) {
1793 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
1794 return BAD_VALUE;
1795 }
1796
1797 auto err = offlineClient->initialize(mCameraProviderManager, mMonitorTags);
1798 if (err != OK) {
1799 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
1800 return err;
1801 }
1802
1803 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
1804 if (evicted.size() > 0) {
1805 for (auto& i : evicted) {
1806 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
1807 __FUNCTION__, i->getKey().string());
1808 }
1809
1810 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
1811 "properly", __FUNCTION__);
1812
1813 return BAD_VALUE;
1814 }
1815
1816 logConnectedOffline(offlineClientDesc->getKey(),
1817 static_cast<int>(offlineClientDesc->getOwnerId()),
1818 String8(offlineClient->getPackageName()));
1819
1820 sp<IBinder> remoteCallback = offlineClient->getRemote();
1821 if (remoteCallback != nullptr) {
1822 remoteCallback->linkToDeath(this);
1823 }
1824 } // lock is destroyed, allow further connect calls
1825
1826 return OK;
1827}
1828
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001829Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001830 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001831 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001832
1833 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07001834 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001835 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001836 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1837 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001838 }
1839
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001840 String8 id = String8(cameraId.string());
Jayant Chowdhary12361932018-08-27 14:46:13 -07001841 int uid = CameraThreadState::getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001842
1843 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08001844 auto state = getCameraState(id);
1845 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001846 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001847 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1848 "Camera ID \"%s\" is a not valid camera ID", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001849 }
1850
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001851 StatusInternal cameraStatus = state->getStatus();
1852 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001853 cameraStatus != StatusInternal::NOT_AVAILABLE) {
1854 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001855 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1856 "Camera ID \"%s\" is a not valid camera ID", id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001857 }
1858
1859 {
1860 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001861 TorchModeStatus status;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001862 status_t err = getTorchStatusLocked(id, &status);
1863 if (err != OK) {
1864 if (err == NAME_NOT_FOUND) {
1865 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1866 "Camera \"%s\" does not have a flash unit", id.string());
1867 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001868 ALOGE("%s: getting current torch status failed for camera %s",
1869 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001870 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1871 "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
1872 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001873 }
1874
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001875 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001876 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001877 ALOGE("%s: torch mode of camera %s is not available because "
1878 "camera is in use", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001879 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1880 "Torch for camera \"%s\" is not available due to an existing camera user",
1881 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001882 } else {
1883 ALOGE("%s: torch mode of camera %s is not available due to "
1884 "insufficient resources", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001885 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1886 "Torch for camera \"%s\" is not available due to insufficient resources",
1887 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001888 }
1889 }
1890 }
1891
Ruben Brunk99e69712015-05-26 17:25:07 -07001892 {
1893 // Update UID map - this is used in the torch status changed callbacks, so must be done
1894 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07001895 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -07001896 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
1897 mTorchUidMap[id].first = uid;
1898 mTorchUidMap[id].second = uid;
1899 } else {
1900 // Set the pending UID
1901 mTorchUidMap[id].first = uid;
1902 }
1903 }
1904
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001905 status_t err = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07001906
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001907 if (err != OK) {
1908 int32_t errorCode;
1909 String8 msg;
1910 switch (err) {
1911 case -ENOSYS:
1912 msg = String8::format("Camera \"%s\" has no flashlight",
1913 id.string());
1914 errorCode = ERROR_ILLEGAL_ARGUMENT;
1915 break;
1916 default:
1917 msg = String8::format(
1918 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
1919 id.string(), enabled, strerror(-err), err);
1920 errorCode = ERROR_INVALID_OPERATION;
1921 }
1922 ALOGE("%s: %s", __FUNCTION__, msg.string());
1923 return STATUS_ERROR(errorCode, msg.string());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001924 }
1925
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001926 {
1927 // update the link to client's death
1928 Mutex::Autolock al(mTorchClientMapMutex);
1929 ssize_t index = mTorchClientMap.indexOfKey(id);
1930 if (enabled) {
1931 if (index == NAME_NOT_FOUND) {
1932 mTorchClientMap.add(id, clientBinder);
1933 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07001934 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001935 mTorchClientMap.replaceValueAt(index, clientBinder);
1936 }
1937 clientBinder->linkToDeath(this);
1938 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07001939 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001940 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001941 }
1942
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07001943 int clientPid = CameraThreadState::getCallingPid();
1944 const char *id_cstr = id.c_str();
1945 const char *torchState = enabled ? "on" : "off";
1946 ALOGI("Torch for camera id %s turned %s for client PID %d", id_cstr, torchState, clientPid);
1947 logTorchEvent(id_cstr, torchState , clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001948 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001949}
1950
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001951Status CameraService::notifySystemEvent(int32_t eventId,
1952 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001953 const int pid = CameraThreadState::getCallingPid();
1954 const int selfPid = getpid();
1955
1956 // Permission checks
1957 if (pid != selfPid) {
1958 // Ensure we're being called by system_server, or similar process with
1959 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001960 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001961 const int uid = CameraThreadState::getCallingUid();
1962 ALOGE("Permission Denial: cannot send updates to camera service about system"
1963 " events from pid=%d, uid=%d", pid, uid);
1964 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09001965 "No permission to send updates to camera service about system events"
1966 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001967 }
1968 }
1969
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001970 ATRACE_CALL();
1971
Ruben Brunk36597b22015-03-20 22:15:57 -07001972 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001973 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001974 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07001975 // from a system server crash
1976 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08001977 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001978 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07001979 break;
1980 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001981 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07001982 default: {
1983 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
1984 eventId);
1985 break;
1986 }
1987 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001988 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07001989}
1990
Emilian Peev53722fa2019-02-22 17:47:20 -08001991void CameraService::notifyMonitoredUids() {
1992 Mutex::Autolock lock(mStatusListenerLock);
1993
1994 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001995 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Emilian Peev53722fa2019-02-22 17:47:20 -08001996 if (!ret.isOk()) {
1997 ALOGE("%s: Failed to trigger permission callback: %d", __FUNCTION__,
1998 ret.exceptionCode());
1999 }
2000 }
2001}
2002
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002003Status CameraService::notifyDeviceStateChange(int64_t newState) {
2004 const int pid = CameraThreadState::getCallingPid();
2005 const int selfPid = getpid();
2006
2007 // Permission checks
2008 if (pid != selfPid) {
2009 // Ensure we're being called by system_server, or similar process with
2010 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002011 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002012 const int uid = CameraThreadState::getCallingUid();
2013 ALOGE("Permission Denial: cannot send updates to camera service about device"
2014 " state changes from pid=%d, uid=%d", pid, uid);
2015 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2016 "No permission to send updates to camera service about device state"
2017 " changes from pid=%d, uid=%d", pid, uid);
2018 }
2019 }
2020
2021 ATRACE_CALL();
2022
2023 using hardware::camera::provider::V2_5::DeviceState;
2024 hardware::hidl_bitfield<DeviceState> newDeviceState{};
2025 if (newState & ICameraService::DEVICE_STATE_BACK_COVERED) {
2026 newDeviceState |= DeviceState::BACK_COVERED;
2027 }
2028 if (newState & ICameraService::DEVICE_STATE_FRONT_COVERED) {
2029 newDeviceState |= DeviceState::FRONT_COVERED;
2030 }
2031 if (newState & ICameraService::DEVICE_STATE_FOLDED) {
2032 newDeviceState |= DeviceState::FOLDED;
2033 }
2034 // Only map vendor bits directly
2035 uint64_t vendorBits = static_cast<uint64_t>(newState) & 0xFFFFFFFF00000000l;
2036 newDeviceState |= vendorBits;
2037
2038 ALOGV("%s: New device state 0x%" PRIx64, __FUNCTION__, newDeviceState);
2039 Mutex::Autolock l(mServiceLock);
2040 mCameraProviderManager->notifyDeviceStateChange(newDeviceState);
2041
2042 return Status::ok();
2043}
2044
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002045 Status CameraService::getConcurrentStreamingCameraIds(
2046 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
2047 ATRACE_CALL();
2048 if (!concurrentCameraIds) {
2049 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
2050 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
2051 }
2052
2053 if (!mInitialized) {
2054 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2055 return STATUS_ERROR(ERROR_DISCONNECTED,
2056 "Camera subsystem is not available");
2057 }
2058 // First call into the provider and get the set of concurrent camera
2059 // combinations
2060 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
2061 mCameraProviderManager->getConcurrentStreamingCameraIds();
2062 for (auto &combination : concurrentCameraCombinations) {
2063 std::vector<std::string> validCombination;
2064 for (auto &cameraId : combination) {
2065 // if the camera state is not present, skip
2066 String8 cameraIdStr(cameraId.c_str());
2067 auto state = getCameraState(cameraIdStr);
2068 if (state == nullptr) {
2069 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
2070 continue;
2071 }
2072 StatusInternal status = state->getStatus();
2073 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
2074 continue;
2075 }
2076 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
2077 continue;
2078 }
2079 validCombination.push_back(cameraId);
2080 }
2081 if (validCombination.size() != 0) {
2082 concurrentCameraIds->push_back(std::move(validCombination));
2083 }
2084 }
2085 return Status::ok();
2086}
2087
2088Status CameraService::isConcurrentSessionConfigurationSupported(
2089 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
2090 /*out*/bool* isSupported) {
2091 if (!isSupported) {
2092 ALOGE("%s: isSupported is NULL", __FUNCTION__);
2093 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
2094 }
2095
2096 if (!mInitialized) {
2097 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2098 return STATUS_ERROR(ERROR_DISCONNECTED,
2099 "Camera subsystem is not available");
2100 }
2101
2102 // Check for camera permissions
2103 int callingPid = CameraThreadState::getCallingPid();
2104 int callingUid = CameraThreadState::getCallingUid();
2105 if ((callingPid != getpid()) && !checkPermission(sCameraPermission, callingPid, callingUid)) {
2106 ALOGE("%s: pid %d doesn't have camera permissions", __FUNCTION__, callingPid);
2107 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2108 "android.permission.CAMERA needed to call"
2109 "isConcurrentSessionConfigurationSupported");
2110 }
2111
2112 status_t res =
2113 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
2114 cameraIdsAndSessionConfigurations, isSupported);
2115 if (res != OK) {
2116 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
2117 "support %s (%d)", strerror(-res), res);
2118 }
2119 return Status::ok();
2120}
2121
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002122Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
2123 /*out*/
2124 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002125 return addListenerHelper(listener, cameraStatuses);
2126}
2127
2128Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
2129 /*out*/
2130 std::vector<hardware::CameraStatus> *cameraStatuses,
2131 bool isVendorListener) {
2132
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002133 ATRACE_CALL();
2134
Igor Murashkinbfc99152013-02-27 12:55:20 -08002135 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08002136
Ruben Brunk3450ba72015-06-16 11:00:37 -07002137 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002138 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002139 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002140 }
2141
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002142 auto clientUid = CameraThreadState::getCallingUid();
2143 auto clientPid = CameraThreadState::getCallingPid();
2144
Igor Murashkinbfc99152013-02-27 12:55:20 -08002145 Mutex::Autolock lock(mServiceLock);
2146
Ruben Brunkcc776712015-02-17 20:18:47 -08002147 {
2148 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08002149 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002150 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002151 ALOGW("%s: Tried to add listener %p which was already subscribed",
2152 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002153 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08002154 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002155 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002156
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002157 sp<ServiceListener> serviceListener =
2158 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08002159 auto ret = serviceListener->initialize();
2160 if (ret != NO_ERROR) {
2161 String8 msg = String8::format("Failed to initialize service listener: %s (%d)",
2162 strerror(-ret), ret);
2163 ALOGE("%s: %s", __FUNCTION__, msg.string());
2164 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
2165 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002166 // The listener still needs to be added to the list of listeners, regardless of what
2167 // permissions the listener process has / whether it is a vendor listener. Since it might be
2168 // eligible to listen to other camera ids.
2169 mListenerList.emplace_back(serviceListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08002170 mUidPolicy->registerMonitorUid(clientUid);
Igor Murashkinbfc99152013-02-27 12:55:20 -08002171 }
2172
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002173 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07002174 {
Ruben Brunkcc776712015-02-17 20:18:47 -08002175 Mutex::Autolock lock(mCameraStatesLock);
2176 for (auto& i : mCameraStates) {
Shuzhen Wang43858162020-01-10 13:42:15 -08002177 cameraStatuses->emplace_back(i.first,
2178 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds());
Igor Murashkincba2c162013-03-20 15:56:31 -07002179 }
2180 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002181 // Remove the camera statuses that should be hidden from the client, we do
2182 // this after collecting the states in order to avoid holding
2183 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
2184 // the same time.
2185 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
2186 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
2187 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
2188 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
2189 ALOGE("%s: Invalid camera id %s, skipping status update",
2190 __FUNCTION__, s.cameraId.c_str());
2191 return true;
2192 }
2193 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
2194 clientUid);}), cameraStatuses->end());
2195
Igor Murashkincba2c162013-03-20 15:56:31 -07002196
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002197 /*
2198 * Immediately signal current torch status to this listener only
2199 * This may be a subset of all the devices, so don't include it in the response directly
2200 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002201 {
2202 Mutex::Autolock al(mTorchStatusMutex);
2203 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002204 String16 id = String16(mTorchStatusMap.keyAt(i).string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002205 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002206 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002207 }
2208
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002209 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08002210}
Ruben Brunkcc776712015-02-17 20:18:47 -08002211
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002212Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002213 ATRACE_CALL();
2214
Igor Murashkinbfc99152013-02-27 12:55:20 -08002215 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
2216
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002217 if (listener == 0) {
2218 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002219 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002220 }
2221
Igor Murashkinbfc99152013-02-27 12:55:20 -08002222 Mutex::Autolock lock(mServiceLock);
2223
Ruben Brunkcc776712015-02-17 20:18:47 -08002224 {
2225 Mutex::Autolock lock(mStatusListenerLock);
2226 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002227 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
2228 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid());
2229 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08002230 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002231 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002232 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002233 }
2234 }
2235
2236 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
2237 __FUNCTION__, listener.get());
2238
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002239 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08002240}
2241
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002242Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002243
2244 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002245 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
2246
2247 if (parameters == NULL) {
2248 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002249 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07002250 }
2251
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002252 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002253
2254 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002255 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07002256 // Error logged by caller
2257 return ret;
2258 }
2259
2260 String8 shimParamsString8 = shimParams.flatten();
2261 String16 shimParamsString16 = String16(shimParamsString8);
2262
2263 *parameters = shimParamsString16;
2264
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002265 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07002266}
2267
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002268Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
2269 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002270 ATRACE_CALL();
2271
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002272 const String8 id = String8(cameraId);
2273
2274 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002275
2276 switch (apiVersion) {
2277 case API_VERSION_1:
2278 case API_VERSION_2:
2279 break;
2280 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002281 String8 msg = String8::format("Unknown API version %d", apiVersion);
2282 ALOGE("%s: %s", __FUNCTION__, msg.string());
2283 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002284 }
2285
Emilian Peev28ad2ea2017-02-07 16:14:32 +00002286 int deviceVersion = getDeviceVersion(id);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002287 switch (deviceVersion) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002288 case CAMERA_DEVICE_API_VERSION_1_0:
2289 case CAMERA_DEVICE_API_VERSION_3_0:
2290 case CAMERA_DEVICE_API_VERSION_3_1:
2291 if (apiVersion == API_VERSION_2) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002292 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without shim",
2293 __FUNCTION__, id.string(), deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002294 *isSupported = false;
2295 } else { // if (apiVersion == API_VERSION_1) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002296 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always supported",
2297 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002298 *isSupported = true;
2299 }
2300 break;
2301 case CAMERA_DEVICE_API_VERSION_3_2:
2302 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -07002303 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002304 case CAMERA_DEVICE_API_VERSION_3_5:
Yin-Chia Yeh56d98ba2020-01-16 16:57:14 -08002305 case CAMERA_DEVICE_API_VERSION_3_6:
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002306 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
2307 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002308 *isSupported = true;
2309 break;
2310 case -1: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002311 String8 msg = String8::format("Unknown camera ID %s", id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002312 ALOGE("%s: %s", __FUNCTION__, msg.string());
2313 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002314 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002315 default: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002316 String8 msg = String8::format("Unknown device version %x for device %s",
2317 deviceVersion, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002318 ALOGE("%s: %s", __FUNCTION__, msg.string());
2319 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
2320 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07002321 }
2322
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002323 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002324}
2325
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002326Status CameraService::isHiddenPhysicalCamera(const String16& cameraId,
2327 /*out*/ bool *isSupported) {
2328 ATRACE_CALL();
2329
2330 const String8 id = String8(cameraId);
2331
2332 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
2333 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(id.string());
2334
2335 return Status::ok();
2336}
2337
Ruben Brunkcc776712015-02-17 20:18:47 -08002338void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002339 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002340 for (auto& i : mActiveClientManager.getAll()) {
2341 auto clientSp = i->getValue();
2342 if (clientSp.get() == client) {
2343 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08002344 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07002345 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002346 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08002347}
2348
Ruben Brunkcc776712015-02-17 20:18:47 -08002349bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002350 bool ret = false;
2351 {
2352 // Acquire mServiceLock and prevent other clients from connecting
2353 std::unique_ptr<AutoConditionLock> lock =
2354 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08002355
Igor Murashkin634a5152013-02-20 17:15:11 -08002356
Ruben Brunkcc776712015-02-17 20:18:47 -08002357 std::vector<sp<BasicClient>> evicted;
2358 for (auto& i : mActiveClientManager.getAll()) {
2359 auto clientSp = i->getValue();
2360 if (clientSp.get() == nullptr) {
2361 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2362 mActiveClientManager.remove(i);
2363 continue;
2364 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08002365 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002366 mActiveClientManager.remove(i);
2367 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08002368
Ruben Brunkcc776712015-02-17 20:18:47 -08002369 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002370 clientSp->notifyError(
2371 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002372 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08002373 }
2374 }
2375
Ruben Brunkcc776712015-02-17 20:18:47 -08002376 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2377 // other clients from connecting in mServiceLockWrapper if held
2378 mServiceLock.unlock();
2379
Ruben Brunk36597b22015-03-20 22:15:57 -07002380 // Do not clear caller identity, remote caller should be client proccess
2381
Ruben Brunkcc776712015-02-17 20:18:47 -08002382 for (auto& i : evicted) {
2383 if (i.get() != nullptr) {
2384 i->disconnect();
2385 ret = true;
2386 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002387 }
2388
Ruben Brunkcc776712015-02-17 20:18:47 -08002389 // Reacquire mServiceLock
2390 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08002391
Ruben Brunkcc776712015-02-17 20:18:47 -08002392 } // lock is destroyed, allow further connect calls
2393
2394 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07002395}
2396
Ruben Brunkcc776712015-02-17 20:18:47 -08002397std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
2398 const String8& cameraId) const {
2399 std::shared_ptr<CameraState> state;
2400 {
2401 Mutex::Autolock lock(mCameraStatesLock);
2402 auto iter = mCameraStates.find(cameraId);
2403 if (iter != mCameraStates.end()) {
2404 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002405 }
2406 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002407 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002408}
2409
Ruben Brunkcc776712015-02-17 20:18:47 -08002410sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
2411 // Remove from active clients list
2412 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
2413 if (clientDescriptorPtr == nullptr) {
2414 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
2415 cameraId.string());
2416 return sp<BasicClient>{nullptr};
2417 }
2418
2419 return clientDescriptorPtr->getValue();
Keun young Parkd8973a72012-03-28 14:13:09 -07002420}
2421
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002422void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07002423 // Acquire mServiceLock and prevent other clients from connecting
2424 std::unique_ptr<AutoConditionLock> lock =
2425 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
2426
Ruben Brunk6267b532015-04-30 17:44:07 -07002427 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002428 for (size_t i = 0; i < newUserIds.size(); i++) {
2429 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07002430 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002431 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07002432 return;
2433 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002434 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07002435 }
2436
Ruben Brunka8ca9152015-04-07 14:23:40 -07002437
Ruben Brunk6267b532015-04-30 17:44:07 -07002438 if (newAllowedUsers == mAllowedUsers) {
2439 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
2440 return;
2441 }
2442
2443 logUserSwitch(mAllowedUsers, newAllowedUsers);
2444
2445 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07002446
2447 // Current user has switched, evict all current clients.
2448 std::vector<sp<BasicClient>> evicted;
2449 for (auto& i : mActiveClientManager.getAll()) {
2450 auto clientSp = i->getValue();
2451
2452 if (clientSp.get() == nullptr) {
2453 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2454 continue;
2455 }
2456
Ruben Brunk6267b532015-04-30 17:44:07 -07002457 // Don't evict clients that are still allowed.
2458 uid_t clientUid = clientSp->getClientUid();
2459 userid_t clientUserId = multiuser_get_user_id(clientUid);
2460 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
2461 continue;
2462 }
2463
Ruben Brunk36597b22015-03-20 22:15:57 -07002464 evicted.push_back(clientSp);
2465
2466 String8 curTime = getFormattedCurrentTime();
2467
2468 ALOGE("Evicting conflicting client for camera ID %s due to user change",
2469 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07002470
Ruben Brunk36597b22015-03-20 22:15:57 -07002471 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002472 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00002473 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
2474 " to user switch.", i->getKey().string(),
2475 String8{clientSp->getPackageName()}.string(),
2476 i->getOwnerId(), i->getPriority().getScore(),
2477 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07002478
2479 }
2480
2481 // Do not hold mServiceLock while disconnecting clients, but retain the condition
2482 // blocking other clients from connecting in mServiceLockWrapper if held.
2483 mServiceLock.unlock();
2484
2485 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07002486 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07002487
2488 for (auto& i : evicted) {
2489 i->disconnect();
2490 }
2491
Jayant Chowdhary12361932018-08-27 14:46:13 -07002492 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07002493
2494 // Reacquire mServiceLock
2495 mServiceLock.lock();
2496}
Ruben Brunkcc776712015-02-17 20:18:47 -08002497
Ruben Brunka8ca9152015-04-07 14:23:40 -07002498void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002499 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07002500 Mutex::Autolock l(mLogLock);
2501 mEventLog.add(String8::format("%s : %s", curTime.string(), event));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002502}
2503
Ruben Brunka8ca9152015-04-07 14:23:40 -07002504void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002505 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002506 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002507 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002508 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002509}
2510
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002511void CameraService::logDisconnectedOffline(const char* cameraId, int clientPid,
2512 const char* clientPackage) {
2513 // Log the clients evicted
2514 logEvent(String8::format("DISCONNECT offline device %s client for package %s (PID %d)",
2515 cameraId, clientPackage, clientPid));
2516}
2517
Ruben Brunka8ca9152015-04-07 14:23:40 -07002518void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002519 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002520 // Log the clients evicted
2521 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002522 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002523}
2524
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002525void CameraService::logConnectedOffline(const char* cameraId, int clientPid,
2526 const char* clientPackage) {
2527 // Log the clients evicted
2528 logEvent(String8::format("CONNECT offline device %s client for package %s (PID %d)", cameraId,
2529 clientPackage, clientPid));
2530}
2531
Ruben Brunka8ca9152015-04-07 14:23:40 -07002532void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002533 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002534 // Log the client rejected
2535 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002536 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002537}
2538
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002539void CameraService::logTorchEvent(const char* cameraId, const char *torchState, int clientPid) {
2540 // Log torch event
2541 logEvent(String8::format("Torch for camera id %s turned %s for client PID %d", cameraId,
2542 torchState, clientPid));
2543}
2544
Ruben Brunk6267b532015-04-30 17:44:07 -07002545void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
2546 const std::set<userid_t>& newUserIds) {
2547 String8 newUsers = toString(newUserIds);
2548 String8 oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002549 if (oldUsers.size() == 0) {
2550 oldUsers = "<None>";
2551 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07002552 // Log the new and old users
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002553 logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
Ruben Brunk6267b532015-04-30 17:44:07 -07002554 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002555}
2556
2557void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
2558 // Log the device removal
2559 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
2560}
2561
2562void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
2563 // Log the device removal
2564 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
2565}
2566
2567void CameraService::logClientDied(int clientPid, const char* reason) {
2568 // Log the device removal
2569 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07002570}
2571
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002572void CameraService::logServiceError(const char* msg, int errorCode) {
2573 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002574 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002575}
2576
Ruben Brunk36597b22015-03-20 22:15:57 -07002577status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
2578 uint32_t flags) {
2579
Mathias Agopian65ab4712010-07-14 17:59:35 -07002580 // Permission checks
2581 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002582 case SHELL_COMMAND_TRANSACTION: {
2583 int in = data.readFileDescriptor();
2584 int out = data.readFileDescriptor();
2585 int err = data.readFileDescriptor();
2586 int argc = data.readInt32();
2587 Vector<String16> args;
2588 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
2589 args.add(data.readString16());
2590 }
2591 sp<IBinder> unusedCallback;
2592 sp<IResultReceiver> resultReceiver;
2593 status_t status;
2594 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
2595 return status;
2596 }
2597 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
2598 return status;
2599 }
2600 status = shellCommand(in, out, err, args);
2601 if (resultReceiver != nullptr) {
2602 resultReceiver->send(status);
2603 }
2604 return NO_ERROR;
2605 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002606 }
2607
2608 return BnCameraService::onTransact(code, data, reply, flags);
2609}
2610
Mathias Agopian65ab4712010-07-14 17:59:35 -07002611// We share the media players for shutter and recording sound for all clients.
2612// A reference count is kept to determine when we will actually release the
2613// media players.
2614
Jaekyun Seokef498052018-03-23 13:09:44 +09002615sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
2616 sp<MediaPlayer> mp = new MediaPlayer();
2617 status_t error;
2618 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08002619 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09002620 error = mp->prepare();
2621 }
2622 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00002623 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09002624 mp->disconnect();
2625 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002626 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002627 }
2628 return mp;
2629}
2630
username5755fea2018-12-27 09:48:08 +08002631void CameraService::increaseSoundRef() {
2632 Mutex::Autolock lock(mSoundLock);
2633 mSoundRef++;
2634}
2635
2636void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002637 ATRACE_CALL();
2638
username5755fea2018-12-27 09:48:08 +08002639 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
2640 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
2641 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
2642 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
2643 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
2644 }
2645 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
2646 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
2647 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
2648 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002649 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08002650 }
2651 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
2652 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
2653 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
2654 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
2655 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002656 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002657}
2658
username5755fea2018-12-27 09:48:08 +08002659void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002660 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002661 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002662 if (--mSoundRef) return;
2663
2664 for (int i = 0; i < NUM_SOUNDS; i++) {
2665 if (mSoundPlayer[i] != 0) {
2666 mSoundPlayer[i]->disconnect();
2667 mSoundPlayer[i].clear();
2668 }
2669 }
2670}
2671
2672void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002673 ATRACE_CALL();
2674
Mathias Agopian65ab4712010-07-14 17:59:35 -07002675 LOG1("playSound(%d)", kind);
2676 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002677 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002678 sp<MediaPlayer> player = mSoundPlayer[kind];
2679 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08002680 player->seekTo(0);
2681 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002682 }
2683}
2684
2685// ----------------------------------------------------------------------------
2686
2687CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07002688 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002689 const String16& clientPackageName,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002690 const std::unique_ptr<String16>& clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002691 const String8& cameraIdStr,
2692 int api1CameraId, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002693 int clientPid, uid_t clientUid,
2694 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002695 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08002696 IInterface::asBinder(cameraClient),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002697 clientPackageName, clientFeatureId,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002698 cameraIdStr, cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002699 clientPid, clientUid,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002700 servicePid),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002701 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08002702{
Jayant Chowdhary12361932018-08-27 14:46:13 -07002703 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002704 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002705
Igor Murashkin44cfcf02013-03-01 16:22:28 -08002706 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002707
username5755fea2018-12-27 09:48:08 +08002708 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002709
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002710 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002711}
2712
Mathias Agopian65ab4712010-07-14 17:59:35 -07002713// tear down the client
2714CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002715 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08002716 mDestructionStarted = true;
2717
username5755fea2018-12-27 09:48:08 +08002718 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002719 // unconditionally disconnect. function is idempotent
2720 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002721}
2722
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002723sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
2724
Igor Murashkin634a5152013-02-20 17:15:11 -08002725CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002726 const sp<IBinder>& remoteCallback,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002727 const String16& clientPackageName, const std::unique_ptr<String16>& clientFeatureId,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002728 const String8& cameraIdStr, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002729 int clientPid, uid_t clientUid,
2730 int servicePid):
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002731 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002732 mClientPackageName(clientPackageName),
2733 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002734 mServicePid(servicePid),
2735 mDisconnected(false),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002736 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002737 mRemoteBinder(remoteCallback)
Igor Murashkin634a5152013-02-20 17:15:11 -08002738{
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002739 if (clientFeatureId) {
2740 mClientFeatureId = std::unique_ptr<String16>(new String16(*clientFeatureId));
2741 } else {
2742 mClientFeatureId = std::unique_ptr<String16>();
2743 }
2744
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002745 if (sCameraService == nullptr) {
2746 sCameraService = cameraService;
2747 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002748 mOpsActive = false;
Igor Murashkin634a5152013-02-20 17:15:11 -08002749 mDestructionStarted = false;
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08002750
2751 // In some cases the calling code has no access to the package it runs under.
2752 // For example, NDK camera API.
2753 // In this case we will get the packages for the calling UID and pick the first one
2754 // for attributing the app op. This will work correctly for runtime permissions
2755 // as for legacy apps we will toggle the app op for all packages in the UID.
2756 // The caveat is that the operation may be attributed to the wrong package and
2757 // stats based on app ops may be slightly off.
2758 if (mClientPackageName.size() <= 0) {
2759 sp<IServiceManager> sm = defaultServiceManager();
2760 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
2761 if (binder == 0) {
2762 ALOGE("Cannot get permission service");
2763 // Leave mClientPackageName unchanged (empty) and the further interaction
2764 // with camera will fail in BasicClient::startCameraOps
2765 return;
2766 }
2767
2768 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
2769 Vector<String16> packages;
2770
2771 permCtrl->getPackagesForUid(mClientUid, packages);
2772
2773 if (packages.isEmpty()) {
2774 ALOGE("No packages for calling UID");
2775 // Leave mClientPackageName unchanged (empty) and the further interaction
2776 // with camera will fail in BasicClient::startCameraOps
2777 return;
2778 }
2779 mClientPackageName = packages[0];
2780 }
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002781 if (!hardware::IPCThreadState::self()->isServingCall()) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002782 mAppOpsManager = std::make_unique<AppOpsManager>();
2783 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002784}
2785
2786CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002787 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08002788 mDestructionStarted = true;
2789}
2790
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002791binder::Status CameraService::BasicClient::disconnect() {
2792 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002793 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002794 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07002795 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07002796 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002797
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002798 sCameraService->removeByClient(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002799 sCameraService->logDisconnected(mCameraIdStr, mClientPid, String8(mClientPackageName));
Peter Kalauskasa29c1352018-10-10 12:05:42 -07002800 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
2801 mCameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002802
2803 sp<IBinder> remote = getRemote();
2804 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002805 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08002806 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002807
2808 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07002809 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002810 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
2811 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
2812 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002813
Igor Murashkincba2c162013-03-20 15:56:31 -07002814 // client shouldn't be able to call into us anymore
2815 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002816
2817 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08002818}
2819
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002820status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
2821 // No dumping of clients directly over Binder,
2822 // must go through CameraService::dump
2823 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07002824 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002825 return OK;
2826}
2827
Ruben Brunkcc776712015-02-17 20:18:47 -08002828String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002829 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08002830}
2831
2832
2833int CameraService::BasicClient::getClientPid() const {
2834 return mClientPid;
2835}
2836
Ruben Brunk6267b532015-04-30 17:44:07 -07002837uid_t CameraService::BasicClient::getClientUid() const {
2838 return mClientUid;
2839}
2840
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002841bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
2842 // Defaults to API2.
2843 return level == API_2;
2844}
2845
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002846status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002847 {
2848 Mutex::Autolock l(mAudioRestrictionLock);
2849 mAudioRestriction = mode;
2850 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002851 sCameraService->updateAudioRestriction();
2852 return OK;
2853}
2854
2855int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002856 return sCameraService->updateAudioRestriction();
2857}
2858
2859int32_t CameraService::BasicClient::getAudioRestriction() const {
2860 Mutex::Autolock l(mAudioRestrictionLock);
2861 return mAudioRestriction;
2862}
2863
2864bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
2865 switch (mode) {
2866 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
2867 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
2868 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
2869 return true;
2870 default:
2871 return false;
2872 }
2873}
2874
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002875status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002876 ATRACE_CALL();
2877
Igor Murashkine6800ce2013-03-04 17:25:57 -08002878 {
2879 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002880 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08002881 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002882 if (mAppOpsManager != nullptr) {
2883 // Notify app ops that the camera is not available
2884 mOpsCallback = new OpsCallback(this);
2885 int32_t res;
2886 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
2887 mClientPackageName, mOpsCallback);
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002888 res = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
2889 mClientPackageName, /*startIfModeDefault*/ false, mClientFeatureId,
2890 String16("start camera ") + String16(mCameraIdStr));
Igor Murashkine6800ce2013-03-04 17:25:57 -08002891
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002892 if (res == AppOpsManager::MODE_ERRORED) {
2893 ALOGI("Camera %s: Access for \"%s\" has been revoked",
2894 mCameraIdStr.string(), String8(mClientPackageName).string());
2895 return PERMISSION_DENIED;
2896 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002897
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002898 if (res == AppOpsManager::MODE_IGNORED) {
2899 ALOGI("Camera %s: Access for \"%s\" has been restricted",
2900 mCameraIdStr.string(), String8(mClientPackageName).string());
2901 // Return the same error as for device policy manager rejection
2902 return -EACCES;
2903 }
Svetoslav28e8ef72015-05-11 19:21:31 -07002904 }
2905
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002906 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002907
2908 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002909 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002910
Emilian Peev573291c2018-02-10 02:10:56 +00002911 int apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_1;
2912 if (canCastToApiClient(API_2)) {
2913 apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_2;
2914 }
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002915 // Transition device state to OPEN
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002916 sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_OPEN,
Emilian Peev573291c2018-02-10 02:10:56 +00002917 mCameraIdStr, mCameraFacing, mClientPackageName, apiLevel);
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002918
Emilian Peev53722fa2019-02-22 17:47:20 -08002919 sCameraService->mUidPolicy->registerMonitorUid(mClientUid);
2920
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002921 return OK;
2922}
2923
2924status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002925 ATRACE_CALL();
2926
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002927 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002928 if (mOpsActive) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002929 // Notify app ops that the camera is available again
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002930 if (mAppOpsManager != nullptr) {
2931 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002932 mClientPackageName, mClientFeatureId);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002933 mOpsActive = false;
2934 }
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002935 // This function is called when a client disconnects. This should
2936 // release the camera, but actually only if it was in a proper
2937 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002938 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002939 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002940
Ruben Brunkcc776712015-02-17 20:18:47 -08002941 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002942 sCameraService->updateStatus(StatusInternal::PRESENT,
2943 mCameraIdStr, rejected);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002944
Emilian Peev573291c2018-02-10 02:10:56 +00002945 int apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_1;
2946 if (canCastToApiClient(API_2)) {
2947 apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_2;
2948 }
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002949 // Transition device state to CLOSED
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002950 sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_CLOSED,
Emilian Peev573291c2018-02-10 02:10:56 +00002951 mCameraIdStr, mCameraFacing, mClientPackageName, apiLevel);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002952 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002953 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002954 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
2955 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002956 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002957 mOpsCallback.clear();
2958
Emilian Peev53722fa2019-02-22 17:47:20 -08002959 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid);
2960
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002961 return OK;
2962}
2963
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002964void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002965 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002966 if (mAppOpsManager == nullptr) {
2967 return;
2968 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002969 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002970 if (op != AppOpsManager::OP_CAMERA) {
2971 ALOGW("Unexpected app ops notification received: %d", op);
2972 return;
2973 }
2974
2975 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002976 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002977 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002978 ALOGV("checkOp returns: %d, %s ", res,
2979 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
2980 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
2981 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
2982 "UNKNOWN");
2983
2984 if (res != AppOpsManager::MODE_ALLOWED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002985 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002986 String8(mClientPackageName).string());
Svet Ganova453d0d2018-01-11 15:37:58 -08002987 block();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002988 }
2989}
2990
Svet Ganova453d0d2018-01-11 15:37:58 -08002991void CameraService::BasicClient::block() {
2992 ATRACE_CALL();
2993
2994 // Reset the client PID to allow server-initiated disconnect,
2995 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07002996 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08002997 CaptureResultExtras resultExtras; // a dummy result (invalid)
2998 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
2999 disconnect();
3000}
3001
Mathias Agopian65ab4712010-07-14 17:59:35 -07003002// ----------------------------------------------------------------------------
3003
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003004void CameraService::Client::notifyError(int32_t errorCode,
Jianing Weicb0652e2014-03-12 18:29:36 -07003005 const CaptureResultExtras& resultExtras) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08003006 (void) resultExtras;
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003007 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07003008 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
3009 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
3010 api1ErrorCode = CAMERA_ERROR_DISABLED;
3011 }
3012 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003013 } else {
3014 ALOGE("mRemoteCallback is NULL!!");
3015 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003016}
3017
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003018// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003019binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003020 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003021 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08003022}
3023
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003024bool CameraService::Client::canCastToApiClient(apiLevel level) const {
3025 return level == API_1;
3026}
3027
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003028CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
3029 mClient(client) {
3030}
3031
3032void CameraService::Client::OpsCallback::opChanged(int32_t op,
3033 const String16& packageName) {
3034 sp<BasicClient> client = mClient.promote();
3035 if (client != NULL) {
3036 client->opChanged(op, packageName);
3037 }
3038}
3039
Mathias Agopian65ab4712010-07-14 17:59:35 -07003040// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08003041// UidPolicy
3042// ----------------------------------------------------------------------------
3043
3044void CameraService::UidPolicy::registerSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003045 Mutex::Autolock _l(mUidLock);
3046
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003047 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07003048 status_t res = mAm.linkToDeath(this);
3049 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08003050 | ActivityManager::UID_OBSERVER_IDLE
Emilian Peev53722fa2019-02-22 17:47:20 -08003051 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganova453d0d2018-01-11 15:37:58 -08003052 ActivityManager::PROCESS_STATE_UNKNOWN,
3053 String16("cameraserver"));
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003054 if (res == OK) {
3055 mRegistered = true;
3056 ALOGV("UidPolicy: Registered with ActivityManager");
3057 }
Svet Ganova453d0d2018-01-11 15:37:58 -08003058}
3059
3060void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003061 Mutex::Autolock _l(mUidLock);
3062
Steven Moreland2f348142019-07-02 15:59:07 -07003063 mAm.unregisterUidObserver(this);
3064 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003065 mRegistered = false;
3066 mActiveUids.clear();
3067 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08003068}
3069
3070void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
3071 onUidIdle(uid, disabled);
3072}
3073
3074void CameraService::UidPolicy::onUidActive(uid_t uid) {
3075 Mutex::Autolock _l(mUidLock);
3076 mActiveUids.insert(uid);
3077}
3078
3079void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
3080 bool deleted = false;
3081 {
3082 Mutex::Autolock _l(mUidLock);
3083 if (mActiveUids.erase(uid) > 0) {
3084 deleted = true;
3085 }
3086 }
3087 if (deleted) {
3088 sp<CameraService> service = mService.promote();
3089 if (service != nullptr) {
3090 service->blockClientsForUid(uid);
3091 }
3092 }
3093}
3094
Emilian Peev53722fa2019-02-22 17:47:20 -08003095void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07003096 int64_t procStateSeq __unused, int32_t capability __unused) {
Emilian Peev53722fa2019-02-22 17:47:20 -08003097 bool procStateChange = false;
3098 {
3099 Mutex::Autolock _l(mUidLock);
3100 if ((mMonitoredUids.find(uid) != mMonitoredUids.end()) &&
3101 (mMonitoredUids[uid].first != procState)) {
3102 mMonitoredUids[uid].first = procState;
3103 procStateChange = true;
3104 }
3105 }
3106
3107 if (procStateChange) {
3108 sp<CameraService> service = mService.promote();
3109 if (service != nullptr) {
3110 service->notifyMonitoredUids();
3111 }
3112 }
3113}
3114
3115void CameraService::UidPolicy::registerMonitorUid(uid_t uid) {
3116 Mutex::Autolock _l(mUidLock);
3117 auto it = mMonitoredUids.find(uid);
3118 if (it != mMonitoredUids.end()) {
3119 it->second.second++;
3120 } else {
3121 mMonitoredUids.emplace(
3122 std::pair<uid_t, std::pair<int32_t, size_t>> (uid,
3123 std::pair<int32_t, size_t> (ActivityManager::PROCESS_STATE_NONEXISTENT, 1)));
3124 }
3125}
3126
3127void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid) {
3128 Mutex::Autolock _l(mUidLock);
3129 auto it = mMonitoredUids.find(uid);
3130 if (it != mMonitoredUids.end()) {
3131 it->second.second--;
3132 if (it->second.second == 0) {
3133 mMonitoredUids.erase(it);
3134 }
3135 } else {
3136 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
3137 }
3138}
3139
Svet Ganov7b4ab782018-03-25 12:48:10 -07003140bool CameraService::UidPolicy::isUidActive(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003141 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003142 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003143}
3144
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003145static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
3146static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003147
Svet Ganov7b4ab782018-03-25 12:48:10 -07003148bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003149 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003150 // If activity manager is unreachable, assume everything is active
3151 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003152 return true;
3153 }
3154 auto it = mOverrideUids.find(uid);
3155 if (it != mOverrideUids.end()) {
3156 return it->second;
3157 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003158 bool active = mActiveUids.find(uid) != mActiveUids.end();
3159 if (!active) {
3160 // We want active UIDs to always access camera with their first attempt since
3161 // there is no guarantee the app is robustly written and would retry getting
3162 // the camera on failure. The inverse case is not a problem as we would take
3163 // camera away soon once we get the callback that the uid is no longer active.
3164 ActivityManager am;
3165 // Okay to access with a lock held as UID changes are dispatched without
3166 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07003167 int64_t startTimeMillis = 0;
3168 do {
3169 // TODO: Fix this b/109950150!
3170 // Okay this is a hack. There is a race between the UID turning active and
3171 // activity being resumed. The proper fix is very risky, so we temporary add
3172 // some polling which should happen pretty rarely anyway as the race is hard
3173 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003174 active = mActiveUids.find(uid) != mActiveUids.end();
3175 if (!active) active = am.isUidActive(uid, callingPackage);
Svet Ganov94ec46f2018-06-08 15:03:46 -07003176 if (active) {
3177 break;
3178 }
3179 if (startTimeMillis <= 0) {
3180 startTimeMillis = uptimeMillis();
3181 }
3182 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003183 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003184 if (remainingTimeMillis <= 0) {
3185 break;
3186 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003187 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
3188
3189 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003190 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003191 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003192 } while (true);
3193
Svet Ganov7b4ab782018-03-25 12:48:10 -07003194 if (active) {
3195 // Now that we found out the UID is actually active, cache that
3196 mActiveUids.insert(uid);
3197 }
3198 }
3199 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08003200}
3201
Varun Shahb42f1eb2019-04-16 14:45:13 -07003202int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
3203 Mutex::Autolock _l(mUidLock);
3204 return getProcStateLocked(uid);
3205}
3206
3207int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
3208 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
3209 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
3210 procState = mMonitoredUids[uid].first;
3211 }
3212 return procState;
3213}
3214
Svet Ganov7b4ab782018-03-25 12:48:10 -07003215void CameraService::UidPolicy::UidPolicy::addOverrideUid(uid_t uid,
3216 String16 callingPackage, bool active) {
3217 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08003218}
3219
Svet Ganov7b4ab782018-03-25 12:48:10 -07003220void CameraService::UidPolicy::removeOverrideUid(uid_t uid, String16 callingPackage) {
3221 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08003222}
3223
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003224void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
3225 Mutex::Autolock _l(mUidLock);
3226 ALOGV("UidPolicy: ActivityManager has died");
3227 mRegistered = false;
3228 mActiveUids.clear();
3229}
3230
Svet Ganov7b4ab782018-03-25 12:48:10 -07003231void CameraService::UidPolicy::updateOverrideUid(uid_t uid, String16 callingPackage,
3232 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003233 bool wasActive = false;
3234 bool isActive = false;
3235 {
3236 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003237 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003238 mOverrideUids.erase(uid);
3239 if (insert) {
3240 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
3241 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003242 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003243 }
3244 if (wasActive != isActive && !isActive) {
3245 sp<CameraService> service = mService.promote();
3246 if (service != nullptr) {
3247 service->blockClientsForUid(uid);
3248 }
3249 }
3250}
3251
3252// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08003253// SensorPrivacyPolicy
3254// ----------------------------------------------------------------------------
3255void CameraService::SensorPrivacyPolicy::registerSelf() {
3256 Mutex::Autolock _l(mSensorPrivacyLock);
3257 if (mRegistered) {
3258 return;
3259 }
Steven Moreland3cf67172020-01-29 11:44:22 -08003260 mSpm.addSensorPrivacyListener(this);
3261 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
3262 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003263 if (res == OK) {
3264 mRegistered = true;
3265 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
3266 }
3267}
3268
3269void CameraService::SensorPrivacyPolicy::unregisterSelf() {
3270 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08003271 mSpm.removeSensorPrivacyListener(this);
3272 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003273 mRegistered = false;
3274 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
3275}
3276
3277bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
3278 Mutex::Autolock _l(mSensorPrivacyLock);
3279 return mSensorPrivacyEnabled;
3280}
3281
3282binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
3283 {
3284 Mutex::Autolock _l(mSensorPrivacyLock);
3285 mSensorPrivacyEnabled = enabled;
3286 }
3287 // if sensor privacy is enabled then block all clients from accessing the camera
3288 if (enabled) {
3289 sp<CameraService> service = mService.promote();
3290 if (service != nullptr) {
3291 service->blockAllClients();
3292 }
3293 }
3294 return binder::Status::ok();
3295}
3296
3297void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
3298 Mutex::Autolock _l(mSensorPrivacyLock);
3299 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
3300 mRegistered = false;
3301}
3302
3303// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003304// CameraState
3305// ----------------------------------------------------------------------------
3306
3307CameraService::CameraState::CameraState(const String8& id, int cost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003308 const std::set<String8>& conflicting, SystemCameraKind systemCameraKind) : mId(id),
3309 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
3310 mSystemCameraKind(systemCameraKind) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08003311
3312CameraService::CameraState::~CameraState() {}
3313
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003314CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003315 Mutex::Autolock lock(mStatusLock);
3316 return mStatus;
3317}
3318
Shuzhen Wang43858162020-01-10 13:42:15 -08003319std::vector<String8> CameraService::CameraState::getUnavailablePhysicalIds() const {
3320 Mutex::Autolock lock(mStatusLock);
3321 std::vector<String8> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
3322 return res;
3323}
3324
Ruben Brunkcc776712015-02-17 20:18:47 -08003325CameraParameters CameraService::CameraState::getShimParams() const {
3326 return mShimParams;
3327}
3328
3329void CameraService::CameraState::setShimParams(const CameraParameters& params) {
3330 mShimParams = params;
3331}
3332
3333int CameraService::CameraState::getCost() const {
3334 return mCost;
3335}
3336
3337std::set<String8> CameraService::CameraState::getConflicting() const {
3338 return mConflicting;
3339}
3340
3341String8 CameraService::CameraState::getId() const {
3342 return mId;
3343}
3344
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003345SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
3346 return mSystemCameraKind;
3347}
3348
Shuzhen Wang43858162020-01-10 13:42:15 -08003349bool CameraService::CameraState::addUnavailablePhysicalId(const String8& physicalId) {
3350 Mutex::Autolock lock(mStatusLock);
3351 auto result = mUnavailablePhysicalIds.insert(physicalId);
3352 return result.second;
3353}
3354
3355bool CameraService::CameraState::removeUnavailablePhysicalId(const String8& physicalId) {
3356 Mutex::Autolock lock(mStatusLock);
3357 auto count = mUnavailablePhysicalIds.erase(physicalId);
3358 return count > 0;
3359}
3360
Ruben Brunkcc776712015-02-17 20:18:47 -08003361// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07003362// ClientEventListener
3363// ----------------------------------------------------------------------------
3364
3365void CameraService::ClientEventListener::onClientAdded(
3366 const resource_policy::ClientDescriptor<String8,
3367 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003368 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003369 if (basicClient.get() != nullptr) {
3370 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3371 notifier.noteStartCamera(descriptor.getKey(),
3372 static_cast<int>(basicClient->getClientUid()));
3373 }
3374}
3375
3376void CameraService::ClientEventListener::onClientRemoved(
3377 const resource_policy::ClientDescriptor<String8,
3378 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003379 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003380 if (basicClient.get() != nullptr) {
3381 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3382 notifier.noteStopCamera(descriptor.getKey(),
3383 static_cast<int>(basicClient->getClientUid()));
3384 }
3385}
3386
3387
3388// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003389// CameraClientManager
3390// ----------------------------------------------------------------------------
3391
Ruben Brunk99e69712015-05-26 17:25:07 -07003392CameraService::CameraClientManager::CameraClientManager() {
3393 setListener(std::make_shared<ClientEventListener>());
3394}
3395
Ruben Brunkcc776712015-02-17 20:18:47 -08003396CameraService::CameraClientManager::~CameraClientManager() {}
3397
3398sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
3399 const String8& id) const {
3400 auto descriptor = get(id);
3401 if (descriptor == nullptr) {
3402 return sp<BasicClient>{nullptr};
3403 }
3404 return descriptor->getValue();
3405}
3406
3407String8 CameraService::CameraClientManager::toString() const {
3408 auto all = getAll();
3409 String8 ret("[");
3410 bool hasAny = false;
3411 for (auto& i : all) {
3412 hasAny = true;
3413 String8 key = i->getKey();
3414 int32_t cost = i->getCost();
3415 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00003416 int32_t score = i->getPriority().getScore();
3417 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08003418 auto conflicting = i->getConflicting();
3419 auto clientSp = i->getValue();
3420 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07003421 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08003422 if (clientSp.get() != nullptr) {
3423 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07003424 uid_t clientUid = clientSp->getClientUid();
3425 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003426 }
Emilian Peev8131a262017-02-01 12:33:43 +00003427 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
3428 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08003429
Ruben Brunk6267b532015-04-30 17:44:07 -07003430 if (clientSp.get() != nullptr) {
3431 ret.appendFormat("User Id: %d, ", clientUserId);
3432 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003433 if (packageName.size() != 0) {
3434 ret.appendFormat("Client Package Name: %s", packageName.string());
3435 }
3436
3437 ret.append(", Conflicting Client Devices: {");
3438 for (auto& j : conflicting) {
3439 ret.appendFormat("%s, ", j.string());
3440 }
3441 ret.append("})");
3442 }
3443 if (hasAny) ret.append("\n");
3444 ret.append("]\n");
3445 return ret;
3446}
3447
3448CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3449 const String8& key, const sp<BasicClient>& value, int32_t cost,
Emilian Peev8131a262017-02-01 12:33:43 +00003450 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
3451 int32_t state) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003452
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003453 bool isVendorClient = hardware::IPCThreadState::self()->isServingCall();
3454 int32_t score_adj = isVendorClient ? kVendorClientScore : score;
3455 int32_t state_adj = isVendorClient ? kVendorClientState: state;
3456
Ruben Brunkcc776712015-02-17 20:18:47 -08003457 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003458 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj, isVendorClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08003459}
3460
3461CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3462 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
3463 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00003464 partial->getConflicting(), partial->getPriority().getScore(),
3465 partial->getOwnerId(), partial->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08003466}
3467
3468// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07003469
3470static const int kDumpLockRetries = 50;
3471static const int kDumpLockSleep = 60000;
3472
3473static bool tryLock(Mutex& mutex)
3474{
3475 bool locked = false;
3476 for (int i = 0; i < kDumpLockRetries; ++i) {
3477 if (mutex.tryLock() == NO_ERROR) {
3478 locked = true;
3479 break;
3480 }
3481 usleep(kDumpLockSleep);
3482 }
3483 return locked;
3484}
3485
3486status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003487 ATRACE_CALL();
3488
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003489 if (checkCallingPermission(sDumpPermission) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003490 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07003491 CameraThreadState::getCallingPid(),
3492 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003493 return NO_ERROR;
3494 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003495 bool locked = tryLock(mServiceLock);
3496 // failed to lock - CameraService is probably deadlocked
3497 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003498 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003499 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003500
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003501 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003502 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07003503
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003504 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003505 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08003506
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003507 if (locked) mServiceLock.unlock();
3508 return NO_ERROR;
3509 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003510 dprintf(fd, "\n== Service global info: ==\n\n");
3511 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003512 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07003513 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
3514 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003515 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
3516 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
3517 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003518 String8 activeClientString = mActiveClientManager.toString();
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003519 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
3520 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003521
3522 dumpEventLog(fd);
3523
3524 bool stateLocked = tryLock(mCameraStatesLock);
3525 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003526 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003527 }
3528
Emilian Peevbd8c5032018-02-14 23:05:40 +00003529 int argSize = args.size();
3530 for (int i = 0; i < argSize; i++) {
3531 if (args[i] == TagMonitor::kMonitorOption) {
3532 if (i + 1 < argSize) {
3533 mMonitorTags = String8(args[i + 1]);
3534 }
3535 break;
3536 }
3537 }
3538
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003539 for (auto& state : mCameraStates) {
3540 String8 cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003541
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003542 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003543
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003544 CameraParameters p = state.second->getShimParams();
3545 if (!p.isEmpty()) {
3546 dprintf(fd, " Camera1 API shim is using parameters:\n ");
3547 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003548 }
3549
3550 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08003551 if (clientDescriptor != nullptr) {
3552 dprintf(fd, " Device %s is open. Client instance dump:\n",
3553 cameraId.string());
3554 dprintf(fd, " Client priority score: %d state: %d\n",
3555 clientDescriptor->getPriority().getScore(),
3556 clientDescriptor->getPriority().getState());
3557 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
3558
3559 auto client = clientDescriptor->getValue();
3560 dprintf(fd, " Client package: %s\n",
3561 String8(client->getPackageName()).string());
3562
3563 client->dumpClient(fd, args);
3564 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003565 dprintf(fd, " Device %s is closed, no client instance\n",
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003566 cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003567 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003568
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003569 }
3570
3571 if (stateLocked) mCameraStatesLock.unlock();
3572
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003573 if (locked) mServiceLock.unlock();
3574
Emilian Peevf53f66e2017-04-11 14:29:43 +01003575 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003576
3577 dprintf(fd, "\n== Vendor tags: ==\n\n");
3578
3579 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
3580 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00003581 sp<VendorTagDescriptorCache> cache =
3582 VendorTagDescriptorCache::getGlobalVendorTagCache();
3583 if (cache == NULL) {
3584 dprintf(fd, "No vendor tags.\n");
3585 } else {
3586 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
3587 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003588 } else {
3589 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
3590 }
3591
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003592 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003593 dprintf(fd, "\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003594 camera3::CameraTraces::dump(fd, args);
3595
3596 // Process dump arguments, if any
3597 int n = args.size();
3598 String16 verboseOption("-v");
3599 String16 unreachableOption("--unreachable");
3600 for (int i = 0; i < n; i++) {
3601 if (args[i] == verboseOption) {
3602 // change logging level
3603 if (i + 1 >= n) continue;
3604 String8 levelStr(args[i+1]);
3605 int level = atoi(levelStr.string());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003606 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003607 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003608 } else if (args[i] == unreachableOption) {
3609 // Dump memory analysis
3610 // TODO - should limit be an argument parameter?
3611 UnreachableMemoryInfo info;
3612 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
3613 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003614 dprintf(fd, "\n== Unable to dump unreachable memory. "
3615 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003616 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003617 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003618 std::string s = info.ToString(/*log_contents*/ true);
3619 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003620 }
3621 }
3622 }
3623 return NO_ERROR;
3624}
3625
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003626void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003627 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003628
3629 Mutex::Autolock l(mLogLock);
3630 for (const auto& msg : mEventLog) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003631 dprintf(fd, " %s\n", msg.string());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003632 }
3633
3634 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003635 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003636 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003637 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003638 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003639 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003640}
3641
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003642void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003643 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003644 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
3645 if (mTorchClientMap[i] == who) {
3646 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003647 String8 cameraId = mTorchClientMap.keyAt(i);
3648 status_t res = mFlashlight->setTorchMode(cameraId, false);
3649 if (res) {
3650 ALOGE("%s: torch client died but couldn't turn off torch: "
3651 "%s (%d)", __FUNCTION__, strerror(-res), res);
3652 return;
3653 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003654 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003655 break;
3656 }
3657 }
3658}
3659
Ruben Brunkcc776712015-02-17 20:18:47 -08003660/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003661
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003662 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07003663 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
3664 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003665 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003666 // PID here is approximate and can be wrong.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003667 logClientDied(CameraThreadState::getCallingPid(), String8("Binder died unexpectedly"));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003668
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003669 // check torch client
3670 handleTorchClientBinderDied(who);
3671
3672 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08003673 if(!evictClientIdByRemote(who)) {
3674 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003675 return;
3676 }
3677
Ruben Brunkcc776712015-02-17 20:18:47 -08003678 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
3679 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003680}
3681
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003682void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003683 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08003684}
3685
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003686void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
3687 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003688 // Do not lock mServiceLock here or can get into a deadlock from
3689 // connect() -> disconnect -> updateStatus
3690
3691 auto state = getCameraState(cameraId);
3692
3693 if (state == nullptr) {
3694 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
3695 cameraId.string());
3696 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07003697 }
3698
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003699 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
3700 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3701 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3702 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
3703 return;
3704 }
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003705 bool supportsHAL3 = false;
3706 // supportsCameraApi also holds mInterfaceMutex, we can't call it in the
3707 // HIDL onStatusChanged wrapper call (we'll hold mStatusListenerLock and
3708 // mInterfaceMutex together, which can lead to deadlocks)
3709 binder::Status sRet =
3710 supportsCameraApi(String16(cameraId), hardware::ICameraService::API_VERSION_2,
3711 &supportsHAL3);
3712 if (!sRet.isOk()) {
3713 ALOGW("%s: Failed to determine if device supports HAL3 %s, supportsCameraApi call failed",
3714 __FUNCTION__, cameraId.string());
3715 return;
3716 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003717 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08003718 // of the listeners with both the mStatusLock and mStatusListenerLock held
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003719 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind, &supportsHAL3]
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003720 (const String8& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003721
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003722 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003723 // Update torch status if it has a flash unit.
3724 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003725 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003726 if (getTorchStatusLocked(cameraId, &torchStatus) !=
3727 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003728 TorchModeStatus newTorchStatus =
3729 status == StatusInternal::PRESENT ?
3730 TorchModeStatus::AVAILABLE_OFF :
3731 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003732 if (torchStatus != newTorchStatus) {
3733 onTorchStatusChangedLocked(cameraId, newTorchStatus);
3734 }
3735 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003736 }
3737
3738 Mutex::Autolock lock(mStatusListenerLock);
3739
Shuzhen Wang43858162020-01-10 13:42:15 -08003740 notifyPhysicalCameraStatusLocked(mapToInterface(status), cameraId);
3741
Ruben Brunkcc776712015-02-17 20:18:47 -08003742 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003743 bool isVendorListener = listener->isVendorListener();
3744 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
3745 listener->getListenerPid(), listener->getListenerUid()) ||
3746 (isVendorListener && !supportsHAL3)) {
3747 ALOGV("Skipping discovery callback for system-only camera/HAL1 device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003748 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003749 continue;
3750 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003751 listener->getListener()->onStatusChanged(mapToInterface(status),
Emilian Peev53722fa2019-02-22 17:47:20 -08003752 String16(cameraId));
Ruben Brunkcc776712015-02-17 20:18:47 -08003753 }
3754 });
Igor Murashkincba2c162013-03-20 15:56:31 -07003755}
3756
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003757template<class Func>
3758void CameraService::CameraState::updateStatus(StatusInternal status,
3759 const String8& cameraId,
3760 std::initializer_list<StatusInternal> rejectSourceStates,
3761 Func onStatusUpdatedLocked) {
3762 Mutex::Autolock lock(mStatusLock);
3763 StatusInternal oldStatus = mStatus;
3764 mStatus = status;
3765
3766 if (oldStatus == status) {
3767 return;
3768 }
3769
3770 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
3771 cameraId.string(), oldStatus, status);
3772
3773 if (oldStatus == StatusInternal::NOT_PRESENT &&
3774 (status != StatusInternal::PRESENT &&
3775 status != StatusInternal::ENUMERATING)) {
3776
3777 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
3778 __FUNCTION__);
3779 mStatus = oldStatus;
3780 return;
3781 }
3782
3783 /**
3784 * Sometimes we want to conditionally do a transition.
3785 * For example if a client disconnects, we want to go to PRESENT
3786 * only if we weren't already in NOT_PRESENT or ENUMERATING.
3787 */
3788 for (auto& rejectStatus : rejectSourceStates) {
3789 if (oldStatus == rejectStatus) {
3790 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
3791 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
3792 mStatus = oldStatus;
3793 return;
3794 }
3795 }
3796
3797 onStatusUpdatedLocked(cameraId, status);
3798}
3799
Eino-Ville Talvalae8c96c72017-06-27 12:24:07 -07003800void CameraService::updateProxyDeviceState(int newState,
Emilian Peev573291c2018-02-10 02:10:56 +00003801 const String8& cameraId, int facing, const String16& clientName, int apiLevel) {
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07003802 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
3803 if (proxyBinder == nullptr) return;
3804 String16 id(cameraId);
Emilian Peev573291c2018-02-10 02:10:56 +00003805 proxyBinder->notifyCameraState(id, newState, facing, clientName, apiLevel);
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07003806}
3807
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003808status_t CameraService::getTorchStatusLocked(
3809 const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003810 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003811 if (!status) {
3812 return BAD_VALUE;
3813 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003814 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3815 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003816 // invalid camera ID or the camera doesn't have a flash unit
3817 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003818 }
3819
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003820 *status = mTorchStatusMap.valueAt(index);
3821 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003822}
3823
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003824status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003825 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003826 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3827 if (index == NAME_NOT_FOUND) {
3828 return BAD_VALUE;
3829 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003830 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003831
3832 return OK;
3833}
3834
Shuzhen Wang43858162020-01-10 13:42:15 -08003835void CameraService::notifyPhysicalCameraStatusLocked(int32_t status, const String8& cameraId) {
3836 Mutex::Autolock lock(mCameraStatesLock);
3837 for (const auto& state : mCameraStates) {
3838 std::vector<std::string> physicalCameraIds;
3839 if (!mCameraProviderManager->isLogicalCamera(state.first.c_str(), &physicalCameraIds)) {
3840 // This is not a logical multi-camera.
3841 continue;
3842 }
3843 if (std::find(physicalCameraIds.begin(), physicalCameraIds.end(), cameraId.c_str())
3844 == physicalCameraIds.end()) {
3845 // cameraId is not a physical camera of this logical multi-camera.
3846 continue;
3847 }
3848
3849 String16 id16(state.first), physicalId16(cameraId);
3850 for (auto& listener : mListenerList) {
3851 listener->getListener()->onPhysicalCameraStatusChanged(status,
3852 id16, physicalId16);
3853 }
3854 }
3855}
3856
Svet Ganova453d0d2018-01-11 15:37:58 -08003857void CameraService::blockClientsForUid(uid_t uid) {
3858 const auto clients = mActiveClientManager.getAll();
3859 for (auto& current : clients) {
3860 if (current != nullptr) {
3861 const auto basicClient = current->getValue();
3862 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
3863 basicClient->block();
3864 }
3865 }
3866 }
3867}
3868
Michael Grooverd1d435a2018-12-18 17:39:42 -08003869void CameraService::blockAllClients() {
3870 const auto clients = mActiveClientManager.getAll();
3871 for (auto& current : clients) {
3872 if (current != nullptr) {
3873 const auto basicClient = current->getValue();
3874 if (basicClient.get() != nullptr) {
3875 basicClient->block();
3876 }
3877 }
3878 }
3879}
3880
Svet Ganova453d0d2018-01-11 15:37:58 -08003881// NOTE: This is a remote API - make sure all args are validated
3882status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
3883 if (!checkCallingPermission(sManageCameraPermission, nullptr, nullptr)) {
3884 return PERMISSION_DENIED;
3885 }
3886 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
3887 return BAD_VALUE;
3888 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003889 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003890 return handleSetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07003891 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003892 return handleResetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07003893 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003894 return handleGetUidState(args, out, err);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003895 } else if (args.size() >= 2 && args[0] == String16("set-rotate-and-crop")) {
3896 return handleSetRotateAndCrop(args);
3897 } else if (args.size() >= 1 && args[0] == String16("get-rotate-and-crop")) {
3898 return handleGetRotateAndCrop(out);
Svet Ganova453d0d2018-01-11 15:37:58 -08003899 } else if (args.size() == 1 && args[0] == String16("help")) {
3900 printHelp(out);
3901 return NO_ERROR;
3902 }
3903 printHelp(err);
3904 return BAD_VALUE;
3905}
3906
3907status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07003908 String16 packageName = args[1];
3909
Svet Ganova453d0d2018-01-11 15:37:58 -08003910 bool active = false;
3911 if (args[2] == String16("active")) {
3912 active = true;
3913 } else if ((args[2] != String16("idle"))) {
3914 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
3915 return BAD_VALUE;
3916 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003917
3918 int userId = 0;
3919 if (args.size() >= 5 && args[3] == String16("--user")) {
3920 userId = atoi(String8(args[4]));
3921 }
3922
3923 uid_t uid;
3924 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
3925 return BAD_VALUE;
3926 }
3927
3928 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08003929 return NO_ERROR;
3930}
3931
3932status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07003933 String16 packageName = args[1];
3934
3935 int userId = 0;
3936 if (args.size() >= 4 && args[2] == String16("--user")) {
3937 userId = atoi(String8(args[3]));
3938 }
3939
3940 uid_t uid;
3941 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003942 return BAD_VALUE;
3943 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003944
3945 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08003946 return NO_ERROR;
3947}
3948
3949status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07003950 String16 packageName = args[1];
3951
3952 int userId = 0;
3953 if (args.size() >= 4 && args[2] == String16("--user")) {
3954 userId = atoi(String8(args[3]));
3955 }
3956
3957 uid_t uid;
3958 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003959 return BAD_VALUE;
3960 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003961
3962 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003963 return dprintf(out, "active\n");
3964 } else {
3965 return dprintf(out, "idle\n");
3966 }
3967}
3968
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003969status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
3970 int rotateValue = atoi(String8(args[1]));
3971 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
3972 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
3973 Mutex::Autolock lock(mServiceLock);
3974
3975 mOverrideRotateAndCropMode = rotateValue;
3976
3977 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
3978
3979 const auto clients = mActiveClientManager.getAll();
3980 for (auto& current : clients) {
3981 if (current != nullptr) {
3982 const auto basicClient = current->getValue();
3983 if (basicClient.get() != nullptr) {
3984 basicClient->setRotateAndCropOverride(rotateValue);
3985 }
3986 }
3987 }
3988
3989 return OK;
3990}
3991
3992status_t CameraService::handleGetRotateAndCrop(int out) {
3993 Mutex::Autolock lock(mServiceLock);
3994
3995 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
3996}
3997
Svet Ganova453d0d2018-01-11 15:37:58 -08003998status_t CameraService::printHelp(int out) {
3999 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07004000 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
4001 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
4002 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004003 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
4004 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
4005 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08004006 " help print this message\n");
4007}
4008
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004009int32_t CameraService::updateAudioRestriction() {
4010 Mutex::Autolock lock(mServiceLock);
4011 return updateAudioRestrictionLocked();
4012}
4013
4014int32_t CameraService::updateAudioRestrictionLocked() {
4015 int32_t mode = 0;
4016 // iterate through all active client
4017 for (const auto& i : mActiveClientManager.getAll()) {
4018 const auto clientSp = i->getValue();
4019 mode |= clientSp->getAudioRestriction();
4020 }
4021
4022 bool modeChanged = (mAudioRestriction != mode);
4023 mAudioRestriction = mode;
4024 if (modeChanged) {
4025 mAppOps.setCameraAudioRestriction(mode);
4026 }
4027 return mode;
4028}
4029
Mathias Agopian65ab4712010-07-14 17:59:35 -07004030}; // namespace android