blob: 138e429e23ed45d3c6472f42692f49d8b987b416 [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>
Steven Moreland89a2c5c2020-01-31 15:02:25 -080046#include <binderthreadstate/CallerUtils.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070047#include <cutils/atomic.h>
Nipun Kwatrab5ca4612010-09-11 19:31:10 -070048#include <cutils/properties.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080049#include <cutils/misc.h>
Mathias Agopiandf712ea2012-02-25 18:48:35 -080050#include <gui/Surface.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070051#include <hardware/hardware.h>
Jayant Chowdharybe543d42018-08-15 13:16:14 -070052#include "hidl/HidlCameraService.h"
53#include <hidl/HidlTransportSupport.h>
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -080054#include <hwbinder/IPCThreadState.h>
Eino-Ville Talvalad89821e2016-04-20 11:23:50 -070055#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070056#include <media/AudioSystem.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080057#include <media/IMediaHTTPService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070058#include <media/mediaplayer.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070059#include <mediautils/BatteryNotifier.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070060#include <utils/Errors.h>
61#include <utils/Log.h>
62#include <utils/String16.h>
Svet Ganov94ec46f2018-06-08 15:03:46 -070063#include <utils/SystemClock.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080064#include <utils/Trace.h>
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080065#include <utils/CallStack.h>
Chien-Yu Chen98a668f2015-12-18 14:10:33 -080066#include <private/android_filesystem_config.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080067#include <system/camera_vendor_tags.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070068#include <system/camera_metadata.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080069
Ruben Brunkb2119af2014-05-09 19:57:56 -070070#include <system/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070071
72#include "CameraService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070073#include "api1/Camera2Client.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070074#include "api2/CameraDeviceClient.h"
Igor Murashkinff3e31d2013-10-23 16:40:06 -070075#include "utils/CameraTraces.h"
Emilian Peevbd8c5032018-02-14 23:05:40 +000076#include "utils/TagMonitor.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070077#include "utils/CameraThreadState.h"
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");
Shuzhen Wang695044d2020-03-06 09:02:23 -0800128static const String16 sCameraOpenCloseListenerPermission(
129 "android.permission.CAMERA_OPEN_CLOSE_LISTENER");
Svet Ganova453d0d2018-01-11 15:37:58 -0800130
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700131// Matches with PERCEPTIBLE_APP_ADJ in ProcessList.java
132static constexpr int32_t kVendorClientScore = 200;
133// Matches with PROCESS_STATE_PERSISTENT_UI in ActivityManager.java
134static constexpr int32_t kVendorClientState = 1;
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800135const String8 CameraService::kOfflineDevice("offline-");
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700136
Eino-Ville Talvala7d5569f2019-04-08 13:57:54 -0700137Mutex CameraService::sProxyMutex;
138sp<hardware::ICameraServiceProxy> CameraService::sCameraServiceProxy;
139
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800140CameraService::CameraService() :
141 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800142 mNumberOfCameras(0),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700143 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700144 mSoundRef(0), mInitialized(false),
145 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000146 ALOGI("CameraService started (pid=%d)", getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800147 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700148}
149
Iliyan Malchev8951a972011-04-14 16:55:59 -0700150void CameraService::onFirstRef()
151{
Ruben Brunkcc776712015-02-17 20:18:47 -0800152 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800153
Iliyan Malchev8951a972011-04-14 16:55:59 -0700154 BnCameraService::onFirstRef();
155
Ruben Brunk99e69712015-05-26 17:25:07 -0700156 // Update battery life tracking if service is restarting
157 BatteryNotifier& notifier(BatteryNotifier::getInstance());
158 notifier.noteResetCamera();
159 notifier.noteResetFlashlight();
160
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800161 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800162
Emilian Peevf53f66e2017-04-11 14:29:43 +0100163 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800164 if (res == OK) {
165 mInitialized = true;
166 }
167
Svet Ganova453d0d2018-01-11 15:37:58 -0800168 mUidPolicy = new UidPolicy(this);
169 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800170 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
171 mSensorPrivacyPolicy->registerSelf();
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700172 mAppOps.setCameraAudioRestriction(mAudioRestriction);
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700173 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
174 if (hcs->registerAsService() != android::OK) {
175 ALOGE("%s: Failed to register default android.frameworks.cameraservice.service@1.0",
176 __FUNCTION__);
177 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700178
179 // This needs to be last call in this function, so that it's as close to
180 // ServiceManager::addService() as possible.
181 CameraService::pingCameraServiceProxy();
182 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800183}
184
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800185status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800186 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100187
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800188 std::vector<std::string> deviceIds;
189 {
190 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800191
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800192 if (nullptr == mCameraProviderManager.get()) {
193 mCameraProviderManager = new CameraProviderManager();
194 res = mCameraProviderManager->initialize(this);
195 if (res != OK) {
196 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
197 __FUNCTION__, strerror(-res), res);
198 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100199 }
200 }
201
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800202
203 // Setup vendor tags before we call get_camera_info the first time
204 // because HAL might need to setup static vendor keys in get_camera_info
205 // TODO: maybe put this into CameraProviderManager::initialize()?
206 mCameraProviderManager->setUpVendorTags();
207
208 if (nullptr == mFlashlight.get()) {
209 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700210 }
211
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800212 res = mFlashlight->findFlashUnits();
213 if (res != OK) {
214 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
215 }
216
217 deviceIds = mCameraProviderManager->getCameraDeviceIds();
218 }
219
220
221 for (auto& cameraId : deviceIds) {
222 String8 id8 = String8(cameraId.c_str());
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800223 if (getCameraState(id8) == nullptr) {
224 onDeviceStatusChanged(id8, CameraDeviceStatus::PRESENT);
225 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800226 }
227
228 return OK;
229}
230
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700231sp<ICameraServiceProxy> CameraService::getCameraServiceProxy() {
Christopher Wiley92c06fc2016-02-11 15:40:05 -0800232#ifndef __BRILLO__
Eino-Ville Talvala7d5569f2019-04-08 13:57:54 -0700233 Mutex::Autolock al(sProxyMutex);
234 if (sCameraServiceProxy == nullptr) {
235 sp<IServiceManager> sm = defaultServiceManager();
236 // Use checkService because cameraserver normally starts before the
237 // system server and the proxy service. So the long timeout that getService
238 // has before giving up is inappropriate.
239 sp<IBinder> binder = sm->checkService(String16("media.camera.proxy"));
240 if (binder != nullptr) {
241 sCameraServiceProxy = interface_cast<ICameraServiceProxy>(binder);
242 }
Ruben Brunk2823ce02015-05-19 17:25:13 -0700243 }
Christopher Wiley92c06fc2016-02-11 15:40:05 -0800244#endif
Eino-Ville Talvala7d5569f2019-04-08 13:57:54 -0700245 return sCameraServiceProxy;
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700246}
247
248void CameraService::pingCameraServiceProxy() {
249 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
250 if (proxyBinder == nullptr) return;
Ruben Brunk2823ce02015-05-19 17:25:13 -0700251 proxyBinder->pingForUserUpdate();
Iliyan Malchev8951a972011-04-14 16:55:59 -0700252}
253
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800254void CameraService::broadcastTorchModeStatus(const String8& cameraId, TorchModeStatus status) {
255 Mutex::Autolock lock(mStatusListenerLock);
256
257 for (auto& i : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700258 i->getListener()->onTorchStatusChanged(mapToInterface(status), String16{cameraId});
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800259 }
260}
261
Mathias Agopian65ab4712010-07-14 17:59:35 -0700262CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800263 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800264 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800265 mSensorPrivacyPolicy->unregisterSelf();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700266}
267
Emilian Peevaee727d2017-05-04 16:35:48 +0100268void CameraService::onNewProviderRegistered() {
269 enumerateProviders();
270}
271
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700272void CameraService::filterAPI1SystemCameraLocked(
273 const std::vector<std::string> &normalDeviceIds) {
274 mNormalDeviceIdsWithoutSystemCamera.clear();
275 for (auto &deviceId : normalDeviceIds) {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700276 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
277 if (getSystemCameraKind(String8(deviceId.c_str()), &deviceKind) != OK) {
278 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, deviceId.c_str());
279 continue;
280 }
281 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700282 // All system camera ids will necessarily come after public camera
283 // device ids as per the HAL interface contract.
284 break;
285 }
286 mNormalDeviceIdsWithoutSystemCamera.push_back(deviceId);
287 }
288 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
289 mNormalDeviceIdsWithoutSystemCamera.size());
290}
291
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700292status_t CameraService::getSystemCameraKind(const String8& cameraId, SystemCameraKind *kind) const {
293 auto state = getCameraState(cameraId);
294 if (state != nullptr) {
295 *kind = state->getSystemCameraKind();
296 return OK;
297 }
298 // Hidden physical camera ids won't have CameraState
299 return mCameraProviderManager->getSystemCameraKind(cameraId.c_str(), kind);
300}
301
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800302void CameraService::updateCameraNumAndIds() {
303 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700304 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
305 // Excludes hidden secure cameras
306 mNumberOfCameras =
307 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
308 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800309 mNormalDeviceIds =
310 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700311 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800312}
313
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100314void CameraService::addStates(const String8 id) {
315 std::string cameraId(id.c_str());
316 hardware::camera::common::V1_0::CameraResourceCost cost;
317 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700318 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100319 if (res != OK) {
320 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
321 return;
322 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700323 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
324 if (res != OK) {
325 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
326 return;
327 }
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100328 std::set<String8> conflicting;
329 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
330 conflicting.emplace(String8(cost.conflictingDevices[i].c_str()));
331 }
332
333 {
334 Mutex::Autolock lock(mCameraStatesLock);
335 mCameraStates.emplace(id, std::make_shared<CameraState>(id, cost.resourceCost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700336 conflicting, deviceKind));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100337 }
338
339 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100340 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100341 mTorchStatusMap.add(id, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800342
343 broadcastTorchModeStatus(id, TorchModeStatus::AVAILABLE_OFF);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100344 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800345
346 updateCameraNumAndIds();
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100347 logDeviceAdded(id, "Device added");
348}
349
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100350void CameraService::removeStates(const String8 id) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800351 updateCameraNumAndIds();
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100352 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100353 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100354 mTorchStatusMap.removeItem(id);
355 }
356
357 {
358 Mutex::Autolock lock(mCameraStatesLock);
359 mCameraStates.erase(id);
360 }
361}
362
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800363void CameraService::onDeviceStatusChanged(const String8& id,
364 CameraDeviceStatus newHalStatus) {
365 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
366 id.string(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700367
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800368 StatusInternal newStatus = mapToInternal(newHalStatus);
369
Ruben Brunkcc776712015-02-17 20:18:47 -0800370 std::shared_ptr<CameraState> state = getCameraState(id);
371
372 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700373 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100374 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700375 __FUNCTION__, id.string());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100376
377 // First add as absent to make sure clients are notified below
378 addStates(id);
379
380 updateStatus(newStatus, id);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700381 } else {
382 ALOGE("%s: Bad camera ID %s", __FUNCTION__, id.string());
383 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700384 return;
385 }
386
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800387 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800388
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800389 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800390 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700391 return;
392 }
393
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800394 if (newStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700395 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
396 newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800397
398 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
399 // to this device until the status changes
400 updateStatus(StatusInternal::NOT_PRESENT, id);
401
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800402 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700403 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800404 // Don't do this in updateStatus to avoid deadlock over mServiceLock
405 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700406
Ruben Brunkcc776712015-02-17 20:18:47 -0800407 // Remove cached shim parameters
408 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700409
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800410 // Remove online as well as offline client from the list of active clients,
411 // if they are present
412 clientToDisconnectOnline = removeClientLocked(id);
413 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + id);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700414 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800415
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800416 disconnectClient(id, clientToDisconnectOnline);
417 disconnectClient(kOfflineDevice + id, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700418
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100419 removeStates(id);
Ruben Brunkcc776712015-02-17 20:18:47 -0800420 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800421 if (oldStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700422 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
423 newStatus));
424 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800425 updateStatus(newStatus, id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700426 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800427}
Igor Murashkincba2c162013-03-20 15:56:31 -0700428
Shuzhen Wang43858162020-01-10 13:42:15 -0800429void CameraService::onDeviceStatusChanged(const String8& id,
430 const String8& physicalId,
431 CameraDeviceStatus newHalStatus) {
432 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
433 __FUNCTION__, id.string(), physicalId.string(), newHalStatus);
434
435 StatusInternal newStatus = mapToInternal(newHalStatus);
436
437 std::shared_ptr<CameraState> state = getCameraState(id);
438
439 if (state == nullptr) {
440 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
441 __FUNCTION__, id.string(), physicalId.string());
442 return;
443 }
444
445 StatusInternal logicalCameraStatus = state->getStatus();
446 if (logicalCameraStatus != StatusInternal::PRESENT &&
447 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
448 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
449 __FUNCTION__, physicalId.string(), newHalStatus, logicalCameraStatus);
450 return;
451 }
452
453 bool updated = false;
454 if (newStatus == StatusInternal::PRESENT) {
455 updated = state->removeUnavailablePhysicalId(physicalId);
456 } else {
457 updated = state->addUnavailablePhysicalId(physicalId);
458 }
459
460 if (updated) {
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800461 String8 idCombo = id + " : " + physicalId;
462 if (newStatus == StatusInternal::PRESENT) {
463 logDeviceAdded(idCombo,
464 String8::format("Device status changed to %d", newStatus));
465 } else {
466 logDeviceRemoved(idCombo,
467 String8::format("Device status changed to %d", newStatus));
468 }
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700469 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
470 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
471 if (getSystemCameraKind(id, &deviceKind) != OK) {
472 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.string());
473 return;
474 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800475 String16 id16(id), physicalId16(physicalId);
476 Mutex::Autolock lock(mStatusListenerLock);
477 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700478 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
479 listener->getListenerPid(), listener->getListenerUid())) {
480 ALOGV("Skipping discovery callback for system-only camera device %s",
481 id.c_str());
482 continue;
483 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800484 listener->getListener()->onPhysicalCameraStatusChanged(mapToInterface(newStatus),
485 id16, physicalId16);
486 }
487 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700488}
489
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800490void CameraService::disconnectClient(const String8& id, sp<BasicClient> clientToDisconnect) {
491 if (clientToDisconnect.get() != nullptr) {
492 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
493 __FUNCTION__, id.string());
494 // Notify the client of disconnection
495 clientToDisconnect->notifyError(
496 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
497 CaptureResultExtras{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800498 clientToDisconnect->disconnect();
499 }
500}
501
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800502void CameraService::onTorchStatusChanged(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800503 TorchModeStatus newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800504 Mutex::Autolock al(mTorchStatusMutex);
505 onTorchStatusChangedLocked(cameraId, newStatus);
506}
507
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800508void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800509 TorchModeStatus newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800510 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
511 __FUNCTION__, cameraId.string(), newStatus);
512
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800513 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800514 status_t res = getTorchStatusLocked(cameraId, &status);
515 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700516 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
517 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800518 return;
519 }
520 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800521 return;
522 }
523
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800524 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800525 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800526 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
527 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800528 return;
529 }
530
Ruben Brunkcc776712015-02-17 20:18:47 -0800531 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700532 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700533 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700534 auto iter = mTorchUidMap.find(cameraId);
535 if (iter != mTorchUidMap.end()) {
536 int oldUid = iter->second.second;
537 int newUid = iter->second.first;
538 BatteryNotifier& notifier(BatteryNotifier::getInstance());
539 if (oldUid != newUid) {
540 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800541 if (status == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700542 notifier.noteFlashlightOff(cameraId, oldUid);
543 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800544 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700545 notifier.noteFlashlightOn(cameraId, newUid);
546 }
547 iter->second.second = newUid;
548 } else {
549 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800550 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700551 notifier.noteFlashlightOn(cameraId, oldUid);
552 } else {
553 notifier.noteFlashlightOff(cameraId, oldUid);
554 }
555 }
556 }
557 }
558
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800559 broadcastTorchModeStatus(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800560}
561
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700562static bool hasPermissionsForSystemCamera(int callingPid, int callingUid) {
563 return checkPermission(sSystemCameraPermission, callingPid, callingUid) &&
564 checkPermission(sCameraPermission, callingPid, callingUid);
565}
566
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800567Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700568 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100569 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700570 bool hasSystemCameraPermissions =
571 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
572 CameraThreadState::getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700573 switch (type) {
574 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700575 if (hasSystemCameraPermissions) {
576 *numCameras = static_cast<int>(mNormalDeviceIds.size());
577 } else {
578 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
579 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800580 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700581 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700582 if (hasSystemCameraPermissions) {
583 *numCameras = mNumberOfCameras;
584 } else {
585 *numCameras = mNumberOfCamerasWithoutSystemCamera;
586 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800587 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700588 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800589 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700590 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800591 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
592 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700593 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800594 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700595}
596
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800597Status CameraService::getCameraInfo(int cameraId,
598 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700599 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100600 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700601 std::string cameraIdStr = cameraIdIntToStrLocked(cameraId);
602 if (shouldRejectSystemCameraConnection(String8(cameraIdStr.c_str()))) {
603 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
604 "characteristics for system only device %s: ", cameraIdStr.c_str());
605 }
Emilian Peevaee727d2017-05-04 16:35:48 +0100606
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800607 if (!mInitialized) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800608 return STATUS_ERROR(ERROR_DISCONNECTED,
609 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -0700610 }
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700611 bool hasSystemCameraPermissions =
612 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
613 CameraThreadState::getCallingUid());
614 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
615 if (hasSystemCameraPermissions) {
616 cameraIdBound = mNumberOfCameras;
617 }
618 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800619 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
620 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700621 }
622
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800623 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800624 status_t err = mCameraProviderManager->getCameraInfo(
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700625 cameraIdStr.c_str(), cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100626 if (err != OK) {
627 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
628 "Error retrieving camera info from device %d: %s (%d)", cameraId,
629 strerror(-err), err);
Ruben Brunkcc776712015-02-17 20:18:47 -0800630 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100631
Ruben Brunkcc776712015-02-17 20:18:47 -0800632 return ret;
633}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700634
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800635std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700636 const std::vector<std::string> *deviceIds = &mNormalDeviceIdsWithoutSystemCamera;
637 auto callingPid = CameraThreadState::getCallingPid();
638 auto callingUid = CameraThreadState::getCallingUid();
639 if (checkPermission(sSystemCameraPermission, callingPid, callingUid) ||
640 getpid() == callingPid) {
641 deviceIds = &mNormalDeviceIds;
642 }
643 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(deviceIds->size())) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800644 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700645 __FUNCTION__, cameraIdInt, deviceIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800646 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800647 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800648
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700649 return (*deviceIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800650}
651
652String8 CameraService::cameraIdIntToStr(int cameraIdInt) {
653 Mutex::Autolock lock(mServiceLock);
654 return String8(cameraIdIntToStrLocked(cameraIdInt).c_str());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800655}
656
657Status CameraService::getCameraCharacteristics(const String16& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800658 CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700659 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700660 if (!cameraInfo) {
661 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800662 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -0700663 }
664
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800665 if (!mInitialized) {
666 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800667 return STATUS_ERROR(ERROR_DISCONNECTED,
668 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -0700669 }
670
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700671 if (shouldRejectSystemCameraConnection(String8(cameraId))) {
672 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
673 "characteristics for system only device %s: ", String8(cameraId).string());
674 }
675
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800676 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800677
Emilian Peevf53f66e2017-04-11 14:29:43 +0100678 status_t res = mCameraProviderManager->getCameraCharacteristics(
679 String8(cameraId).string(), cameraInfo);
680 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700681 if (res == NAME_NOT_FOUND) {
682 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
683 "characteristics for unknown device %s: %s (%d)", String8(cameraId).string(),
684 strerror(-res), res);
685 } else {
686 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
687 "characteristics for device %s: %s (%d)", String8(cameraId).string(),
688 strerror(-res), res);
689 }
Ruben Brunkb2119af2014-05-09 19:57:56 -0700690 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700691 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
692 if (getSystemCameraKind(String8(cameraId), &deviceKind) != OK) {
693 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, String8(cameraId).string());
694 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera kind "
695 "for device %s", String8(cameraId).string());
696 }
Jayant Chowdhary12361932018-08-27 14:46:13 -0700697 int callingPid = CameraThreadState::getCallingPid();
698 int callingUid = CameraThreadState::getCallingUid();
Emilian Peeve20c6372018-08-14 18:45:53 +0100699 std::vector<int32_t> tagsRemoved;
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700700 // If it's not calling from cameraserver, check the permission only if
701 // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
702 // it would've already been checked in shouldRejectSystemCameraConnection.
Emilian Peeve20c6372018-08-14 18:45:53 +0100703 if ((callingPid != getpid()) &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700704 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700705 !checkPermission(sCameraPermission, callingPid, callingUid)) {
Emilian Peeve20c6372018-08-14 18:45:53 +0100706 res = cameraInfo->removePermissionEntries(
707 mCameraProviderManager->getProviderTagIdLocked(String8(cameraId).string()),
708 &tagsRemoved);
709 if (res != OK) {
710 cameraInfo->clear();
711 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
712 " characteristics needing camera permission for device %s: %s (%d)",
713 String8(cameraId).string(), strerror(-res), res);
714 }
715 }
716
717 if (!tagsRemoved.empty()) {
718 res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
719 tagsRemoved.data(), tagsRemoved.size());
720 if (res != OK) {
721 cameraInfo->clear();
722 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
723 "keys needing permission for device %s: %s (%d)", String8(cameraId).string(),
724 strerror(-res), res);
725 }
726 }
727
Zhijun He2b59be82013-09-25 10:14:30 -0700728 return ret;
729}
730
Ruben Brunkcc776712015-02-17 20:18:47 -0800731String8 CameraService::getFormattedCurrentTime() {
732 time_t now = time(nullptr);
733 char formattedTime[64];
734 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
735 return String8(formattedTime);
736}
737
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800738Status CameraService::getCameraVendorTagDescriptor(
739 /*out*/
740 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700741 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800742 if (!mInitialized) {
743 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800744 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800745 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -0800746 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
747 if (globalDescriptor != nullptr) {
748 *desc = *(globalDescriptor.get());
749 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800750 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800751}
752
Emilian Peev71c73a22017-03-21 16:35:51 +0000753Status CameraService::getCameraVendorTagCache(
754 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
755 ATRACE_CALL();
756 if (!mInitialized) {
757 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
758 return STATUS_ERROR(ERROR_DISCONNECTED,
759 "Camera subsystem not available");
760 }
761 sp<VendorTagDescriptorCache> globalCache =
762 VendorTagDescriptorCache::getGlobalVendorTagCache();
763 if (globalCache != nullptr) {
764 *cache = *(globalCache.get());
765 }
766 return Status::ok();
767}
768
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800769int CameraService::getDeviceVersion(const String8& cameraId, int* facing) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700770 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800771
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800772 int deviceVersion = 0;
773
Emilian Peevf53f66e2017-04-11 14:29:43 +0100774 status_t res;
775 hardware::hidl_version maxVersion{0,0};
776 res = mCameraProviderManager->getHighestSupportedVersion(cameraId.string(),
777 &maxVersion);
778 if (res != OK) return -1;
779 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800780
Emilian Peevf53f66e2017-04-11 14:29:43 +0100781 hardware::CameraInfo info;
782 if (facing) {
783 res = mCameraProviderManager->getCameraInfo(cameraId.string(), &info);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -0800784 if (res != OK) return -1;
Emilian Peevf53f66e2017-04-11 14:29:43 +0100785 *facing = info.facing;
Igor Murashkin634a5152013-02-20 17:15:11 -0800786 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100787
Igor Murashkin634a5152013-02-20 17:15:11 -0800788 return deviceVersion;
789}
790
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800791Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700792 switch(err) {
793 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800794 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800795 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800796 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
797 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800798 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800799 return STATUS_ERROR(ERROR_DISCONNECTED,
800 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700801 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800802 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
803 "Camera HAL encountered error %d: %s",
804 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700805 }
Igor Murashkinbfc99152013-02-27 12:55:20 -0800806}
807
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800808Status CameraService::makeClient(const sp<CameraService>& cameraService,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800809 const sp<IInterface>& cameraCb, const String16& packageName,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700810 const std::optional<String16>& featureId, const String8& cameraId,
811 int api1CameraId, int facing, int clientPid, uid_t clientUid, int servicePid,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800812 int deviceVersion, apiLevel effectiveApiLevel,
Ruben Brunkcc776712015-02-17 20:18:47 -0800813 /*out*/sp<BasicClient>* client) {
814
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700815 // Create CameraClient based on device version reported by the HAL.
816 switch(deviceVersion) {
817 case CAMERA_DEVICE_API_VERSION_1_0:
818 ALOGE("Camera using old HAL version: %d", deviceVersion);
819 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
820 "Camera device \"%s\" HAL version %d no longer supported",
821 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800822 break;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700823 case CAMERA_DEVICE_API_VERSION_3_0:
824 case CAMERA_DEVICE_API_VERSION_3_1:
825 case CAMERA_DEVICE_API_VERSION_3_2:
826 case CAMERA_DEVICE_API_VERSION_3_3:
827 case CAMERA_DEVICE_API_VERSION_3_4:
828 case CAMERA_DEVICE_API_VERSION_3_5:
829 case CAMERA_DEVICE_API_VERSION_3_6:
Ruben Brunkcc776712015-02-17 20:18:47 -0800830 if (effectiveApiLevel == API_1) { // Camera1 API route
831 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800832 *client = new Camera2Client(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800833 cameraId, api1CameraId,
834 facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700835 servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800836 } else { // Camera2 API route
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800837 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
838 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800839 *client = new CameraDeviceClient(cameraService, tmp, packageName, featureId,
840 cameraId, facing, clientPid, clientUid, servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800841 }
842 break;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700843 default:
Ruben Brunkcc776712015-02-17 20:18:47 -0800844 // Should not be reachable
845 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800846 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800847 "Camera device \"%s\" has unknown HAL version %d",
848 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800849 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800850 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800851}
852
Ruben Brunk6267b532015-04-30 17:44:07 -0700853String8 CameraService::toString(std::set<userid_t> intSet) {
854 String8 s("");
855 bool first = true;
856 for (userid_t i : intSet) {
857 if (first) {
858 s.appendFormat("%d", i);
859 first = false;
860 } else {
861 s.appendFormat(", %d", i);
862 }
863 }
864 return s;
865}
866
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800867int32_t CameraService::mapToInterface(TorchModeStatus status) {
868 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
869 switch (status) {
870 case TorchModeStatus::NOT_AVAILABLE:
871 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
872 break;
873 case TorchModeStatus::AVAILABLE_OFF:
874 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
875 break;
876 case TorchModeStatus::AVAILABLE_ON:
877 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
878 break;
879 default:
880 ALOGW("Unknown new flash status: %d", status);
881 }
882 return serviceStatus;
883}
884
885CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
886 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
887 switch (status) {
888 case CameraDeviceStatus::NOT_PRESENT:
889 serviceStatus = StatusInternal::NOT_PRESENT;
890 break;
891 case CameraDeviceStatus::PRESENT:
892 serviceStatus = StatusInternal::PRESENT;
893 break;
894 case CameraDeviceStatus::ENUMERATING:
895 serviceStatus = StatusInternal::ENUMERATING;
896 break;
897 default:
898 ALOGW("Unknown new HAL device status: %d", status);
899 }
900 return serviceStatus;
901}
902
903int32_t CameraService::mapToInterface(StatusInternal status) {
904 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
905 switch (status) {
906 case StatusInternal::NOT_PRESENT:
907 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
908 break;
909 case StatusInternal::PRESENT:
910 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
911 break;
912 case StatusInternal::ENUMERATING:
913 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
914 break;
915 case StatusInternal::NOT_AVAILABLE:
916 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
917 break;
918 case StatusInternal::UNKNOWN:
919 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
920 break;
921 default:
922 ALOGW("Unknown new internal device status: %d", status);
923 }
924 return serviceStatus;
925}
926
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800927Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -0700928 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700929
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800930 String16 internalPackageName("cameraserver");
Ruben Brunkcc776712015-02-17 20:18:47 -0800931 String8 id = String8::format("%d", cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800932 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800933 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800934 if (!(ret = connectHelper<ICameraClient,Client>(
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800935 sp<ICameraClient>{nullptr}, id, cameraId,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +0900936 internalPackageName, {}, uid, USE_CALLING_PID,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700937 API_1, /*shimUpdateOnly*/ true, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800938 ).isOk()) {
939 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
Ruben Brunkb2119af2014-05-09 19:57:56 -0700940 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800941 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700942}
943
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800944Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -0700945 /*out*/
946 CameraParameters* parameters) {
947
948 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
949
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800950 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -0700951
952 if (parameters == NULL) {
953 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800954 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -0700955 }
956
Ruben Brunkcc776712015-02-17 20:18:47 -0800957 String8 id = String8::format("%d", cameraId);
958
959 // Check if we already have parameters
960 {
961 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -0700962 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -0800963 auto cameraState = getCameraState(id);
964 if (cameraState == nullptr) {
965 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800966 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
967 "Invalid camera ID: %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -0800968 }
969 CameraParameters p = cameraState->getShimParams();
970 if (!p.isEmpty()) {
971 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800972 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700973 }
974 }
975
Jayant Chowdhary12361932018-08-27 14:46:13 -0700976 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -0800977 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -0700978 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800979 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800980 // Error already logged by callee
981 return ret;
982 }
983
984 // Check for parameters again
985 {
986 // Scope for service lock
987 Mutex::Autolock lock(mServiceLock);
988 auto cameraState = getCameraState(id);
989 if (cameraState == nullptr) {
990 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800991 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
992 "Invalid camera ID: %s", id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -0700993 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800994 CameraParameters p = cameraState->getShimParams();
995 if (!p.isEmpty()) {
996 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800997 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700998 }
999 }
1000
Ruben Brunkcc776712015-02-17 20:18:47 -08001001 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1002 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001003 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001004}
1005
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001006// Can camera service trust the caller based on the calling UID?
1007static bool isTrustedCallingUid(uid_t uid) {
1008 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001009 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001010 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001011 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001012 return true;
1013 default:
1014 return false;
1015 }
1016}
1017
Nicholas Sauera3620332019-04-03 14:05:17 -07001018static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1019 PermissionController pc;
1020 uid = pc.getPackageUid(packageName, 0);
1021 if (uid <= 0) {
1022 ALOGE("Unknown package: '%s'", String8(packageName).string());
1023 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
1024 return BAD_VALUE;
1025 }
1026
1027 if (userId < 0) {
1028 ALOGE("Invalid user: %d", userId);
1029 dprintf(err, "Invalid user: %d\n", userId);
1030 return BAD_VALUE;
1031 }
1032
1033 uid = multiuser_get_uid(userId, uid);
1034 return NO_ERROR;
1035}
1036
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001037Status CameraService::validateConnectLocked(const String8& cameraId,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001038 const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
1039 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001040
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001041#ifdef __BRILLO__
1042 UNUSED(clientName8);
1043 UNUSED(clientUid);
1044 UNUSED(clientPid);
1045 UNUSED(originalClientPid);
1046#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001047 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1048 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001049 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001050 return allowed;
1051 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001052#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001053
Jayant Chowdhary12361932018-08-27 14:46:13 -07001054 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001055
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001056 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001057 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1058 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001059 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1060 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001061 }
1062
Ruben Brunkcc776712015-02-17 20:18:47 -08001063 if (getCameraState(cameraId) == nullptr) {
1064 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1065 cameraId.string());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001066 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1067 "No camera device with ID \"%s\" available", cameraId.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001068 }
1069
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001070 status_t err = checkIfDeviceIsUsable(cameraId);
1071 if (err != NO_ERROR) {
1072 switch(err) {
1073 case -ENODEV:
1074 case -EBUSY:
1075 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1076 "No camera device with ID \"%s\" currently available", cameraId.string());
1077 default:
1078 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1079 "Unknown error connecting to ID \"%s\"", cameraId.string());
1080 }
1081 }
1082 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001083}
1084
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001085Status CameraService::validateClientPermissionsLocked(const String8& cameraId,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001086 const String8& clientName8, int& clientUid, int& clientPid,
1087 /*out*/int& originalClientPid) const {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001088 int callingPid = CameraThreadState::getCallingPid();
1089 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001090
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001091 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001092 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001093 clientUid = callingUid;
1094 } else if (!isTrustedCallingUid(callingUid)) {
1095 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1096 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001097 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1098 "Untrusted caller (calling PID %d, UID %d) trying to "
1099 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1100 callingPid, callingUid, cameraId.string(),
1101 clientName8.string(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001102 }
1103
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001104 // Check if we can trust clientPid
1105 if (clientPid == USE_CALLING_PID) {
1106 clientPid = callingPid;
1107 } else if (!isTrustedCallingUid(callingUid)) {
1108 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1109 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001110 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1111 "Untrusted caller (calling PID %d, UID %d) trying to "
1112 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1113 callingPid, callingUid, cameraId.string(),
1114 clientName8.string(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001115 }
1116
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001117 if (shouldRejectSystemCameraConnection(cameraId)) {
1118 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1119 cameraId.c_str());
1120 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
1121 "available", cameraId.string());
1122 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001123 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1124 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1125 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
1126 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
1127 "found while trying to query device kind", cameraId.string());
1128
1129 }
1130
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001131 // If it's not calling from cameraserver, check the permission if the
1132 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1133 // android.permission.SYSTEM_CAMERA for system only camera devices).
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001134 if (callingPid != getpid() &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001135 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001136 !checkPermission(sCameraPermission, clientPid, clientUid)) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001137 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001138 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1139 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
1140 clientName8.string(), clientUid, clientPid, cameraId.string());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001141 }
1142
Svet Ganova453d0d2018-01-11 15:37:58 -08001143 // Make sure the UID is in an active state to use the camera
Svet Ganov7b4ab782018-03-25 12:48:10 -07001144 if (!mUidPolicy->isUidActive(callingUid, String16(clientName8))) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001145 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001146 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1147 clientPid, clientUid);
1148 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001149 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1150 "calling UID %d proc state %" PRId32 ")",
1151 clientName8.string(), clientUid, clientPid, cameraId.string(),
1152 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001153 }
1154
Michael Grooverd1d435a2018-12-18 17:39:42 -08001155 // If sensor privacy is enabled then prevent access to the camera
1156 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1157 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1158 return STATUS_ERROR_FMT(ERROR_DISABLED,
1159 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
1160 "is enabled", clientName8.string(), clientUid, clientPid, cameraId.string());
1161 }
1162
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001163 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1164 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001165 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001166 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001167
Ruben Brunk6267b532015-04-30 17:44:07 -07001168 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001169
Ruben Brunka8ca9152015-04-07 14:23:40 -07001170 // Only allow clients who are being used by the current foreground device user, unless calling
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001171 // from our own process OR the caller is using the cameraserver's HIDL interface.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001172 if (getCurrentServingCall() != BinderCallType::HWBINDER && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001173 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001174 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1175 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
1176 toString(mAllowedUsers).string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001177 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1178 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
1179 clientUserId, cameraId.string());
Ruben Brunk36597b22015-03-20 22:15:57 -07001180 }
1181
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001182 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001183}
1184
1185status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
1186 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001187 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001188 if (cameraState == nullptr) {
1189 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1190 cameraId.string());
1191 return -ENODEV;
1192 }
1193
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001194 StatusInternal currentStatus = cameraState->getStatus();
1195 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001196 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
1197 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001198 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001199 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001200 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
1201 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001202 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001203 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001204
Ruben Brunkcc776712015-02-17 20:18:47 -08001205 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001206}
1207
Ruben Brunkcc776712015-02-17 20:18:47 -08001208void CameraService::finishConnectLocked(const sp<BasicClient>& client,
1209 const CameraService::DescriptorPtr& desc) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001210
Ruben Brunkcc776712015-02-17 20:18:47 -08001211 // Make a descriptor for the incoming client
1212 auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
1213 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1214
1215 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
1216 String8(client->getPackageName()));
1217
1218 if (evicted.size() > 0) {
1219 // This should never happen - clients should already have been removed in disconnect
1220 for (auto& i : evicted) {
1221 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
1222 __FUNCTION__, i->getKey().string());
1223 }
1224
1225 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1226 __FUNCTION__);
1227 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001228
1229 // And register a death notification for the client callback. Do
1230 // this last to avoid Binder policy where a nested Binder
1231 // transaction might be pre-empted to service the client death
1232 // notification if the client process dies before linkToDeath is
1233 // invoked.
1234 sp<IBinder> remoteCallback = client->getRemote();
1235 if (remoteCallback != nullptr) {
1236 remoteCallback->linkToDeath(this);
1237 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001238}
1239
1240status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
1241 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
1242 /*out*/
1243 sp<BasicClient>* client,
1244 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001245 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001246 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001247 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001248 DescriptorPtr clientDescriptor;
1249 {
1250 if (effectiveApiLevel == API_1) {
1251 // If we are using API1, any existing client for this camera ID with the same remote
1252 // should be returned rather than evicted to allow MediaRecorder to work properly.
1253
1254 auto current = mActiveClientManager.get(cameraId);
1255 if (current != nullptr) {
1256 auto clientSp = current->getValue();
1257 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001258 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
1259 ALOGW("CameraService connect called from same client, but with a different"
1260 " API level, evicting prior client...");
1261 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001262 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001263 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001264 *client = clientSp;
1265 return NO_ERROR;
1266 }
1267 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001268 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001269 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001270
Ruben Brunkcc776712015-02-17 20:18:47 -08001271 // Get current active client PIDs
1272 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1273 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001274
Emilian Peev8131a262017-02-01 12:33:43 +00001275 std::vector<int> priorityScores(ownerPids.size());
1276 std::vector<int> states(ownerPids.size());
Igor Murashkine6800ce2013-03-04 17:25:57 -08001277
Emilian Peev8131a262017-02-01 12:33:43 +00001278 // Get priority scores of all active PIDs
1279 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1280 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1281 /*out*/&priorityScores[0]);
1282 if (err != OK) {
1283 ALOGE("%s: Priority score query failed: %d",
1284 __FUNCTION__, err);
1285 return err;
1286 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001287
Ruben Brunkcc776712015-02-17 20:18:47 -08001288 // Update all active clients' priorities
Emilian Peev8131a262017-02-01 12:33:43 +00001289 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
Ruben Brunkcc776712015-02-17 20:18:47 -08001290 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
Emilian Peev8131a262017-02-01 12:33:43 +00001291 pidToPriorityMap.emplace(ownerPids[i],
Jayant Chowdharyc578a502019-05-08 10:57:54 -07001292 resource_policy::ClientPriority(priorityScores[i], states[i],
1293 /* isVendorClient won't get copied over*/ false));
Ruben Brunkcc776712015-02-17 20:18:47 -08001294 }
1295 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001296
Ruben Brunkcc776712015-02-17 20:18:47 -08001297 // Get state for the given cameraId
1298 auto state = getCameraState(cameraId);
1299 if (state == nullptr) {
1300 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1301 clientPid, cameraId.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001302 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001303 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001304 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001305
1306 // Make descriptor for incoming client
Shuzhen Wang2db86ff2018-04-25 01:11:17 +00001307 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001308 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1309 state->getConflicting(),
Emilian Peev8131a262017-02-01 12:33:43 +00001310 priorityScores[priorityScores.size() - 1],
1311 clientPid,
1312 states[states.size() - 1]);
Ruben Brunkcc776712015-02-17 20:18:47 -08001313
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001314 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1315
Ruben Brunkcc776712015-02-17 20:18:47 -08001316 // Find clients that would be evicted
1317 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1318
1319 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1320 // background, so we cannot do evictions
1321 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1322 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1323 " priority).", clientPid);
1324
1325 sp<BasicClient> clientSp = clientDescriptor->getValue();
1326 String8 curTime = getFormattedCurrentTime();
1327 auto incompatibleClients =
1328 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1329
1330 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Emilian Peev8131a262017-02-01 12:33:43 +00001331 "(PID %d, score %d state %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001332 cameraId.string(), packageName.string(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001333 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001334
1335 for (auto& i : incompatibleClients) {
1336 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001337 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
1338 i->getKey().string(),
1339 String8{i->getValue()->getPackageName()}.string(),
1340 i->getOwnerId(), i->getPriority().getScore(),
1341 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001342 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00001343 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(),
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001344 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001345 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001346 }
1347
1348 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001349 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001350 mEventLog.add(msg);
1351
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001352 auto current = mActiveClientManager.get(cameraId);
1353 if (current != nullptr) {
1354 return -EBUSY; // CAMERA_IN_USE
1355 } else {
1356 return -EUSERS; // MAX_CAMERAS_IN_USE
1357 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001358 }
1359
1360 for (auto& i : evicted) {
1361 sp<BasicClient> clientSp = i->getValue();
1362 if (clientSp.get() == nullptr) {
1363 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1364
1365 // TODO: Remove this
1366 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1367 __FUNCTION__);
1368 mActiveClientManager.remove(i);
1369 continue;
1370 }
1371
1372 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1373 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001374 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001375
Ruben Brunkcc776712015-02-17 20:18:47 -08001376 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001377 logEvent(String8::format("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00001378 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1379 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001380 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
Emilian Peev8131a262017-02-01 12:33:43 +00001381 i->getOwnerId(), i->getPriority().getScore(),
1382 i->getPriority().getState(), cameraId.string(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001383 packageName.string(), clientPid, clientPriority.getScore(),
1384 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08001385
1386 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001387 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001388 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001389 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001390 }
1391
Ruben Brunkcc776712015-02-17 20:18:47 -08001392 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1393 // other clients from connecting in mServiceLockWrapper if held
1394 mServiceLock.unlock();
1395
1396 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07001397 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001398
1399 // Destroy evicted clients
1400 for (auto& i : evictedClients) {
1401 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001402 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001403 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001404
Jayant Chowdhary12361932018-08-27 14:46:13 -07001405 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08001406
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001407 for (const auto& i : evictedClients) {
1408 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1409 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1410 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1411 if (ret == TIMED_OUT) {
1412 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1413 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1414 mActiveClientManager.toString().string());
1415 return -EBUSY;
1416 }
1417 if (ret != NO_ERROR) {
1418 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1419 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1420 ret, mActiveClientManager.toString().string());
1421 return ret;
1422 }
1423 }
1424
1425 evictedClients.clear();
1426
Ruben Brunkcc776712015-02-17 20:18:47 -08001427 // Once clients have been disconnected, relock
1428 mServiceLock.lock();
1429
1430 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1431 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1432 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001433 }
1434
Ruben Brunkcc776712015-02-17 20:18:47 -08001435 *partial = clientDescriptor;
1436 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001437}
1438
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001439Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001440 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001441 int api1CameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001442 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001443 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001444 int clientPid,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001445 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001446 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001447
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001448 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001449 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001450
1451 String8 id = cameraIdIntToStr(api1CameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001452 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001453 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001454 clientPackageName, {}, clientUid, clientPid, API_1,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001455 /*shimUpdateOnly*/ false, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001456
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001457 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001458 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001459 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001460 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001461 }
1462
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001463 *device = client;
1464 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001465}
1466
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001467bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
1468 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001469 // If the client is not a vendor client, don't add listener if
1470 // a) the camera is a publicly hidden secure camera OR
1471 // b) the camera is a system only camera and the client doesn't
1472 // have android.permission.SYSTEM_CAMERA permissions.
1473 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
1474 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1475 !hasPermissionsForSystemCamera(clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001476 return true;
1477 }
1478 return false;
1479}
1480
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001481bool CameraService::shouldRejectSystemCameraConnection(const String8& cameraId) const {
1482 // Rules for rejection:
1483 // 1) If cameraserver tries to access this camera device, accept the
1484 // connection.
1485 // 2) The camera device is a publicly hidden secure camera device AND some
1486 // component is trying to access it on a non-hwbinder thread (generally a non HAL client),
1487 // reject it.
1488 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
1489 // and the serving thread is a non hwbinder thread, the client must have
1490 // android.permission.SYSTEM_CAMERA permissions to connect.
1491
1492 int cPid = CameraThreadState::getCallingPid();
1493 int cUid = CameraThreadState::getCallingUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001494 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
1495 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001496 // This isn't a known camera ID, so it's not a system camera
1497 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
1498 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001499 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001500
1501 // (1) Cameraserver trying to connect, accept.
1502 if (CameraThreadState::getCallingPid() == getpid()) {
1503 return false;
1504 }
1505 // (2)
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001506 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001507 systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
1508 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
1509 return true;
1510 }
1511 // (3) Here we only check for permissions if it is a system only camera device. This is since
1512 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
1513 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
1514 // same behavior for system camera devices.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001515 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001516 systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1517 !hasPermissionsForSystemCamera(cPid, cUid)) {
1518 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
1519 cameraId.c_str());
1520 return true;
1521 }
1522
1523 return false;
1524}
1525
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001526Status CameraService::connectDevice(
1527 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001528 const String16& cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001529 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001530 const std::optional<String16>& clientFeatureId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001531 int clientUid,
1532 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001533 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001534
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001535 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001536 Status ret = Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001537 String8 id = String8(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001538 sp<CameraDeviceClient> client = nullptr;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001539 String16 clientPackageNameAdj = clientPackageName;
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001540
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001541 if (getCurrentServingCall() == BinderCallType::HWBINDER) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001542 std::string vendorClient =
1543 StringPrintf("vendor.client.pid<%d>", CameraThreadState::getCallingPid());
1544 clientPackageNameAdj = String16(vendorClient.c_str());
1545 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001546 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001547 /*api1CameraId*/-1, clientPackageNameAdj, clientFeatureId,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001548 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08001549
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001550 if(!ret.isOk()) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001551 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageNameAdj),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001552 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001553 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001554 }
1555
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001556 *device = client;
1557 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001558}
1559
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001560template<class CALLBACK, class CLIENT>
1561Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001562 int api1CameraId, const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001563 const std::optional<String16>& clientFeatureId, int clientUid, int clientPid,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001564 apiLevel effectiveApiLevel, bool shimUpdateOnly,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001565 /*out*/sp<CLIENT>& device) {
1566 binder::Status ret = binder::Status::ok();
1567
1568 String8 clientName8(clientPackageName);
1569
1570 int originalClientPid = 0;
1571
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001572 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001573 "Camera API version %d", clientPid, clientName8.string(), cameraId.string(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001574 static_cast<int>(effectiveApiLevel));
1575
1576 sp<CLIENT> client = nullptr;
1577 {
1578 // Acquire mServiceLock and prevent other clients from connecting
1579 std::unique_ptr<AutoConditionLock> lock =
1580 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1581
1582 if (lock == nullptr) {
1583 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
1584 , clientPid);
1585 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1586 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
1587 cameraId.string(), clientName8.string(), clientPid);
1588 }
1589
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07001590 // Enforce client permissions and do basic validity checks
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001591 if(!(ret = validateConnectLocked(cameraId, clientName8,
1592 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
1593 return ret;
1594 }
1595
1596 // Check the shim parameters after acquiring lock, if they have already been updated and
1597 // we were doing a shim update, return immediately
1598 if (shimUpdateOnly) {
1599 auto cameraState = getCameraState(cameraId);
1600 if (cameraState != nullptr) {
1601 if (!cameraState->getShimParams().isEmpty()) return ret;
1602 }
1603 }
1604
1605 status_t err;
1606
1607 sp<BasicClient> clientTmp = nullptr;
1608 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
1609 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
1610 IInterface::asBinder(cameraCb), clientName8, /*out*/&clientTmp,
1611 /*out*/&partial)) != NO_ERROR) {
1612 switch (err) {
1613 case -ENODEV:
1614 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1615 "No camera device with ID \"%s\" currently available",
1616 cameraId.string());
1617 case -EBUSY:
1618 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1619 "Higher-priority client using camera, ID \"%s\" currently unavailable",
1620 cameraId.string());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001621 case -EUSERS:
1622 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1623 "Too many cameras already open, cannot open camera \"%s\"",
1624 cameraId.string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001625 default:
1626 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1627 "Unexpected error %s (%d) opening camera \"%s\"",
1628 strerror(-err), err, cameraId.string());
1629 }
1630 }
1631
1632 if (clientTmp.get() != nullptr) {
1633 // Handle special case for API1 MediaRecorder where the existing client is returned
1634 device = static_cast<CLIENT*>(clientTmp.get());
1635 return ret;
1636 }
1637
1638 // give flashlight a chance to close devices if necessary.
1639 mFlashlight->prepareDeviceOpen(cameraId);
1640
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001641 int facing = -1;
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001642 int deviceVersion = getDeviceVersion(cameraId, /*out*/&facing);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08001643 if (facing == -1) {
1644 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.string());
1645 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1646 "Unable to get camera device \"%s\" facing", cameraId.string());
1647 }
1648
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001649 sp<BasicClient> tmp = nullptr;
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001650 if(!(ret = makeClient(this, cameraCb, clientPackageName, clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001651 cameraId, api1CameraId, facing,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001652 clientPid, clientUid, getpid(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001653 deviceVersion, effectiveApiLevel,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001654 /*out*/&tmp)).isOk()) {
1655 return ret;
1656 }
1657 client = static_cast<CLIENT*>(tmp.get());
1658
1659 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
1660 __FUNCTION__);
1661
Emilian Peevbd8c5032018-02-14 23:05:40 +00001662 err = client->initialize(mCameraProviderManager, mMonitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001663 if (err != OK) {
1664 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001665 // Errors could be from the HAL module open call or from AppOpsManager
1666 switch(err) {
1667 case BAD_VALUE:
1668 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1669 "Illegal argument to HAL module for camera \"%s\"", cameraId.string());
1670 case -EBUSY:
1671 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1672 "Camera \"%s\" is already open", cameraId.string());
1673 case -EUSERS:
1674 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1675 "Too many cameras already open, cannot open camera \"%s\"",
1676 cameraId.string());
1677 case PERMISSION_DENIED:
1678 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1679 "No permission to open camera \"%s\"", cameraId.string());
1680 case -EACCES:
1681 return STATUS_ERROR_FMT(ERROR_DISABLED,
1682 "Camera \"%s\" disabled by policy", cameraId.string());
1683 case -ENODEV:
1684 default:
1685 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1686 "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
1687 strerror(-err), err);
1688 }
1689 }
1690
1691 // Update shim paremeters for legacy clients
1692 if (effectiveApiLevel == API_1) {
1693 // Assume we have always received a Client subclass for API1
1694 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
1695 String8 rawParams = shimClient->getParameters();
1696 CameraParameters params(rawParams);
1697
1698 auto cameraState = getCameraState(cameraId);
1699 if (cameraState != nullptr) {
1700 cameraState->setShimParams(params);
1701 } else {
1702 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
1703 __FUNCTION__, cameraId.string());
1704 }
1705 }
1706
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001707 // Set rotate-and-crop override behavior
1708 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
1709 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
1710 }
1711
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001712 if (shimUpdateOnly) {
1713 // If only updating legacy shim parameters, immediately disconnect client
1714 mServiceLock.unlock();
1715 client->disconnect();
1716 mServiceLock.lock();
1717 } else {
1718 // Otherwise, add client to active clients list
1719 finishConnectLocked(client, partial);
1720 }
1721 } // lock is destroyed, allow further connect calls
1722
1723 // Important: release the mutex here so the client can call back into the service from its
1724 // destructor (can be at the end of the call)
1725 device = client;
1726 return ret;
1727}
1728
Emilian Peevb2bc5a42019-11-20 16:02:14 -08001729status_t CameraService::addOfflineClient(String8 cameraId, sp<BasicClient> offlineClient) {
1730 if (offlineClient.get() == nullptr) {
1731 return BAD_VALUE;
1732 }
1733
1734 {
1735 // Acquire mServiceLock and prevent other clients from connecting
1736 std::unique_ptr<AutoConditionLock> lock =
1737 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1738
1739 if (lock == nullptr) {
1740 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
1741 , __FUNCTION__, offlineClient->getClientPid());
1742 return TIMED_OUT;
1743 }
1744
1745 auto onlineClientDesc = mActiveClientManager.get(cameraId);
1746 if (onlineClientDesc.get() == nullptr) {
1747 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
1748 cameraId.c_str());
1749 return BAD_VALUE;
1750 }
1751
1752 // Offline clients do not evict or conflict with other online devices. Resource sharing
1753 // conflicts are handled by the camera provider which will either succeed or fail before
1754 // reaching this method.
1755 const auto& onlinePriority = onlineClientDesc->getPriority();
1756 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
1757 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
1758 /*conflictingKeys*/ std::set<String8>(), onlinePriority.getScore(),
1759 onlineClientDesc->getOwnerId(), onlinePriority.getState());
1760
1761 // Allow only one offline device per camera
1762 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
1763 if (!incompatibleClients.empty()) {
1764 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
1765 return BAD_VALUE;
1766 }
1767
1768 auto err = offlineClient->initialize(mCameraProviderManager, mMonitorTags);
1769 if (err != OK) {
1770 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
1771 return err;
1772 }
1773
1774 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
1775 if (evicted.size() > 0) {
1776 for (auto& i : evicted) {
1777 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
1778 __FUNCTION__, i->getKey().string());
1779 }
1780
1781 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
1782 "properly", __FUNCTION__);
1783
1784 return BAD_VALUE;
1785 }
1786
1787 logConnectedOffline(offlineClientDesc->getKey(),
1788 static_cast<int>(offlineClientDesc->getOwnerId()),
1789 String8(offlineClient->getPackageName()));
1790
1791 sp<IBinder> remoteCallback = offlineClient->getRemote();
1792 if (remoteCallback != nullptr) {
1793 remoteCallback->linkToDeath(this);
1794 }
1795 } // lock is destroyed, allow further connect calls
1796
1797 return OK;
1798}
1799
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001800Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001801 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001802 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001803
1804 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07001805 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001806 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001807 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1808 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001809 }
1810
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001811 String8 id = String8(cameraId.string());
Jayant Chowdhary12361932018-08-27 14:46:13 -07001812 int uid = CameraThreadState::getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001813
1814 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08001815 auto state = getCameraState(id);
1816 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001817 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001818 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1819 "Camera ID \"%s\" is a not valid camera ID", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001820 }
1821
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001822 StatusInternal cameraStatus = state->getStatus();
1823 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001824 cameraStatus != StatusInternal::NOT_AVAILABLE) {
1825 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001826 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1827 "Camera ID \"%s\" is a not valid camera ID", id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001828 }
1829
1830 {
1831 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001832 TorchModeStatus status;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001833 status_t err = getTorchStatusLocked(id, &status);
1834 if (err != OK) {
1835 if (err == NAME_NOT_FOUND) {
1836 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1837 "Camera \"%s\" does not have a flash unit", id.string());
1838 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001839 ALOGE("%s: getting current torch status failed for camera %s",
1840 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001841 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1842 "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
1843 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001844 }
1845
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001846 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001847 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001848 ALOGE("%s: torch mode of camera %s is not available because "
1849 "camera is in use", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001850 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1851 "Torch for camera \"%s\" is not available due to an existing camera user",
1852 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001853 } else {
1854 ALOGE("%s: torch mode of camera %s is not available due to "
1855 "insufficient resources", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001856 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1857 "Torch for camera \"%s\" is not available due to insufficient resources",
1858 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001859 }
1860 }
1861 }
1862
Ruben Brunk99e69712015-05-26 17:25:07 -07001863 {
1864 // Update UID map - this is used in the torch status changed callbacks, so must be done
1865 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07001866 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -07001867 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
1868 mTorchUidMap[id].first = uid;
1869 mTorchUidMap[id].second = uid;
1870 } else {
1871 // Set the pending UID
1872 mTorchUidMap[id].first = uid;
1873 }
1874 }
1875
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001876 status_t err = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07001877
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001878 if (err != OK) {
1879 int32_t errorCode;
1880 String8 msg;
1881 switch (err) {
1882 case -ENOSYS:
1883 msg = String8::format("Camera \"%s\" has no flashlight",
1884 id.string());
1885 errorCode = ERROR_ILLEGAL_ARGUMENT;
1886 break;
1887 default:
1888 msg = String8::format(
1889 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
1890 id.string(), enabled, strerror(-err), err);
1891 errorCode = ERROR_INVALID_OPERATION;
1892 }
1893 ALOGE("%s: %s", __FUNCTION__, msg.string());
1894 return STATUS_ERROR(errorCode, msg.string());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001895 }
1896
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001897 {
1898 // update the link to client's death
1899 Mutex::Autolock al(mTorchClientMapMutex);
1900 ssize_t index = mTorchClientMap.indexOfKey(id);
1901 if (enabled) {
1902 if (index == NAME_NOT_FOUND) {
1903 mTorchClientMap.add(id, clientBinder);
1904 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07001905 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001906 mTorchClientMap.replaceValueAt(index, clientBinder);
1907 }
1908 clientBinder->linkToDeath(this);
1909 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07001910 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001911 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001912 }
1913
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07001914 int clientPid = CameraThreadState::getCallingPid();
1915 const char *id_cstr = id.c_str();
1916 const char *torchState = enabled ? "on" : "off";
1917 ALOGI("Torch for camera id %s turned %s for client PID %d", id_cstr, torchState, clientPid);
1918 logTorchEvent(id_cstr, torchState , clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001919 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001920}
1921
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001922Status CameraService::notifySystemEvent(int32_t eventId,
1923 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001924 const int pid = CameraThreadState::getCallingPid();
1925 const int selfPid = getpid();
1926
1927 // Permission checks
1928 if (pid != selfPid) {
1929 // Ensure we're being called by system_server, or similar process with
1930 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001931 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001932 const int uid = CameraThreadState::getCallingUid();
1933 ALOGE("Permission Denial: cannot send updates to camera service about system"
1934 " events from pid=%d, uid=%d", pid, uid);
1935 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09001936 "No permission to send updates to camera service about system events"
1937 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001938 }
1939 }
1940
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001941 ATRACE_CALL();
1942
Ruben Brunk36597b22015-03-20 22:15:57 -07001943 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001944 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001945 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07001946 // from a system server crash
1947 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08001948 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001949 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07001950 break;
1951 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001952 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07001953 default: {
1954 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
1955 eventId);
1956 break;
1957 }
1958 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001959 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07001960}
1961
Emilian Peev53722fa2019-02-22 17:47:20 -08001962void CameraService::notifyMonitoredUids() {
1963 Mutex::Autolock lock(mStatusListenerLock);
1964
1965 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001966 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Emilian Peev53722fa2019-02-22 17:47:20 -08001967 if (!ret.isOk()) {
1968 ALOGE("%s: Failed to trigger permission callback: %d", __FUNCTION__,
1969 ret.exceptionCode());
1970 }
1971 }
1972}
1973
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08001974Status CameraService::notifyDeviceStateChange(int64_t newState) {
1975 const int pid = CameraThreadState::getCallingPid();
1976 const int selfPid = getpid();
1977
1978 // Permission checks
1979 if (pid != selfPid) {
1980 // Ensure we're being called by system_server, or similar process with
1981 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001982 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08001983 const int uid = CameraThreadState::getCallingUid();
1984 ALOGE("Permission Denial: cannot send updates to camera service about device"
1985 " state changes from pid=%d, uid=%d", pid, uid);
1986 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1987 "No permission to send updates to camera service about device state"
1988 " changes from pid=%d, uid=%d", pid, uid);
1989 }
1990 }
1991
1992 ATRACE_CALL();
1993
1994 using hardware::camera::provider::V2_5::DeviceState;
1995 hardware::hidl_bitfield<DeviceState> newDeviceState{};
1996 if (newState & ICameraService::DEVICE_STATE_BACK_COVERED) {
1997 newDeviceState |= DeviceState::BACK_COVERED;
1998 }
1999 if (newState & ICameraService::DEVICE_STATE_FRONT_COVERED) {
2000 newDeviceState |= DeviceState::FRONT_COVERED;
2001 }
2002 if (newState & ICameraService::DEVICE_STATE_FOLDED) {
2003 newDeviceState |= DeviceState::FOLDED;
2004 }
2005 // Only map vendor bits directly
2006 uint64_t vendorBits = static_cast<uint64_t>(newState) & 0xFFFFFFFF00000000l;
2007 newDeviceState |= vendorBits;
2008
2009 ALOGV("%s: New device state 0x%" PRIx64, __FUNCTION__, newDeviceState);
2010 Mutex::Autolock l(mServiceLock);
2011 mCameraProviderManager->notifyDeviceStateChange(newDeviceState);
2012
2013 return Status::ok();
2014}
2015
Jayant Chowdharycad23c22020-03-10 15:04:59 -07002016 Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002017 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
2018 ATRACE_CALL();
2019 if (!concurrentCameraIds) {
2020 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
2021 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
2022 }
2023
2024 if (!mInitialized) {
2025 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2026 return STATUS_ERROR(ERROR_DISCONNECTED,
2027 "Camera subsystem is not available");
2028 }
2029 // First call into the provider and get the set of concurrent camera
2030 // combinations
2031 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07002032 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002033 for (auto &combination : concurrentCameraCombinations) {
2034 std::vector<std::string> validCombination;
2035 for (auto &cameraId : combination) {
2036 // if the camera state is not present, skip
2037 String8 cameraIdStr(cameraId.c_str());
2038 auto state = getCameraState(cameraIdStr);
2039 if (state == nullptr) {
2040 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
2041 continue;
2042 }
2043 StatusInternal status = state->getStatus();
2044 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
2045 continue;
2046 }
2047 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
2048 continue;
2049 }
2050 validCombination.push_back(cameraId);
2051 }
2052 if (validCombination.size() != 0) {
2053 concurrentCameraIds->push_back(std::move(validCombination));
2054 }
2055 }
2056 return Status::ok();
2057}
2058
2059Status CameraService::isConcurrentSessionConfigurationSupported(
2060 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
2061 /*out*/bool* isSupported) {
2062 if (!isSupported) {
2063 ALOGE("%s: isSupported is NULL", __FUNCTION__);
2064 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
2065 }
2066
2067 if (!mInitialized) {
2068 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2069 return STATUS_ERROR(ERROR_DISCONNECTED,
2070 "Camera subsystem is not available");
2071 }
2072
2073 // Check for camera permissions
2074 int callingPid = CameraThreadState::getCallingPid();
2075 int callingUid = CameraThreadState::getCallingUid();
2076 if ((callingPid != getpid()) && !checkPermission(sCameraPermission, callingPid, callingUid)) {
2077 ALOGE("%s: pid %d doesn't have camera permissions", __FUNCTION__, callingPid);
2078 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2079 "android.permission.CAMERA needed to call"
2080 "isConcurrentSessionConfigurationSupported");
2081 }
2082
2083 status_t res =
2084 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
2085 cameraIdsAndSessionConfigurations, isSupported);
2086 if (res != OK) {
2087 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
2088 "support %s (%d)", strerror(-res), res);
2089 }
2090 return Status::ok();
2091}
2092
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002093Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
2094 /*out*/
2095 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002096 return addListenerHelper(listener, cameraStatuses);
2097}
2098
2099Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
2100 /*out*/
2101 std::vector<hardware::CameraStatus> *cameraStatuses,
2102 bool isVendorListener) {
2103
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002104 ATRACE_CALL();
2105
Igor Murashkinbfc99152013-02-27 12:55:20 -08002106 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08002107
Ruben Brunk3450ba72015-06-16 11:00:37 -07002108 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002109 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002110 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002111 }
2112
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002113 auto clientUid = CameraThreadState::getCallingUid();
2114 auto clientPid = CameraThreadState::getCallingPid();
Shuzhen Wang695044d2020-03-06 09:02:23 -08002115 bool openCloseCallbackAllowed = checkPermission(sCameraOpenCloseListenerPermission,
2116 clientPid, clientUid);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002117
Igor Murashkinbfc99152013-02-27 12:55:20 -08002118 Mutex::Autolock lock(mServiceLock);
2119
Ruben Brunkcc776712015-02-17 20:18:47 -08002120 {
2121 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08002122 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002123 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002124 ALOGW("%s: Tried to add listener %p which was already subscribed",
2125 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002126 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08002127 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002128 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002129
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002130 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08002131 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
2132 openCloseCallbackAllowed);
Emilian Peev53722fa2019-02-22 17:47:20 -08002133 auto ret = serviceListener->initialize();
2134 if (ret != NO_ERROR) {
2135 String8 msg = String8::format("Failed to initialize service listener: %s (%d)",
2136 strerror(-ret), ret);
2137 ALOGE("%s: %s", __FUNCTION__, msg.string());
2138 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
2139 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002140 // The listener still needs to be added to the list of listeners, regardless of what
2141 // permissions the listener process has / whether it is a vendor listener. Since it might be
2142 // eligible to listen to other camera ids.
2143 mListenerList.emplace_back(serviceListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08002144 mUidPolicy->registerMonitorUid(clientUid);
Igor Murashkinbfc99152013-02-27 12:55:20 -08002145 }
2146
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002147 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07002148 {
Ruben Brunkcc776712015-02-17 20:18:47 -08002149 Mutex::Autolock lock(mCameraStatesLock);
2150 for (auto& i : mCameraStates) {
Shuzhen Wang43858162020-01-10 13:42:15 -08002151 cameraStatuses->emplace_back(i.first,
2152 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds());
Igor Murashkincba2c162013-03-20 15:56:31 -07002153 }
2154 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002155 // Remove the camera statuses that should be hidden from the client, we do
2156 // this after collecting the states in order to avoid holding
2157 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
2158 // the same time.
2159 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
2160 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
2161 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
2162 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
2163 ALOGE("%s: Invalid camera id %s, skipping status update",
2164 __FUNCTION__, s.cameraId.c_str());
2165 return true;
2166 }
2167 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
2168 clientUid);}), cameraStatuses->end());
2169
Igor Murashkincba2c162013-03-20 15:56:31 -07002170
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002171 /*
2172 * Immediately signal current torch status to this listener only
2173 * This may be a subset of all the devices, so don't include it in the response directly
2174 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002175 {
2176 Mutex::Autolock al(mTorchStatusMutex);
2177 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002178 String16 id = String16(mTorchStatusMap.keyAt(i).string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002179 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002180 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002181 }
2182
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002183 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08002184}
Ruben Brunkcc776712015-02-17 20:18:47 -08002185
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002186Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002187 ATRACE_CALL();
2188
Igor Murashkinbfc99152013-02-27 12:55:20 -08002189 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
2190
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002191 if (listener == 0) {
2192 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002193 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002194 }
2195
Igor Murashkinbfc99152013-02-27 12:55:20 -08002196 Mutex::Autolock lock(mServiceLock);
2197
Ruben Brunkcc776712015-02-17 20:18:47 -08002198 {
2199 Mutex::Autolock lock(mStatusListenerLock);
2200 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002201 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
2202 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid());
2203 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08002204 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002205 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002206 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002207 }
2208 }
2209
2210 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
2211 __FUNCTION__, listener.get());
2212
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002213 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08002214}
2215
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002216Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002217
2218 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002219 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
2220
2221 if (parameters == NULL) {
2222 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002223 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07002224 }
2225
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002226 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002227
2228 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002229 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07002230 // Error logged by caller
2231 return ret;
2232 }
2233
2234 String8 shimParamsString8 = shimParams.flatten();
2235 String16 shimParamsString16 = String16(shimParamsString8);
2236
2237 *parameters = shimParamsString16;
2238
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002239 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07002240}
2241
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002242Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
2243 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002244 ATRACE_CALL();
2245
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002246 const String8 id = String8(cameraId);
2247
2248 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002249
2250 switch (apiVersion) {
2251 case API_VERSION_1:
2252 case API_VERSION_2:
2253 break;
2254 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002255 String8 msg = String8::format("Unknown API version %d", apiVersion);
2256 ALOGE("%s: %s", __FUNCTION__, msg.string());
2257 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002258 }
2259
Emilian Peev28ad2ea2017-02-07 16:14:32 +00002260 int deviceVersion = getDeviceVersion(id);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002261 switch (deviceVersion) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002262 case CAMERA_DEVICE_API_VERSION_1_0:
2263 case CAMERA_DEVICE_API_VERSION_3_0:
2264 case CAMERA_DEVICE_API_VERSION_3_1:
2265 if (apiVersion == API_VERSION_2) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002266 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without shim",
2267 __FUNCTION__, id.string(), deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002268 *isSupported = false;
2269 } else { // if (apiVersion == API_VERSION_1) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002270 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always supported",
2271 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002272 *isSupported = true;
2273 }
2274 break;
2275 case CAMERA_DEVICE_API_VERSION_3_2:
2276 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -07002277 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002278 case CAMERA_DEVICE_API_VERSION_3_5:
Yin-Chia Yeh56d98ba2020-01-16 16:57:14 -08002279 case CAMERA_DEVICE_API_VERSION_3_6:
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002280 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
2281 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002282 *isSupported = true;
2283 break;
2284 case -1: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002285 String8 msg = String8::format("Unknown camera ID %s", id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002286 ALOGE("%s: %s", __FUNCTION__, msg.string());
2287 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002288 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002289 default: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002290 String8 msg = String8::format("Unknown device version %x for device %s",
2291 deviceVersion, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002292 ALOGE("%s: %s", __FUNCTION__, msg.string());
2293 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
2294 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07002295 }
2296
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002297 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002298}
2299
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002300Status CameraService::isHiddenPhysicalCamera(const String16& cameraId,
2301 /*out*/ bool *isSupported) {
2302 ATRACE_CALL();
2303
2304 const String8 id = String8(cameraId);
2305
2306 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
2307 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(id.string());
2308
2309 return Status::ok();
2310}
2311
Ruben Brunkcc776712015-02-17 20:18:47 -08002312void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002313 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002314 for (auto& i : mActiveClientManager.getAll()) {
2315 auto clientSp = i->getValue();
2316 if (clientSp.get() == client) {
2317 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08002318 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07002319 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002320 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08002321}
2322
Ruben Brunkcc776712015-02-17 20:18:47 -08002323bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002324 bool ret = false;
2325 {
2326 // Acquire mServiceLock and prevent other clients from connecting
2327 std::unique_ptr<AutoConditionLock> lock =
2328 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08002329
Igor Murashkin634a5152013-02-20 17:15:11 -08002330
Ruben Brunkcc776712015-02-17 20:18:47 -08002331 std::vector<sp<BasicClient>> evicted;
2332 for (auto& i : mActiveClientManager.getAll()) {
2333 auto clientSp = i->getValue();
2334 if (clientSp.get() == nullptr) {
2335 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2336 mActiveClientManager.remove(i);
2337 continue;
2338 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08002339 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002340 mActiveClientManager.remove(i);
2341 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08002342
Ruben Brunkcc776712015-02-17 20:18:47 -08002343 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002344 clientSp->notifyError(
2345 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002346 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08002347 }
2348 }
2349
Ruben Brunkcc776712015-02-17 20:18:47 -08002350 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2351 // other clients from connecting in mServiceLockWrapper if held
2352 mServiceLock.unlock();
2353
Ruben Brunk36597b22015-03-20 22:15:57 -07002354 // Do not clear caller identity, remote caller should be client proccess
2355
Ruben Brunkcc776712015-02-17 20:18:47 -08002356 for (auto& i : evicted) {
2357 if (i.get() != nullptr) {
2358 i->disconnect();
2359 ret = true;
2360 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002361 }
2362
Ruben Brunkcc776712015-02-17 20:18:47 -08002363 // Reacquire mServiceLock
2364 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08002365
Ruben Brunkcc776712015-02-17 20:18:47 -08002366 } // lock is destroyed, allow further connect calls
2367
2368 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07002369}
2370
Ruben Brunkcc776712015-02-17 20:18:47 -08002371std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
2372 const String8& cameraId) const {
2373 std::shared_ptr<CameraState> state;
2374 {
2375 Mutex::Autolock lock(mCameraStatesLock);
2376 auto iter = mCameraStates.find(cameraId);
2377 if (iter != mCameraStates.end()) {
2378 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002379 }
2380 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002381 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002382}
2383
Ruben Brunkcc776712015-02-17 20:18:47 -08002384sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
2385 // Remove from active clients list
2386 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
2387 if (clientDescriptorPtr == nullptr) {
2388 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
2389 cameraId.string());
2390 return sp<BasicClient>{nullptr};
2391 }
2392
2393 return clientDescriptorPtr->getValue();
Keun young Parkd8973a72012-03-28 14:13:09 -07002394}
2395
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002396void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07002397 // Acquire mServiceLock and prevent other clients from connecting
2398 std::unique_ptr<AutoConditionLock> lock =
2399 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
2400
Ruben Brunk6267b532015-04-30 17:44:07 -07002401 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002402 for (size_t i = 0; i < newUserIds.size(); i++) {
2403 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07002404 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002405 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07002406 return;
2407 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002408 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07002409 }
2410
Ruben Brunka8ca9152015-04-07 14:23:40 -07002411
Ruben Brunk6267b532015-04-30 17:44:07 -07002412 if (newAllowedUsers == mAllowedUsers) {
2413 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
2414 return;
2415 }
2416
2417 logUserSwitch(mAllowedUsers, newAllowedUsers);
2418
2419 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07002420
2421 // Current user has switched, evict all current clients.
2422 std::vector<sp<BasicClient>> evicted;
2423 for (auto& i : mActiveClientManager.getAll()) {
2424 auto clientSp = i->getValue();
2425
2426 if (clientSp.get() == nullptr) {
2427 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2428 continue;
2429 }
2430
Ruben Brunk6267b532015-04-30 17:44:07 -07002431 // Don't evict clients that are still allowed.
2432 uid_t clientUid = clientSp->getClientUid();
2433 userid_t clientUserId = multiuser_get_user_id(clientUid);
2434 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
2435 continue;
2436 }
2437
Ruben Brunk36597b22015-03-20 22:15:57 -07002438 evicted.push_back(clientSp);
2439
2440 String8 curTime = getFormattedCurrentTime();
2441
2442 ALOGE("Evicting conflicting client for camera ID %s due to user change",
2443 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07002444
Ruben Brunk36597b22015-03-20 22:15:57 -07002445 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002446 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00002447 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
2448 " to user switch.", i->getKey().string(),
2449 String8{clientSp->getPackageName()}.string(),
2450 i->getOwnerId(), i->getPriority().getScore(),
2451 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07002452
2453 }
2454
2455 // Do not hold mServiceLock while disconnecting clients, but retain the condition
2456 // blocking other clients from connecting in mServiceLockWrapper if held.
2457 mServiceLock.unlock();
2458
2459 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07002460 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07002461
2462 for (auto& i : evicted) {
2463 i->disconnect();
2464 }
2465
Jayant Chowdhary12361932018-08-27 14:46:13 -07002466 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07002467
2468 // Reacquire mServiceLock
2469 mServiceLock.lock();
2470}
Ruben Brunkcc776712015-02-17 20:18:47 -08002471
Ruben Brunka8ca9152015-04-07 14:23:40 -07002472void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002473 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07002474 Mutex::Autolock l(mLogLock);
2475 mEventLog.add(String8::format("%s : %s", curTime.string(), event));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002476}
2477
Ruben Brunka8ca9152015-04-07 14:23:40 -07002478void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002479 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002480 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002481 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002482 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002483}
2484
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002485void CameraService::logDisconnectedOffline(const char* cameraId, int clientPid,
2486 const char* clientPackage) {
2487 // Log the clients evicted
2488 logEvent(String8::format("DISCONNECT offline device %s client for package %s (PID %d)",
2489 cameraId, clientPackage, clientPid));
2490}
2491
Ruben Brunka8ca9152015-04-07 14:23:40 -07002492void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002493 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002494 // Log the clients evicted
2495 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002496 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002497}
2498
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002499void CameraService::logConnectedOffline(const char* cameraId, int clientPid,
2500 const char* clientPackage) {
2501 // Log the clients evicted
2502 logEvent(String8::format("CONNECT offline device %s client for package %s (PID %d)", cameraId,
2503 clientPackage, clientPid));
2504}
2505
Ruben Brunka8ca9152015-04-07 14:23:40 -07002506void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002507 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002508 // Log the client rejected
2509 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002510 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002511}
2512
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002513void CameraService::logTorchEvent(const char* cameraId, const char *torchState, int clientPid) {
2514 // Log torch event
2515 logEvent(String8::format("Torch for camera id %s turned %s for client PID %d", cameraId,
2516 torchState, clientPid));
2517}
2518
Ruben Brunk6267b532015-04-30 17:44:07 -07002519void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
2520 const std::set<userid_t>& newUserIds) {
2521 String8 newUsers = toString(newUserIds);
2522 String8 oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002523 if (oldUsers.size() == 0) {
2524 oldUsers = "<None>";
2525 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07002526 // Log the new and old users
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002527 logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
Ruben Brunk6267b532015-04-30 17:44:07 -07002528 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002529}
2530
2531void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
2532 // Log the device removal
2533 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
2534}
2535
2536void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
2537 // Log the device removal
2538 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
2539}
2540
2541void CameraService::logClientDied(int clientPid, const char* reason) {
2542 // Log the device removal
2543 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07002544}
2545
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002546void CameraService::logServiceError(const char* msg, int errorCode) {
2547 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002548 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002549}
2550
Ruben Brunk36597b22015-03-20 22:15:57 -07002551status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
2552 uint32_t flags) {
2553
Mathias Agopian65ab4712010-07-14 17:59:35 -07002554 // Permission checks
2555 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002556 case SHELL_COMMAND_TRANSACTION: {
2557 int in = data.readFileDescriptor();
2558 int out = data.readFileDescriptor();
2559 int err = data.readFileDescriptor();
2560 int argc = data.readInt32();
2561 Vector<String16> args;
2562 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
2563 args.add(data.readString16());
2564 }
2565 sp<IBinder> unusedCallback;
2566 sp<IResultReceiver> resultReceiver;
2567 status_t status;
2568 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
2569 return status;
2570 }
2571 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
2572 return status;
2573 }
2574 status = shellCommand(in, out, err, args);
2575 if (resultReceiver != nullptr) {
2576 resultReceiver->send(status);
2577 }
2578 return NO_ERROR;
2579 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002580 }
2581
2582 return BnCameraService::onTransact(code, data, reply, flags);
2583}
2584
Mathias Agopian65ab4712010-07-14 17:59:35 -07002585// We share the media players for shutter and recording sound for all clients.
2586// A reference count is kept to determine when we will actually release the
2587// media players.
2588
Jaekyun Seokef498052018-03-23 13:09:44 +09002589sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
2590 sp<MediaPlayer> mp = new MediaPlayer();
2591 status_t error;
2592 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08002593 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09002594 error = mp->prepare();
2595 }
2596 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00002597 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09002598 mp->disconnect();
2599 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002600 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002601 }
2602 return mp;
2603}
2604
username5755fea2018-12-27 09:48:08 +08002605void CameraService::increaseSoundRef() {
2606 Mutex::Autolock lock(mSoundLock);
2607 mSoundRef++;
2608}
2609
2610void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002611 ATRACE_CALL();
2612
username5755fea2018-12-27 09:48:08 +08002613 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
2614 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
2615 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
2616 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
2617 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
2618 }
2619 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
2620 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
2621 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
2622 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002623 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08002624 }
2625 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
2626 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
2627 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
2628 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
2629 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002630 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002631}
2632
username5755fea2018-12-27 09:48:08 +08002633void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002634 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002635 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002636 if (--mSoundRef) return;
2637
2638 for (int i = 0; i < NUM_SOUNDS; i++) {
2639 if (mSoundPlayer[i] != 0) {
2640 mSoundPlayer[i]->disconnect();
2641 mSoundPlayer[i].clear();
2642 }
2643 }
2644}
2645
2646void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002647 ATRACE_CALL();
2648
Mathias Agopian65ab4712010-07-14 17:59:35 -07002649 LOG1("playSound(%d)", kind);
2650 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002651 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002652 sp<MediaPlayer> player = mSoundPlayer[kind];
2653 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08002654 player->seekTo(0);
2655 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002656 }
2657}
2658
2659// ----------------------------------------------------------------------------
2660
2661CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07002662 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002663 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09002664 const std::optional<String16>& clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002665 const String8& cameraIdStr,
2666 int api1CameraId, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002667 int clientPid, uid_t clientUid,
2668 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002669 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08002670 IInterface::asBinder(cameraClient),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002671 clientPackageName, clientFeatureId,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002672 cameraIdStr, cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002673 clientPid, clientUid,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002674 servicePid),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002675 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08002676{
Jayant Chowdhary12361932018-08-27 14:46:13 -07002677 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002678 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002679
Igor Murashkin44cfcf02013-03-01 16:22:28 -08002680 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002681
username5755fea2018-12-27 09:48:08 +08002682 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002683
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002684 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002685}
2686
Mathias Agopian65ab4712010-07-14 17:59:35 -07002687// tear down the client
2688CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002689 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08002690 mDestructionStarted = true;
2691
username5755fea2018-12-27 09:48:08 +08002692 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002693 // unconditionally disconnect. function is idempotent
2694 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002695}
2696
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002697sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
2698
Igor Murashkin634a5152013-02-20 17:15:11 -08002699CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002700 const sp<IBinder>& remoteCallback,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09002701 const String16& clientPackageName, const std::optional<String16>& clientFeatureId,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002702 const String8& cameraIdStr, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002703 int clientPid, uid_t clientUid,
2704 int servicePid):
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002705 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing),
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09002706 mClientPackageName(clientPackageName), mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002707 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002708 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07002709 mDisconnected(false), mUidIsTrusted(false),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002710 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002711 mRemoteBinder(remoteCallback)
Igor Murashkin634a5152013-02-20 17:15:11 -08002712{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002713 if (sCameraService == nullptr) {
2714 sCameraService = cameraService;
2715 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002716 mOpsActive = false;
Igor Murashkin634a5152013-02-20 17:15:11 -08002717 mDestructionStarted = false;
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08002718
2719 // In some cases the calling code has no access to the package it runs under.
2720 // For example, NDK camera API.
2721 // In this case we will get the packages for the calling UID and pick the first one
2722 // for attributing the app op. This will work correctly for runtime permissions
2723 // as for legacy apps we will toggle the app op for all packages in the UID.
2724 // The caveat is that the operation may be attributed to the wrong package and
2725 // stats based on app ops may be slightly off.
2726 if (mClientPackageName.size() <= 0) {
2727 sp<IServiceManager> sm = defaultServiceManager();
2728 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
2729 if (binder == 0) {
2730 ALOGE("Cannot get permission service");
2731 // Leave mClientPackageName unchanged (empty) and the further interaction
2732 // with camera will fail in BasicClient::startCameraOps
2733 return;
2734 }
2735
2736 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
2737 Vector<String16> packages;
2738
2739 permCtrl->getPackagesForUid(mClientUid, packages);
2740
2741 if (packages.isEmpty()) {
2742 ALOGE("No packages for calling UID");
2743 // Leave mClientPackageName unchanged (empty) and the further interaction
2744 // with camera will fail in BasicClient::startCameraOps
2745 return;
2746 }
2747 mClientPackageName = packages[0];
2748 }
Steven Moreland89a2c5c2020-01-31 15:02:25 -08002749 if (getCurrentServingCall() != BinderCallType::HWBINDER) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002750 mAppOpsManager = std::make_unique<AppOpsManager>();
2751 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07002752
2753 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08002754}
2755
2756CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002757 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08002758 mDestructionStarted = true;
2759}
2760
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002761binder::Status CameraService::BasicClient::disconnect() {
2762 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002763 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002764 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07002765 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07002766 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002767
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002768 sCameraService->removeByClient(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002769 sCameraService->logDisconnected(mCameraIdStr, mClientPid, String8(mClientPackageName));
Peter Kalauskasa29c1352018-10-10 12:05:42 -07002770 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
2771 mCameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002772
2773 sp<IBinder> remote = getRemote();
2774 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002775 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08002776 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002777
2778 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07002779 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002780 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
2781 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
2782 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002783
Igor Murashkincba2c162013-03-20 15:56:31 -07002784 // client shouldn't be able to call into us anymore
2785 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002786
2787 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08002788}
2789
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002790status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
2791 // No dumping of clients directly over Binder,
2792 // must go through CameraService::dump
2793 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07002794 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002795 return OK;
2796}
2797
Ruben Brunkcc776712015-02-17 20:18:47 -08002798String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002799 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08002800}
2801
2802
2803int CameraService::BasicClient::getClientPid() const {
2804 return mClientPid;
2805}
2806
Ruben Brunk6267b532015-04-30 17:44:07 -07002807uid_t CameraService::BasicClient::getClientUid() const {
2808 return mClientUid;
2809}
2810
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002811bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
2812 // Defaults to API2.
2813 return level == API_2;
2814}
2815
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002816status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002817 {
2818 Mutex::Autolock l(mAudioRestrictionLock);
2819 mAudioRestriction = mode;
2820 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002821 sCameraService->updateAudioRestriction();
2822 return OK;
2823}
2824
2825int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002826 return sCameraService->updateAudioRestriction();
2827}
2828
2829int32_t CameraService::BasicClient::getAudioRestriction() const {
2830 Mutex::Autolock l(mAudioRestrictionLock);
2831 return mAudioRestriction;
2832}
2833
2834bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
2835 switch (mode) {
2836 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
2837 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
2838 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
2839 return true;
2840 default:
2841 return false;
2842 }
2843}
2844
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002845status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002846 ATRACE_CALL();
2847
Igor Murashkine6800ce2013-03-04 17:25:57 -08002848 {
2849 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002850 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08002851 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002852 if (mAppOpsManager != nullptr) {
2853 // Notify app ops that the camera is not available
2854 mOpsCallback = new OpsCallback(this);
2855 int32_t res;
2856 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
2857 mClientPackageName, mOpsCallback);
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002858 res = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
2859 mClientPackageName, /*startIfModeDefault*/ false, mClientFeatureId,
2860 String16("start camera ") + String16(mCameraIdStr));
Igor Murashkine6800ce2013-03-04 17:25:57 -08002861
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002862 if (res == AppOpsManager::MODE_ERRORED) {
2863 ALOGI("Camera %s: Access for \"%s\" has been revoked",
2864 mCameraIdStr.string(), String8(mClientPackageName).string());
2865 return PERMISSION_DENIED;
2866 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002867
Shuzhen Wang2c656792020-04-13 17:36:49 -07002868 // If the calling Uid is trusted (a native service), the AppOpsManager could
2869 // return MODE_IGNORED. Do not treat such case as error.
2870 if (!mUidIsTrusted && res == AppOpsManager::MODE_IGNORED) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002871 ALOGI("Camera %s: Access for \"%s\" has been restricted",
2872 mCameraIdStr.string(), String8(mClientPackageName).string());
2873 // Return the same error as for device policy manager rejection
2874 return -EACCES;
2875 }
Svetoslav28e8ef72015-05-11 19:21:31 -07002876 }
2877
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002878 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002879
2880 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002881 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002882
Emilian Peev573291c2018-02-10 02:10:56 +00002883 int apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_1;
2884 if (canCastToApiClient(API_2)) {
2885 apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_2;
2886 }
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002887 // Transition device state to OPEN
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002888 sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_OPEN,
Emilian Peev573291c2018-02-10 02:10:56 +00002889 mCameraIdStr, mCameraFacing, mClientPackageName, apiLevel);
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002890
Emilian Peev53722fa2019-02-22 17:47:20 -08002891 sCameraService->mUidPolicy->registerMonitorUid(mClientUid);
2892
Shuzhen Wang695044d2020-03-06 09:02:23 -08002893 // Notify listeners of camera open/close status
2894 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
2895
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002896 return OK;
2897}
2898
2899status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002900 ATRACE_CALL();
2901
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002902 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002903 if (mOpsActive) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002904 // Notify app ops that the camera is available again
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002905 if (mAppOpsManager != nullptr) {
2906 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002907 mClientPackageName, mClientFeatureId);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002908 mOpsActive = false;
2909 }
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002910 // This function is called when a client disconnects. This should
2911 // release the camera, but actually only if it was in a proper
2912 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002913 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002914 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002915
Ruben Brunkcc776712015-02-17 20:18:47 -08002916 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002917 sCameraService->updateStatus(StatusInternal::PRESENT,
2918 mCameraIdStr, rejected);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002919
Emilian Peev573291c2018-02-10 02:10:56 +00002920 int apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_1;
2921 if (canCastToApiClient(API_2)) {
2922 apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_2;
2923 }
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002924 // Transition device state to CLOSED
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002925 sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_CLOSED,
Emilian Peev573291c2018-02-10 02:10:56 +00002926 mCameraIdStr, mCameraFacing, mClientPackageName, apiLevel);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002927 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002928 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002929 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
2930 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002931 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002932 mOpsCallback.clear();
2933
Emilian Peev53722fa2019-02-22 17:47:20 -08002934 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid);
2935
Shuzhen Wang695044d2020-03-06 09:02:23 -08002936 // Notify listeners of camera open/close status
2937 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
2938
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002939 return OK;
2940}
2941
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002942void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002943 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002944 if (mAppOpsManager == nullptr) {
2945 return;
2946 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002947 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002948 if (op != AppOpsManager::OP_CAMERA) {
2949 ALOGW("Unexpected app ops notification received: %d", op);
2950 return;
2951 }
2952
2953 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002954 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002955 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002956 ALOGV("checkOp returns: %d, %s ", res,
2957 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
2958 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
2959 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
2960 "UNKNOWN");
2961
2962 if (res != AppOpsManager::MODE_ALLOWED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002963 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002964 String8(mClientPackageName).string());
Svet Ganova453d0d2018-01-11 15:37:58 -08002965 block();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002966 }
2967}
2968
Svet Ganova453d0d2018-01-11 15:37:58 -08002969void CameraService::BasicClient::block() {
2970 ATRACE_CALL();
2971
2972 // Reset the client PID to allow server-initiated disconnect,
2973 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07002974 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08002975 CaptureResultExtras resultExtras; // a dummy result (invalid)
2976 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
2977 disconnect();
2978}
2979
Mathias Agopian65ab4712010-07-14 17:59:35 -07002980// ----------------------------------------------------------------------------
2981
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002982void CameraService::Client::notifyError(int32_t errorCode,
Jianing Weicb0652e2014-03-12 18:29:36 -07002983 const CaptureResultExtras& resultExtras) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002984 (void) resultExtras;
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07002985 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07002986 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
2987 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
2988 api1ErrorCode = CAMERA_ERROR_DISABLED;
2989 }
2990 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07002991 } else {
2992 ALOGE("mRemoteCallback is NULL!!");
2993 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002994}
2995
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002996// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002997binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002998 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002999 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08003000}
3001
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003002bool CameraService::Client::canCastToApiClient(apiLevel level) const {
3003 return level == API_1;
3004}
3005
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003006CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
3007 mClient(client) {
3008}
3009
3010void CameraService::Client::OpsCallback::opChanged(int32_t op,
3011 const String16& packageName) {
3012 sp<BasicClient> client = mClient.promote();
3013 if (client != NULL) {
3014 client->opChanged(op, packageName);
3015 }
3016}
3017
Mathias Agopian65ab4712010-07-14 17:59:35 -07003018// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08003019// UidPolicy
3020// ----------------------------------------------------------------------------
3021
3022void CameraService::UidPolicy::registerSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003023 Mutex::Autolock _l(mUidLock);
3024
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003025 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07003026 status_t res = mAm.linkToDeath(this);
3027 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08003028 | ActivityManager::UID_OBSERVER_IDLE
Emilian Peev53722fa2019-02-22 17:47:20 -08003029 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganova453d0d2018-01-11 15:37:58 -08003030 ActivityManager::PROCESS_STATE_UNKNOWN,
3031 String16("cameraserver"));
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003032 if (res == OK) {
3033 mRegistered = true;
3034 ALOGV("UidPolicy: Registered with ActivityManager");
3035 }
Svet Ganova453d0d2018-01-11 15:37:58 -08003036}
3037
3038void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003039 Mutex::Autolock _l(mUidLock);
3040
Steven Moreland2f348142019-07-02 15:59:07 -07003041 mAm.unregisterUidObserver(this);
3042 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003043 mRegistered = false;
3044 mActiveUids.clear();
3045 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08003046}
3047
3048void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
3049 onUidIdle(uid, disabled);
3050}
3051
3052void CameraService::UidPolicy::onUidActive(uid_t uid) {
3053 Mutex::Autolock _l(mUidLock);
3054 mActiveUids.insert(uid);
3055}
3056
3057void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
3058 bool deleted = false;
3059 {
3060 Mutex::Autolock _l(mUidLock);
3061 if (mActiveUids.erase(uid) > 0) {
3062 deleted = true;
3063 }
3064 }
3065 if (deleted) {
3066 sp<CameraService> service = mService.promote();
3067 if (service != nullptr) {
3068 service->blockClientsForUid(uid);
3069 }
3070 }
3071}
3072
Emilian Peev53722fa2019-02-22 17:47:20 -08003073void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07003074 int64_t procStateSeq __unused, int32_t capability __unused) {
Emilian Peev53722fa2019-02-22 17:47:20 -08003075 bool procStateChange = false;
3076 {
3077 Mutex::Autolock _l(mUidLock);
3078 if ((mMonitoredUids.find(uid) != mMonitoredUids.end()) &&
3079 (mMonitoredUids[uid].first != procState)) {
3080 mMonitoredUids[uid].first = procState;
3081 procStateChange = true;
3082 }
3083 }
3084
3085 if (procStateChange) {
3086 sp<CameraService> service = mService.promote();
3087 if (service != nullptr) {
3088 service->notifyMonitoredUids();
3089 }
3090 }
3091}
3092
3093void CameraService::UidPolicy::registerMonitorUid(uid_t uid) {
3094 Mutex::Autolock _l(mUidLock);
3095 auto it = mMonitoredUids.find(uid);
3096 if (it != mMonitoredUids.end()) {
3097 it->second.second++;
3098 } else {
3099 mMonitoredUids.emplace(
3100 std::pair<uid_t, std::pair<int32_t, size_t>> (uid,
3101 std::pair<int32_t, size_t> (ActivityManager::PROCESS_STATE_NONEXISTENT, 1)));
3102 }
3103}
3104
3105void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid) {
3106 Mutex::Autolock _l(mUidLock);
3107 auto it = mMonitoredUids.find(uid);
3108 if (it != mMonitoredUids.end()) {
3109 it->second.second--;
3110 if (it->second.second == 0) {
3111 mMonitoredUids.erase(it);
3112 }
3113 } else {
3114 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
3115 }
3116}
3117
Svet Ganov7b4ab782018-03-25 12:48:10 -07003118bool CameraService::UidPolicy::isUidActive(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003119 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003120 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003121}
3122
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003123static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
3124static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003125
Svet Ganov7b4ab782018-03-25 12:48:10 -07003126bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003127 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003128 // If activity manager is unreachable, assume everything is active
3129 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003130 return true;
3131 }
3132 auto it = mOverrideUids.find(uid);
3133 if (it != mOverrideUids.end()) {
3134 return it->second;
3135 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003136 bool active = mActiveUids.find(uid) != mActiveUids.end();
3137 if (!active) {
3138 // We want active UIDs to always access camera with their first attempt since
3139 // there is no guarantee the app is robustly written and would retry getting
3140 // the camera on failure. The inverse case is not a problem as we would take
3141 // camera away soon once we get the callback that the uid is no longer active.
3142 ActivityManager am;
3143 // Okay to access with a lock held as UID changes are dispatched without
3144 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07003145 int64_t startTimeMillis = 0;
3146 do {
3147 // TODO: Fix this b/109950150!
3148 // Okay this is a hack. There is a race between the UID turning active and
3149 // activity being resumed. The proper fix is very risky, so we temporary add
3150 // some polling which should happen pretty rarely anyway as the race is hard
3151 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003152 active = mActiveUids.find(uid) != mActiveUids.end();
Hui Yu12c7ec72020-05-04 17:40:52 +00003153 if (!active) active = am.isUidActive(uid, callingPackage);
Svet Ganov94ec46f2018-06-08 15:03:46 -07003154 if (active) {
3155 break;
3156 }
3157 if (startTimeMillis <= 0) {
3158 startTimeMillis = uptimeMillis();
3159 }
3160 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003161 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003162 if (remainingTimeMillis <= 0) {
3163 break;
3164 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003165 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
3166
3167 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003168 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003169 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003170 } while (true);
3171
Svet Ganov7b4ab782018-03-25 12:48:10 -07003172 if (active) {
3173 // Now that we found out the UID is actually active, cache that
3174 mActiveUids.insert(uid);
3175 }
3176 }
3177 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08003178}
3179
Varun Shahb42f1eb2019-04-16 14:45:13 -07003180int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
3181 Mutex::Autolock _l(mUidLock);
3182 return getProcStateLocked(uid);
3183}
3184
3185int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
3186 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
3187 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
3188 procState = mMonitoredUids[uid].first;
3189 }
3190 return procState;
3191}
3192
Svet Ganov7b4ab782018-03-25 12:48:10 -07003193void CameraService::UidPolicy::UidPolicy::addOverrideUid(uid_t uid,
3194 String16 callingPackage, bool active) {
3195 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08003196}
3197
Svet Ganov7b4ab782018-03-25 12:48:10 -07003198void CameraService::UidPolicy::removeOverrideUid(uid_t uid, String16 callingPackage) {
3199 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08003200}
3201
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003202void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
3203 Mutex::Autolock _l(mUidLock);
3204 ALOGV("UidPolicy: ActivityManager has died");
3205 mRegistered = false;
3206 mActiveUids.clear();
3207}
3208
Svet Ganov7b4ab782018-03-25 12:48:10 -07003209void CameraService::UidPolicy::updateOverrideUid(uid_t uid, String16 callingPackage,
3210 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003211 bool wasActive = false;
3212 bool isActive = false;
3213 {
3214 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003215 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003216 mOverrideUids.erase(uid);
3217 if (insert) {
3218 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
3219 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003220 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003221 }
3222 if (wasActive != isActive && !isActive) {
3223 sp<CameraService> service = mService.promote();
3224 if (service != nullptr) {
3225 service->blockClientsForUid(uid);
3226 }
3227 }
3228}
3229
3230// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08003231// SensorPrivacyPolicy
3232// ----------------------------------------------------------------------------
3233void CameraService::SensorPrivacyPolicy::registerSelf() {
3234 Mutex::Autolock _l(mSensorPrivacyLock);
3235 if (mRegistered) {
3236 return;
3237 }
Steven Moreland3cf67172020-01-29 11:44:22 -08003238 mSpm.addSensorPrivacyListener(this);
3239 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
3240 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003241 if (res == OK) {
3242 mRegistered = true;
3243 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
3244 }
3245}
3246
3247void CameraService::SensorPrivacyPolicy::unregisterSelf() {
3248 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08003249 mSpm.removeSensorPrivacyListener(this);
3250 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003251 mRegistered = false;
3252 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
3253}
3254
3255bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
3256 Mutex::Autolock _l(mSensorPrivacyLock);
3257 return mSensorPrivacyEnabled;
3258}
3259
3260binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
3261 {
3262 Mutex::Autolock _l(mSensorPrivacyLock);
3263 mSensorPrivacyEnabled = enabled;
3264 }
3265 // if sensor privacy is enabled then block all clients from accessing the camera
3266 if (enabled) {
3267 sp<CameraService> service = mService.promote();
3268 if (service != nullptr) {
3269 service->blockAllClients();
3270 }
3271 }
3272 return binder::Status::ok();
3273}
3274
3275void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
3276 Mutex::Autolock _l(mSensorPrivacyLock);
3277 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
3278 mRegistered = false;
3279}
3280
3281// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003282// CameraState
3283// ----------------------------------------------------------------------------
3284
3285CameraService::CameraState::CameraState(const String8& id, int cost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003286 const std::set<String8>& conflicting, SystemCameraKind systemCameraKind) : mId(id),
3287 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
3288 mSystemCameraKind(systemCameraKind) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08003289
3290CameraService::CameraState::~CameraState() {}
3291
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003292CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003293 Mutex::Autolock lock(mStatusLock);
3294 return mStatus;
3295}
3296
Shuzhen Wang43858162020-01-10 13:42:15 -08003297std::vector<String8> CameraService::CameraState::getUnavailablePhysicalIds() const {
3298 Mutex::Autolock lock(mStatusLock);
3299 std::vector<String8> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
3300 return res;
3301}
3302
Ruben Brunkcc776712015-02-17 20:18:47 -08003303CameraParameters CameraService::CameraState::getShimParams() const {
3304 return mShimParams;
3305}
3306
3307void CameraService::CameraState::setShimParams(const CameraParameters& params) {
3308 mShimParams = params;
3309}
3310
3311int CameraService::CameraState::getCost() const {
3312 return mCost;
3313}
3314
3315std::set<String8> CameraService::CameraState::getConflicting() const {
3316 return mConflicting;
3317}
3318
3319String8 CameraService::CameraState::getId() const {
3320 return mId;
3321}
3322
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003323SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
3324 return mSystemCameraKind;
3325}
3326
Shuzhen Wang43858162020-01-10 13:42:15 -08003327bool CameraService::CameraState::addUnavailablePhysicalId(const String8& physicalId) {
3328 Mutex::Autolock lock(mStatusLock);
3329 auto result = mUnavailablePhysicalIds.insert(physicalId);
3330 return result.second;
3331}
3332
3333bool CameraService::CameraState::removeUnavailablePhysicalId(const String8& physicalId) {
3334 Mutex::Autolock lock(mStatusLock);
3335 auto count = mUnavailablePhysicalIds.erase(physicalId);
3336 return count > 0;
3337}
3338
Ruben Brunkcc776712015-02-17 20:18:47 -08003339// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07003340// ClientEventListener
3341// ----------------------------------------------------------------------------
3342
3343void CameraService::ClientEventListener::onClientAdded(
3344 const resource_policy::ClientDescriptor<String8,
3345 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003346 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003347 if (basicClient.get() != nullptr) {
3348 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3349 notifier.noteStartCamera(descriptor.getKey(),
3350 static_cast<int>(basicClient->getClientUid()));
3351 }
3352}
3353
3354void CameraService::ClientEventListener::onClientRemoved(
3355 const resource_policy::ClientDescriptor<String8,
3356 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003357 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003358 if (basicClient.get() != nullptr) {
3359 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3360 notifier.noteStopCamera(descriptor.getKey(),
3361 static_cast<int>(basicClient->getClientUid()));
3362 }
3363}
3364
3365
3366// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003367// CameraClientManager
3368// ----------------------------------------------------------------------------
3369
Ruben Brunk99e69712015-05-26 17:25:07 -07003370CameraService::CameraClientManager::CameraClientManager() {
3371 setListener(std::make_shared<ClientEventListener>());
3372}
3373
Ruben Brunkcc776712015-02-17 20:18:47 -08003374CameraService::CameraClientManager::~CameraClientManager() {}
3375
3376sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
3377 const String8& id) const {
3378 auto descriptor = get(id);
3379 if (descriptor == nullptr) {
3380 return sp<BasicClient>{nullptr};
3381 }
3382 return descriptor->getValue();
3383}
3384
3385String8 CameraService::CameraClientManager::toString() const {
3386 auto all = getAll();
3387 String8 ret("[");
3388 bool hasAny = false;
3389 for (auto& i : all) {
3390 hasAny = true;
3391 String8 key = i->getKey();
3392 int32_t cost = i->getCost();
3393 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00003394 int32_t score = i->getPriority().getScore();
3395 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08003396 auto conflicting = i->getConflicting();
3397 auto clientSp = i->getValue();
3398 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07003399 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08003400 if (clientSp.get() != nullptr) {
3401 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07003402 uid_t clientUid = clientSp->getClientUid();
3403 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003404 }
Emilian Peev8131a262017-02-01 12:33:43 +00003405 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
3406 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08003407
Ruben Brunk6267b532015-04-30 17:44:07 -07003408 if (clientSp.get() != nullptr) {
3409 ret.appendFormat("User Id: %d, ", clientUserId);
3410 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003411 if (packageName.size() != 0) {
3412 ret.appendFormat("Client Package Name: %s", packageName.string());
3413 }
3414
3415 ret.append(", Conflicting Client Devices: {");
3416 for (auto& j : conflicting) {
3417 ret.appendFormat("%s, ", j.string());
3418 }
3419 ret.append("})");
3420 }
3421 if (hasAny) ret.append("\n");
3422 ret.append("]\n");
3423 return ret;
3424}
3425
3426CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3427 const String8& key, const sp<BasicClient>& value, int32_t cost,
Emilian Peev8131a262017-02-01 12:33:43 +00003428 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
3429 int32_t state) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003430
Steven Moreland89a2c5c2020-01-31 15:02:25 -08003431 bool isVendorClient = getCurrentServingCall() == BinderCallType::HWBINDER;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003432 int32_t score_adj = isVendorClient ? kVendorClientScore : score;
3433 int32_t state_adj = isVendorClient ? kVendorClientState: state;
3434
Ruben Brunkcc776712015-02-17 20:18:47 -08003435 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003436 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj, isVendorClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08003437}
3438
3439CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3440 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
3441 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00003442 partial->getConflicting(), partial->getPriority().getScore(),
3443 partial->getOwnerId(), partial->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08003444}
3445
3446// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07003447
3448static const int kDumpLockRetries = 50;
3449static const int kDumpLockSleep = 60000;
3450
3451static bool tryLock(Mutex& mutex)
3452{
3453 bool locked = false;
3454 for (int i = 0; i < kDumpLockRetries; ++i) {
3455 if (mutex.tryLock() == NO_ERROR) {
3456 locked = true;
3457 break;
3458 }
3459 usleep(kDumpLockSleep);
3460 }
3461 return locked;
3462}
3463
3464status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003465 ATRACE_CALL();
3466
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003467 if (checkCallingPermission(sDumpPermission) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003468 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07003469 CameraThreadState::getCallingPid(),
3470 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003471 return NO_ERROR;
3472 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003473 bool locked = tryLock(mServiceLock);
3474 // failed to lock - CameraService is probably deadlocked
3475 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003476 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003477 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003478
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003479 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003480 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07003481
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003482 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003483 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08003484
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003485 if (locked) mServiceLock.unlock();
3486 return NO_ERROR;
3487 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003488 dprintf(fd, "\n== Service global info: ==\n\n");
3489 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003490 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07003491 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
3492 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003493 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
3494 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
3495 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003496 String8 activeClientString = mActiveClientManager.toString();
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003497 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
3498 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003499
3500 dumpEventLog(fd);
3501
3502 bool stateLocked = tryLock(mCameraStatesLock);
3503 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003504 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003505 }
3506
Emilian Peevbd8c5032018-02-14 23:05:40 +00003507 int argSize = args.size();
3508 for (int i = 0; i < argSize; i++) {
3509 if (args[i] == TagMonitor::kMonitorOption) {
3510 if (i + 1 < argSize) {
3511 mMonitorTags = String8(args[i + 1]);
3512 }
3513 break;
3514 }
3515 }
3516
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003517 for (auto& state : mCameraStates) {
3518 String8 cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003519
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003520 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003521
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003522 CameraParameters p = state.second->getShimParams();
3523 if (!p.isEmpty()) {
3524 dprintf(fd, " Camera1 API shim is using parameters:\n ");
3525 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003526 }
3527
3528 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08003529 if (clientDescriptor != nullptr) {
3530 dprintf(fd, " Device %s is open. Client instance dump:\n",
3531 cameraId.string());
3532 dprintf(fd, " Client priority score: %d state: %d\n",
3533 clientDescriptor->getPriority().getScore(),
3534 clientDescriptor->getPriority().getState());
3535 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
3536
3537 auto client = clientDescriptor->getValue();
3538 dprintf(fd, " Client package: %s\n",
3539 String8(client->getPackageName()).string());
3540
3541 client->dumpClient(fd, args);
3542 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003543 dprintf(fd, " Device %s is closed, no client instance\n",
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003544 cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003545 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003546
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003547 }
3548
3549 if (stateLocked) mCameraStatesLock.unlock();
3550
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003551 if (locked) mServiceLock.unlock();
3552
Emilian Peevf53f66e2017-04-11 14:29:43 +01003553 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003554
3555 dprintf(fd, "\n== Vendor tags: ==\n\n");
3556
3557 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
3558 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00003559 sp<VendorTagDescriptorCache> cache =
3560 VendorTagDescriptorCache::getGlobalVendorTagCache();
3561 if (cache == NULL) {
3562 dprintf(fd, "No vendor tags.\n");
3563 } else {
3564 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
3565 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003566 } else {
3567 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
3568 }
3569
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003570 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003571 dprintf(fd, "\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003572 camera3::CameraTraces::dump(fd, args);
3573
3574 // Process dump arguments, if any
3575 int n = args.size();
3576 String16 verboseOption("-v");
3577 String16 unreachableOption("--unreachable");
3578 for (int i = 0; i < n; i++) {
3579 if (args[i] == verboseOption) {
3580 // change logging level
3581 if (i + 1 >= n) continue;
3582 String8 levelStr(args[i+1]);
3583 int level = atoi(levelStr.string());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003584 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003585 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003586 } else if (args[i] == unreachableOption) {
3587 // Dump memory analysis
3588 // TODO - should limit be an argument parameter?
3589 UnreachableMemoryInfo info;
3590 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
3591 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003592 dprintf(fd, "\n== Unable to dump unreachable memory. "
3593 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003594 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003595 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003596 std::string s = info.ToString(/*log_contents*/ true);
3597 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003598 }
3599 }
3600 }
3601 return NO_ERROR;
3602}
3603
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003604void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003605 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003606
3607 Mutex::Autolock l(mLogLock);
3608 for (const auto& msg : mEventLog) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003609 dprintf(fd, " %s\n", msg.string());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003610 }
3611
3612 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003613 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003614 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003615 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003616 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003617 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003618}
3619
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003620void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003621 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003622 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
3623 if (mTorchClientMap[i] == who) {
3624 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003625 String8 cameraId = mTorchClientMap.keyAt(i);
3626 status_t res = mFlashlight->setTorchMode(cameraId, false);
3627 if (res) {
3628 ALOGE("%s: torch client died but couldn't turn off torch: "
3629 "%s (%d)", __FUNCTION__, strerror(-res), res);
3630 return;
3631 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003632 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003633 break;
3634 }
3635 }
3636}
3637
Ruben Brunkcc776712015-02-17 20:18:47 -08003638/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003639
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003640 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07003641 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
3642 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003643 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003644 // PID here is approximate and can be wrong.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003645 logClientDied(CameraThreadState::getCallingPid(), String8("Binder died unexpectedly"));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003646
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003647 // check torch client
3648 handleTorchClientBinderDied(who);
3649
3650 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08003651 if(!evictClientIdByRemote(who)) {
3652 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003653 return;
3654 }
3655
Ruben Brunkcc776712015-02-17 20:18:47 -08003656 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
3657 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003658}
3659
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003660void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003661 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08003662}
3663
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003664void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
3665 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003666 // Do not lock mServiceLock here or can get into a deadlock from
3667 // connect() -> disconnect -> updateStatus
3668
3669 auto state = getCameraState(cameraId);
3670
3671 if (state == nullptr) {
3672 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
3673 cameraId.string());
3674 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07003675 }
3676
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003677 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
3678 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3679 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3680 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
3681 return;
3682 }
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003683 bool supportsHAL3 = false;
3684 // supportsCameraApi also holds mInterfaceMutex, we can't call it in the
3685 // HIDL onStatusChanged wrapper call (we'll hold mStatusListenerLock and
3686 // mInterfaceMutex together, which can lead to deadlocks)
3687 binder::Status sRet =
3688 supportsCameraApi(String16(cameraId), hardware::ICameraService::API_VERSION_2,
3689 &supportsHAL3);
3690 if (!sRet.isOk()) {
3691 ALOGW("%s: Failed to determine if device supports HAL3 %s, supportsCameraApi call failed",
3692 __FUNCTION__, cameraId.string());
3693 return;
3694 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003695
3696 // Collect the logical cameras without holding mStatusLock in updateStatus
3697 // as that can lead to a deadlock(b/162192331).
3698 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08003699 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08003700 // of the listeners with both the mStatusLock and mStatusListenerLock held
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003701 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind, &supportsHAL3,
3702 &logicalCameraIds]
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003703 (const String8& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003704
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003705 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003706 // Update torch status if it has a flash unit.
3707 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003708 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003709 if (getTorchStatusLocked(cameraId, &torchStatus) !=
3710 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003711 TorchModeStatus newTorchStatus =
3712 status == StatusInternal::PRESENT ?
3713 TorchModeStatus::AVAILABLE_OFF :
3714 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003715 if (torchStatus != newTorchStatus) {
3716 onTorchStatusChangedLocked(cameraId, newTorchStatus);
3717 }
3718 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003719 }
3720
3721 Mutex::Autolock lock(mStatusListenerLock);
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003722 notifyPhysicalCameraStatusLocked(mapToInterface(status), String16(cameraId),
3723 logicalCameraIds, deviceKind);
Shuzhen Wang43858162020-01-10 13:42:15 -08003724
Ruben Brunkcc776712015-02-17 20:18:47 -08003725 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003726 bool isVendorListener = listener->isVendorListener();
3727 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
3728 listener->getListenerPid(), listener->getListenerUid()) ||
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07003729 (isVendorListener && !supportsHAL3)) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003730 ALOGV("Skipping discovery callback for system-only camera/HAL1 device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003731 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003732 continue;
3733 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003734 listener->getListener()->onStatusChanged(mapToInterface(status),
Emilian Peev53722fa2019-02-22 17:47:20 -08003735 String16(cameraId));
Ruben Brunkcc776712015-02-17 20:18:47 -08003736 }
3737 });
Igor Murashkincba2c162013-03-20 15:56:31 -07003738}
3739
Shuzhen Wang695044d2020-03-06 09:02:23 -08003740void CameraService::updateOpenCloseStatus(const String8& cameraId, bool open,
3741 const String16& clientPackageName) {
3742 Mutex::Autolock lock(mStatusListenerLock);
3743
3744 for (const auto& it : mListenerList) {
3745 if (!it->isOpenCloseCallbackAllowed()) {
3746 continue;
3747 }
3748
3749 binder::Status ret;
3750 String16 cameraId64(cameraId);
3751 if (open) {
3752 ret = it->getListener()->onCameraOpened(cameraId64, clientPackageName);
3753 } else {
3754 ret = it->getListener()->onCameraClosed(cameraId64);
3755 }
3756 if (!ret.isOk()) {
3757 ALOGE("%s: Failed to trigger onCameraOpened/onCameraClosed callback: %d", __FUNCTION__,
3758 ret.exceptionCode());
3759 }
3760 }
3761}
3762
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003763template<class Func>
3764void CameraService::CameraState::updateStatus(StatusInternal status,
3765 const String8& cameraId,
3766 std::initializer_list<StatusInternal> rejectSourceStates,
3767 Func onStatusUpdatedLocked) {
3768 Mutex::Autolock lock(mStatusLock);
3769 StatusInternal oldStatus = mStatus;
3770 mStatus = status;
3771
3772 if (oldStatus == status) {
3773 return;
3774 }
3775
3776 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
3777 cameraId.string(), oldStatus, status);
3778
3779 if (oldStatus == StatusInternal::NOT_PRESENT &&
3780 (status != StatusInternal::PRESENT &&
3781 status != StatusInternal::ENUMERATING)) {
3782
3783 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
3784 __FUNCTION__);
3785 mStatus = oldStatus;
3786 return;
3787 }
3788
3789 /**
3790 * Sometimes we want to conditionally do a transition.
3791 * For example if a client disconnects, we want to go to PRESENT
3792 * only if we weren't already in NOT_PRESENT or ENUMERATING.
3793 */
3794 for (auto& rejectStatus : rejectSourceStates) {
3795 if (oldStatus == rejectStatus) {
3796 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
3797 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
3798 mStatus = oldStatus;
3799 return;
3800 }
3801 }
3802
3803 onStatusUpdatedLocked(cameraId, status);
3804}
3805
Eino-Ville Talvalae8c96c72017-06-27 12:24:07 -07003806void CameraService::updateProxyDeviceState(int newState,
Emilian Peev573291c2018-02-10 02:10:56 +00003807 const String8& cameraId, int facing, const String16& clientName, int apiLevel) {
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07003808 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
3809 if (proxyBinder == nullptr) return;
3810 String16 id(cameraId);
Emilian Peev573291c2018-02-10 02:10:56 +00003811 proxyBinder->notifyCameraState(id, newState, facing, clientName, apiLevel);
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07003812}
3813
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003814status_t CameraService::getTorchStatusLocked(
3815 const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003816 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003817 if (!status) {
3818 return BAD_VALUE;
3819 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003820 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3821 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003822 // invalid camera ID or the camera doesn't have a flash unit
3823 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003824 }
3825
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003826 *status = mTorchStatusMap.valueAt(index);
3827 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003828}
3829
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003830status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003831 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003832 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3833 if (index == NAME_NOT_FOUND) {
3834 return BAD_VALUE;
3835 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003836 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003837
3838 return OK;
3839}
3840
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003841std::list<String16> CameraService::getLogicalCameras(
3842 const String8& physicalCameraId) {
3843 std::list<String16> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08003844 Mutex::Autolock lock(mCameraStatesLock);
3845 for (const auto& state : mCameraStates) {
3846 std::vector<std::string> physicalCameraIds;
3847 if (!mCameraProviderManager->isLogicalCamera(state.first.c_str(), &physicalCameraIds)) {
3848 // This is not a logical multi-camera.
3849 continue;
3850 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003851 if (std::find(physicalCameraIds.begin(), physicalCameraIds.end(), physicalCameraId.c_str())
Shuzhen Wang43858162020-01-10 13:42:15 -08003852 == physicalCameraIds.end()) {
3853 // cameraId is not a physical camera of this logical multi-camera.
3854 continue;
3855 }
3856
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003857 retList.emplace_back(String16(state.first));
3858 }
3859 return retList;
3860}
3861
3862void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
3863 const String16& physicalCameraId, const std::list<String16>& logicalCameraIds,
3864 SystemCameraKind deviceKind) {
3865 // mStatusListenerLock is expected to be locked
3866 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08003867 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003868 // Note: we check only the deviceKind of the physical camera id
3869 // since, logical camera ids and their physical camera ids are
3870 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07003871 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
3872 listener->getListenerPid(), listener->getListenerUid())) {
3873 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003874 String8(physicalCameraId).c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07003875 continue;
3876 }
Shuzhen Wang43858162020-01-10 13:42:15 -08003877 listener->getListener()->onPhysicalCameraStatusChanged(status,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003878 logicalCameraId, physicalCameraId);
Shuzhen Wang43858162020-01-10 13:42:15 -08003879 }
3880 }
3881}
3882
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003883
Svet Ganova453d0d2018-01-11 15:37:58 -08003884void CameraService::blockClientsForUid(uid_t uid) {
3885 const auto clients = mActiveClientManager.getAll();
3886 for (auto& current : clients) {
3887 if (current != nullptr) {
3888 const auto basicClient = current->getValue();
3889 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
3890 basicClient->block();
3891 }
3892 }
3893 }
3894}
3895
Michael Grooverd1d435a2018-12-18 17:39:42 -08003896void CameraService::blockAllClients() {
3897 const auto clients = mActiveClientManager.getAll();
3898 for (auto& current : clients) {
3899 if (current != nullptr) {
3900 const auto basicClient = current->getValue();
3901 if (basicClient.get() != nullptr) {
3902 basicClient->block();
3903 }
3904 }
3905 }
3906}
3907
Svet Ganova453d0d2018-01-11 15:37:58 -08003908// NOTE: This is a remote API - make sure all args are validated
3909status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
3910 if (!checkCallingPermission(sManageCameraPermission, nullptr, nullptr)) {
3911 return PERMISSION_DENIED;
3912 }
3913 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
3914 return BAD_VALUE;
3915 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003916 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003917 return handleSetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07003918 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003919 return handleResetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07003920 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003921 return handleGetUidState(args, out, err);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003922 } else if (args.size() >= 2 && args[0] == String16("set-rotate-and-crop")) {
3923 return handleSetRotateAndCrop(args);
3924 } else if (args.size() >= 1 && args[0] == String16("get-rotate-and-crop")) {
3925 return handleGetRotateAndCrop(out);
Svet Ganova453d0d2018-01-11 15:37:58 -08003926 } else if (args.size() == 1 && args[0] == String16("help")) {
3927 printHelp(out);
3928 return NO_ERROR;
3929 }
3930 printHelp(err);
3931 return BAD_VALUE;
3932}
3933
3934status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07003935 String16 packageName = args[1];
3936
Svet Ganova453d0d2018-01-11 15:37:58 -08003937 bool active = false;
3938 if (args[2] == String16("active")) {
3939 active = true;
3940 } else if ((args[2] != String16("idle"))) {
3941 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
3942 return BAD_VALUE;
3943 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003944
3945 int userId = 0;
3946 if (args.size() >= 5 && args[3] == String16("--user")) {
3947 userId = atoi(String8(args[4]));
3948 }
3949
3950 uid_t uid;
3951 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
3952 return BAD_VALUE;
3953 }
3954
3955 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08003956 return NO_ERROR;
3957}
3958
3959status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07003960 String16 packageName = args[1];
3961
3962 int userId = 0;
3963 if (args.size() >= 4 && args[2] == String16("--user")) {
3964 userId = atoi(String8(args[3]));
3965 }
3966
3967 uid_t uid;
3968 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003969 return BAD_VALUE;
3970 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003971
3972 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08003973 return NO_ERROR;
3974}
3975
3976status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07003977 String16 packageName = args[1];
3978
3979 int userId = 0;
3980 if (args.size() >= 4 && args[2] == String16("--user")) {
3981 userId = atoi(String8(args[3]));
3982 }
3983
3984 uid_t uid;
3985 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003986 return BAD_VALUE;
3987 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003988
3989 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003990 return dprintf(out, "active\n");
3991 } else {
3992 return dprintf(out, "idle\n");
3993 }
3994}
3995
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003996status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
3997 int rotateValue = atoi(String8(args[1]));
3998 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
3999 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
4000 Mutex::Autolock lock(mServiceLock);
4001
4002 mOverrideRotateAndCropMode = rotateValue;
4003
4004 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
4005
4006 const auto clients = mActiveClientManager.getAll();
4007 for (auto& current : clients) {
4008 if (current != nullptr) {
4009 const auto basicClient = current->getValue();
4010 if (basicClient.get() != nullptr) {
4011 basicClient->setRotateAndCropOverride(rotateValue);
4012 }
4013 }
4014 }
4015
4016 return OK;
4017}
4018
4019status_t CameraService::handleGetRotateAndCrop(int out) {
4020 Mutex::Autolock lock(mServiceLock);
4021
4022 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
4023}
4024
Svet Ganova453d0d2018-01-11 15:37:58 -08004025status_t CameraService::printHelp(int out) {
4026 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07004027 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
4028 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
4029 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004030 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
4031 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
4032 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08004033 " help print this message\n");
4034}
4035
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004036int32_t CameraService::updateAudioRestriction() {
4037 Mutex::Autolock lock(mServiceLock);
4038 return updateAudioRestrictionLocked();
4039}
4040
4041int32_t CameraService::updateAudioRestrictionLocked() {
4042 int32_t mode = 0;
4043 // iterate through all active client
4044 for (const auto& i : mActiveClientManager.getAll()) {
4045 const auto clientSp = i->getValue();
4046 mode |= clientSp->getAudioRestriction();
4047 }
4048
4049 bool modeChanged = (mAudioRestriction != mode);
4050 mAudioRestriction = mode;
4051 if (modeChanged) {
4052 mAppOps.setCameraAudioRestriction(mode);
4053 }
4054 return mode;
4055}
4056
Mathias Agopian65ab4712010-07-14 17:59:35 -07004057}; // namespace android