blob: daa1edbdd0938913cf0c836ca207229de5feb46f [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/CameraClient.h"
74#include "api1/Camera2Client.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070075#include "api2/CameraDeviceClient.h"
Igor Murashkinff3e31d2013-10-23 16:40:06 -070076#include "utils/CameraTraces.h"
Emilian Peevbd8c5032018-02-14 23:05:40 +000077#include "utils/TagMonitor.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070078#include "utils/CameraThreadState.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070079
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080080namespace {
81 const char* kPermissionServiceName = "permission";
82}; // namespace anonymous
83
Mathias Agopian65ab4712010-07-14 17:59:35 -070084namespace android {
85
Jayant Chowdharyb61526c2019-05-13 19:37:42 -070086using base::StringPrintf;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080087using binder::Status;
Jayant Chowdharybe543d42018-08-15 13:16:14 -070088using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -080089using hardware::ICamera;
90using hardware::ICameraClient;
Eino-Ville Talvalae8c96c72017-06-27 12:24:07 -070091using hardware::ICameraServiceProxy;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -080092using hardware::ICameraServiceListener;
93using hardware::camera::common::V1_0::CameraDeviceStatus;
94using hardware::camera::common::V1_0::TorchModeStatus;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080095using hardware::camera2::utils::CameraIdAndSessionConfiguration;
96using hardware::camera2::utils::ConcurrentCameraIdCombination;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080097
Mathias Agopian65ab4712010-07-14 17:59:35 -070098// ----------------------------------------------------------------------------
99// Logging support -- this is for debugging only
100// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700101volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700102
Steve Blockb8a80522011-12-20 16:23:08 +0000103#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
104#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700105
106static void setLogLevel(int level) {
107 android_atomic_write(level, &gLogLevel);
108}
109
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800110// Convenience methods for constructing binder::Status objects for error returns
111
112#define STATUS_ERROR(errorCode, errorString) \
113 binder::Status::fromServiceSpecificError(errorCode, \
114 String8::format("%s:%d: %s", __FUNCTION__, __LINE__, errorString))
115
116#define STATUS_ERROR_FMT(errorCode, errorString, ...) \
117 binder::Status::fromServiceSpecificError(errorCode, \
118 String8::format("%s:%d: " errorString, __FUNCTION__, __LINE__, \
119 __VA_ARGS__))
120
Mathias Agopian65ab4712010-07-14 17:59:35 -0700121// ----------------------------------------------------------------------------
122
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700123static const String16 sDumpPermission("android.permission.DUMP");
Svet Ganova453d0d2018-01-11 15:37:58 -0800124static const String16 sManageCameraPermission("android.permission.MANAGE_CAMERA");
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700125static const String16 sCameraPermission("android.permission.CAMERA");
126static const String16 sSystemCameraPermission("android.permission.SYSTEM_CAMERA");
127static const String16
128 sCameraSendSystemEventsPermission("android.permission.CAMERA_SEND_SYSTEM_EVENTS");
Shuzhen Wang695044d2020-03-06 09:02:23 -0800129static const String16 sCameraOpenCloseListenerPermission(
130 "android.permission.CAMERA_OPEN_CLOSE_LISTENER");
Svet Ganova453d0d2018-01-11 15:37:58 -0800131
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700132// Matches with PERCEPTIBLE_APP_ADJ in ProcessList.java
133static constexpr int32_t kVendorClientScore = 200;
134// Matches with PROCESS_STATE_PERSISTENT_UI in ActivityManager.java
135static constexpr int32_t kVendorClientState = 1;
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800136const String8 CameraService::kOfflineDevice("offline-");
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700137
Eino-Ville Talvala7d5569f2019-04-08 13:57:54 -0700138Mutex CameraService::sProxyMutex;
139sp<hardware::ICameraServiceProxy> CameraService::sCameraServiceProxy;
140
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800141CameraService::CameraService() :
142 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800143 mNumberOfCameras(0),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700144 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700145 mSoundRef(0), mInitialized(false),
146 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000147 ALOGI("CameraService started (pid=%d)", getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800148 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700149}
150
Iliyan Malchev8951a972011-04-14 16:55:59 -0700151void CameraService::onFirstRef()
152{
Ruben Brunkcc776712015-02-17 20:18:47 -0800153 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800154
Iliyan Malchev8951a972011-04-14 16:55:59 -0700155 BnCameraService::onFirstRef();
156
Ruben Brunk99e69712015-05-26 17:25:07 -0700157 // Update battery life tracking if service is restarting
158 BatteryNotifier& notifier(BatteryNotifier::getInstance());
159 notifier.noteResetCamera();
160 notifier.noteResetFlashlight();
161
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800162 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800163
Emilian Peevf53f66e2017-04-11 14:29:43 +0100164 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800165 if (res == OK) {
166 mInitialized = true;
167 }
168
Svet Ganova453d0d2018-01-11 15:37:58 -0800169 mUidPolicy = new UidPolicy(this);
170 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800171 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
172 mSensorPrivacyPolicy->registerSelf();
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700173 mAppOps.setCameraAudioRestriction(mAudioRestriction);
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700174 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
175 if (hcs->registerAsService() != android::OK) {
176 ALOGE("%s: Failed to register default android.frameworks.cameraservice.service@1.0",
177 __FUNCTION__);
178 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700179
180 // This needs to be last call in this function, so that it's as close to
181 // ServiceManager::addService() as possible.
182 CameraService::pingCameraServiceProxy();
183 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800184}
185
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800186status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800187 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100188
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800189 std::vector<std::string> deviceIds;
190 {
191 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800192
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800193 if (nullptr == mCameraProviderManager.get()) {
194 mCameraProviderManager = new CameraProviderManager();
195 res = mCameraProviderManager->initialize(this);
196 if (res != OK) {
197 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
198 __FUNCTION__, strerror(-res), res);
199 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100200 }
201 }
202
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800203
204 // Setup vendor tags before we call get_camera_info the first time
205 // because HAL might need to setup static vendor keys in get_camera_info
206 // TODO: maybe put this into CameraProviderManager::initialize()?
207 mCameraProviderManager->setUpVendorTags();
208
209 if (nullptr == mFlashlight.get()) {
210 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700211 }
212
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800213 res = mFlashlight->findFlashUnits();
214 if (res != OK) {
215 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
216 }
217
218 deviceIds = mCameraProviderManager->getCameraDeviceIds();
219 }
220
221
222 for (auto& cameraId : deviceIds) {
223 String8 id8 = String8(cameraId.c_str());
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800224 if (getCameraState(id8) == nullptr) {
225 onDeviceStatusChanged(id8, CameraDeviceStatus::PRESENT);
226 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800227 }
228
229 return OK;
230}
231
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700232sp<ICameraServiceProxy> CameraService::getCameraServiceProxy() {
Christopher Wiley92c06fc2016-02-11 15:40:05 -0800233#ifndef __BRILLO__
Eino-Ville Talvala7d5569f2019-04-08 13:57:54 -0700234 Mutex::Autolock al(sProxyMutex);
235 if (sCameraServiceProxy == nullptr) {
236 sp<IServiceManager> sm = defaultServiceManager();
237 // Use checkService because cameraserver normally starts before the
238 // system server and the proxy service. So the long timeout that getService
239 // has before giving up is inappropriate.
240 sp<IBinder> binder = sm->checkService(String16("media.camera.proxy"));
241 if (binder != nullptr) {
242 sCameraServiceProxy = interface_cast<ICameraServiceProxy>(binder);
243 }
Ruben Brunk2823ce02015-05-19 17:25:13 -0700244 }
Christopher Wiley92c06fc2016-02-11 15:40:05 -0800245#endif
Eino-Ville Talvala7d5569f2019-04-08 13:57:54 -0700246 return sCameraServiceProxy;
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700247}
248
249void CameraService::pingCameraServiceProxy() {
250 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
251 if (proxyBinder == nullptr) return;
Ruben Brunk2823ce02015-05-19 17:25:13 -0700252 proxyBinder->pingForUserUpdate();
Iliyan Malchev8951a972011-04-14 16:55:59 -0700253}
254
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800255void CameraService::broadcastTorchModeStatus(const String8& cameraId, TorchModeStatus status) {
256 Mutex::Autolock lock(mStatusListenerLock);
257
258 for (auto& i : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700259 i->getListener()->onTorchStatusChanged(mapToInterface(status), String16{cameraId});
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800260 }
261}
262
Mathias Agopian65ab4712010-07-14 17:59:35 -0700263CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800264 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800265 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800266 mSensorPrivacyPolicy->unregisterSelf();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700267}
268
Emilian Peevaee727d2017-05-04 16:35:48 +0100269void CameraService::onNewProviderRegistered() {
270 enumerateProviders();
271}
272
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700273void CameraService::filterAPI1SystemCameraLocked(
274 const std::vector<std::string> &normalDeviceIds) {
275 mNormalDeviceIdsWithoutSystemCamera.clear();
276 for (auto &deviceId : normalDeviceIds) {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700277 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
278 if (getSystemCameraKind(String8(deviceId.c_str()), &deviceKind) != OK) {
279 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, deviceId.c_str());
280 continue;
281 }
282 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700283 // All system camera ids will necessarily come after public camera
284 // device ids as per the HAL interface contract.
285 break;
286 }
287 mNormalDeviceIdsWithoutSystemCamera.push_back(deviceId);
288 }
289 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
290 mNormalDeviceIdsWithoutSystemCamera.size());
291}
292
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700293status_t CameraService::getSystemCameraKind(const String8& cameraId, SystemCameraKind *kind) const {
294 auto state = getCameraState(cameraId);
295 if (state != nullptr) {
296 *kind = state->getSystemCameraKind();
297 return OK;
298 }
299 // Hidden physical camera ids won't have CameraState
300 return mCameraProviderManager->getSystemCameraKind(cameraId.c_str(), kind);
301}
302
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800303void CameraService::updateCameraNumAndIds() {
304 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700305 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
306 // Excludes hidden secure cameras
307 mNumberOfCameras =
308 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
309 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800310 mNormalDeviceIds =
311 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700312 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800313}
314
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100315void CameraService::addStates(const String8 id) {
316 std::string cameraId(id.c_str());
317 hardware::camera::common::V1_0::CameraResourceCost cost;
318 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700319 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100320 if (res != OK) {
321 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
322 return;
323 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700324 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
325 if (res != OK) {
326 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
327 return;
328 }
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100329 std::set<String8> conflicting;
330 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
331 conflicting.emplace(String8(cost.conflictingDevices[i].c_str()));
332 }
333
334 {
335 Mutex::Autolock lock(mCameraStatesLock);
336 mCameraStates.emplace(id, std::make_shared<CameraState>(id, cost.resourceCost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700337 conflicting, deviceKind));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100338 }
339
340 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100341 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100342 mTorchStatusMap.add(id, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800343
344 broadcastTorchModeStatus(id, TorchModeStatus::AVAILABLE_OFF);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100345 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800346
347 updateCameraNumAndIds();
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100348 logDeviceAdded(id, "Device added");
349}
350
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100351void CameraService::removeStates(const String8 id) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800352 updateCameraNumAndIds();
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100353 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100354 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100355 mTorchStatusMap.removeItem(id);
356 }
357
358 {
359 Mutex::Autolock lock(mCameraStatesLock);
360 mCameraStates.erase(id);
361 }
362}
363
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800364void CameraService::onDeviceStatusChanged(const String8& id,
365 CameraDeviceStatus newHalStatus) {
366 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
367 id.string(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700368
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800369 StatusInternal newStatus = mapToInternal(newHalStatus);
370
Ruben Brunkcc776712015-02-17 20:18:47 -0800371 std::shared_ptr<CameraState> state = getCameraState(id);
372
373 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700374 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100375 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700376 __FUNCTION__, id.string());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100377
378 // First add as absent to make sure clients are notified below
379 addStates(id);
380
381 updateStatus(newStatus, id);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700382 } else {
383 ALOGE("%s: Bad camera ID %s", __FUNCTION__, id.string());
384 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700385 return;
386 }
387
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800388 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800389
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800390 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800391 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700392 return;
393 }
394
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800395 if (newStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700396 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
397 newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800398
399 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
400 // to this device until the status changes
401 updateStatus(StatusInternal::NOT_PRESENT, id);
402
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800403 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700404 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800405 // Don't do this in updateStatus to avoid deadlock over mServiceLock
406 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700407
Ruben Brunkcc776712015-02-17 20:18:47 -0800408 // Remove cached shim parameters
409 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700410
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800411 // Remove online as well as offline client from the list of active clients,
412 // if they are present
413 clientToDisconnectOnline = removeClientLocked(id);
414 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + id);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700415 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800416
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800417 disconnectClient(id, clientToDisconnectOnline);
418 disconnectClient(kOfflineDevice + id, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700419
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100420 removeStates(id);
Ruben Brunkcc776712015-02-17 20:18:47 -0800421 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800422 if (oldStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700423 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
424 newStatus));
425 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800426 updateStatus(newStatus, id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700427 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800428}
Igor Murashkincba2c162013-03-20 15:56:31 -0700429
Shuzhen Wang43858162020-01-10 13:42:15 -0800430void CameraService::onDeviceStatusChanged(const String8& id,
431 const String8& physicalId,
432 CameraDeviceStatus newHalStatus) {
433 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
434 __FUNCTION__, id.string(), physicalId.string(), newHalStatus);
435
436 StatusInternal newStatus = mapToInternal(newHalStatus);
437
438 std::shared_ptr<CameraState> state = getCameraState(id);
439
440 if (state == nullptr) {
441 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
442 __FUNCTION__, id.string(), physicalId.string());
443 return;
444 }
445
446 StatusInternal logicalCameraStatus = state->getStatus();
447 if (logicalCameraStatus != StatusInternal::PRESENT &&
448 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
449 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
450 __FUNCTION__, physicalId.string(), newHalStatus, logicalCameraStatus);
451 return;
452 }
453
454 bool updated = false;
455 if (newStatus == StatusInternal::PRESENT) {
456 updated = state->removeUnavailablePhysicalId(physicalId);
457 } else {
458 updated = state->addUnavailablePhysicalId(physicalId);
459 }
460
461 if (updated) {
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800462 String8 idCombo = id + " : " + physicalId;
463 if (newStatus == StatusInternal::PRESENT) {
464 logDeviceAdded(idCombo,
465 String8::format("Device status changed to %d", newStatus));
466 } else {
467 logDeviceRemoved(idCombo,
468 String8::format("Device status changed to %d", newStatus));
469 }
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700470 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
471 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
472 if (getSystemCameraKind(id, &deviceKind) != OK) {
473 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.string());
474 return;
475 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800476 String16 id16(id), physicalId16(physicalId);
477 Mutex::Autolock lock(mStatusListenerLock);
478 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700479 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
480 listener->getListenerPid(), listener->getListenerUid())) {
481 ALOGV("Skipping discovery callback for system-only camera device %s",
482 id.c_str());
483 continue;
484 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800485 listener->getListener()->onPhysicalCameraStatusChanged(mapToInterface(newStatus),
486 id16, physicalId16);
487 }
488 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700489}
490
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800491void CameraService::disconnectClient(const String8& id, sp<BasicClient> clientToDisconnect) {
492 if (clientToDisconnect.get() != nullptr) {
493 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
494 __FUNCTION__, id.string());
495 // Notify the client of disconnection
496 clientToDisconnect->notifyError(
497 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
498 CaptureResultExtras{});
499 // Ensure not in binder RPC so client disconnect PID checks work correctly
500 LOG_ALWAYS_FATAL_IF(CameraThreadState::getCallingPid() != getpid(),
501 "onDeviceStatusChanged must be called from the camera service process!");
502 clientToDisconnect->disconnect();
503 }
504}
505
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800506void CameraService::onTorchStatusChanged(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800507 TorchModeStatus newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800508 Mutex::Autolock al(mTorchStatusMutex);
509 onTorchStatusChangedLocked(cameraId, newStatus);
510}
511
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800512void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800513 TorchModeStatus newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800514 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
515 __FUNCTION__, cameraId.string(), newStatus);
516
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800517 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800518 status_t res = getTorchStatusLocked(cameraId, &status);
519 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700520 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
521 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800522 return;
523 }
524 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800525 return;
526 }
527
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800528 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800529 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800530 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
531 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800532 return;
533 }
534
Ruben Brunkcc776712015-02-17 20:18:47 -0800535 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700536 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700537 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700538 auto iter = mTorchUidMap.find(cameraId);
539 if (iter != mTorchUidMap.end()) {
540 int oldUid = iter->second.second;
541 int newUid = iter->second.first;
542 BatteryNotifier& notifier(BatteryNotifier::getInstance());
543 if (oldUid != newUid) {
544 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800545 if (status == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700546 notifier.noteFlashlightOff(cameraId, oldUid);
547 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800548 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700549 notifier.noteFlashlightOn(cameraId, newUid);
550 }
551 iter->second.second = newUid;
552 } else {
553 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800554 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700555 notifier.noteFlashlightOn(cameraId, oldUid);
556 } else {
557 notifier.noteFlashlightOff(cameraId, oldUid);
558 }
559 }
560 }
561 }
562
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800563 broadcastTorchModeStatus(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800564}
565
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700566static bool hasPermissionsForSystemCamera(int callingPid, int callingUid) {
567 return checkPermission(sSystemCameraPermission, callingPid, callingUid) &&
568 checkPermission(sCameraPermission, callingPid, callingUid);
569}
570
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800571Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700572 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100573 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700574 bool hasSystemCameraPermissions =
575 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
576 CameraThreadState::getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700577 switch (type) {
578 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700579 if (hasSystemCameraPermissions) {
580 *numCameras = static_cast<int>(mNormalDeviceIds.size());
581 } else {
582 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
583 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800584 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700585 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700586 if (hasSystemCameraPermissions) {
587 *numCameras = mNumberOfCameras;
588 } else {
589 *numCameras = mNumberOfCamerasWithoutSystemCamera;
590 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800591 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700592 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800593 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700594 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800595 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
596 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700597 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800598 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700599}
600
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800601Status CameraService::getCameraInfo(int cameraId,
602 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700603 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100604 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700605 std::string cameraIdStr = cameraIdIntToStrLocked(cameraId);
606 if (shouldRejectSystemCameraConnection(String8(cameraIdStr.c_str()))) {
607 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
608 "characteristics for system only device %s: ", cameraIdStr.c_str());
609 }
Emilian Peevaee727d2017-05-04 16:35:48 +0100610
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800611 if (!mInitialized) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800612 return STATUS_ERROR(ERROR_DISCONNECTED,
613 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -0700614 }
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700615 bool hasSystemCameraPermissions =
616 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
617 CameraThreadState::getCallingUid());
618 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
619 if (hasSystemCameraPermissions) {
620 cameraIdBound = mNumberOfCameras;
621 }
622 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800623 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
624 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700625 }
626
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800627 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800628 status_t err = mCameraProviderManager->getCameraInfo(
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700629 cameraIdStr.c_str(), cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100630 if (err != OK) {
631 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
632 "Error retrieving camera info from device %d: %s (%d)", cameraId,
633 strerror(-err), err);
Ruben Brunkcc776712015-02-17 20:18:47 -0800634 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100635
Ruben Brunkcc776712015-02-17 20:18:47 -0800636 return ret;
637}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700638
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800639std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700640 const std::vector<std::string> *deviceIds = &mNormalDeviceIdsWithoutSystemCamera;
641 auto callingPid = CameraThreadState::getCallingPid();
642 auto callingUid = CameraThreadState::getCallingUid();
643 if (checkPermission(sSystemCameraPermission, callingPid, callingUid) ||
644 getpid() == callingPid) {
645 deviceIds = &mNormalDeviceIds;
646 }
647 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(deviceIds->size())) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800648 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700649 __FUNCTION__, cameraIdInt, deviceIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800650 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800651 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800652
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700653 return (*deviceIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800654}
655
656String8 CameraService::cameraIdIntToStr(int cameraIdInt) {
657 Mutex::Autolock lock(mServiceLock);
658 return String8(cameraIdIntToStrLocked(cameraIdInt).c_str());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800659}
660
661Status CameraService::getCameraCharacteristics(const String16& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800662 CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700663 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700664 if (!cameraInfo) {
665 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800666 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -0700667 }
668
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800669 if (!mInitialized) {
670 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800671 return STATUS_ERROR(ERROR_DISCONNECTED,
672 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -0700673 }
674
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700675 if (shouldRejectSystemCameraConnection(String8(cameraId))) {
676 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
677 "characteristics for system only device %s: ", String8(cameraId).string());
678 }
679
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800680 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800681
Emilian Peevf53f66e2017-04-11 14:29:43 +0100682 status_t res = mCameraProviderManager->getCameraCharacteristics(
683 String8(cameraId).string(), cameraInfo);
684 if (res != OK) {
685 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
686 "characteristics for device %s: %s (%d)", String8(cameraId).string(),
687 strerror(-res), res);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700688 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700689 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
690 if (getSystemCameraKind(String8(cameraId), &deviceKind) != OK) {
691 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, String8(cameraId).string());
692 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera kind "
693 "for device %s", String8(cameraId).string());
694 }
Jayant Chowdhary12361932018-08-27 14:46:13 -0700695 int callingPid = CameraThreadState::getCallingPid();
696 int callingUid = CameraThreadState::getCallingUid();
Emilian Peeve20c6372018-08-14 18:45:53 +0100697 std::vector<int32_t> tagsRemoved;
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700698 // If it's not calling from cameraserver, check the permission only if
699 // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
700 // it would've already been checked in shouldRejectSystemCameraConnection.
Emilian Peeve20c6372018-08-14 18:45:53 +0100701 if ((callingPid != getpid()) &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700702 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700703 !checkPermission(sCameraPermission, callingPid, callingUid)) {
Emilian Peeve20c6372018-08-14 18:45:53 +0100704 res = cameraInfo->removePermissionEntries(
705 mCameraProviderManager->getProviderTagIdLocked(String8(cameraId).string()),
706 &tagsRemoved);
707 if (res != OK) {
708 cameraInfo->clear();
709 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
710 " characteristics needing camera permission for device %s: %s (%d)",
711 String8(cameraId).string(), strerror(-res), res);
712 }
713 }
714
715 if (!tagsRemoved.empty()) {
716 res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
717 tagsRemoved.data(), tagsRemoved.size());
718 if (res != OK) {
719 cameraInfo->clear();
720 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
721 "keys needing permission for device %s: %s (%d)", String8(cameraId).string(),
722 strerror(-res), res);
723 }
724 }
725
Zhijun He2b59be82013-09-25 10:14:30 -0700726 return ret;
727}
728
Ruben Brunkcc776712015-02-17 20:18:47 -0800729String8 CameraService::getFormattedCurrentTime() {
730 time_t now = time(nullptr);
731 char formattedTime[64];
732 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
733 return String8(formattedTime);
734}
735
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800736Status CameraService::getCameraVendorTagDescriptor(
737 /*out*/
738 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700739 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800740 if (!mInitialized) {
741 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800742 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800743 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -0800744 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
745 if (globalDescriptor != nullptr) {
746 *desc = *(globalDescriptor.get());
747 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800748 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800749}
750
Emilian Peev71c73a22017-03-21 16:35:51 +0000751Status CameraService::getCameraVendorTagCache(
752 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
753 ATRACE_CALL();
754 if (!mInitialized) {
755 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
756 return STATUS_ERROR(ERROR_DISCONNECTED,
757 "Camera subsystem not available");
758 }
759 sp<VendorTagDescriptorCache> globalCache =
760 VendorTagDescriptorCache::getGlobalVendorTagCache();
761 if (globalCache != nullptr) {
762 *cache = *(globalCache.get());
763 }
764 return Status::ok();
765}
766
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800767int CameraService::getDeviceVersion(const String8& cameraId, int* facing) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700768 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800769
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800770 int deviceVersion = 0;
771
Emilian Peevf53f66e2017-04-11 14:29:43 +0100772 status_t res;
773 hardware::hidl_version maxVersion{0,0};
774 res = mCameraProviderManager->getHighestSupportedVersion(cameraId.string(),
775 &maxVersion);
776 if (res != OK) return -1;
777 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800778
Emilian Peevf53f66e2017-04-11 14:29:43 +0100779 hardware::CameraInfo info;
780 if (facing) {
781 res = mCameraProviderManager->getCameraInfo(cameraId.string(), &info);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -0800782 if (res != OK) return -1;
Emilian Peevf53f66e2017-04-11 14:29:43 +0100783 *facing = info.facing;
Igor Murashkin634a5152013-02-20 17:15:11 -0800784 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100785
Igor Murashkin634a5152013-02-20 17:15:11 -0800786 return deviceVersion;
787}
788
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800789Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700790 switch(err) {
791 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800792 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800793 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800794 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
795 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800796 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800797 return STATUS_ERROR(ERROR_DISCONNECTED,
798 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700799 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800800 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
801 "Camera HAL encountered error %d: %s",
802 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700803 }
Igor Murashkinbfc99152013-02-27 12:55:20 -0800804}
805
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800806Status CameraService::makeClient(const sp<CameraService>& cameraService,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800807 const sp<IInterface>& cameraCb, const String16& packageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +0900808 const std::optional<String16>& featureId, const String8& cameraId, int api1CameraId,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800809 int facing, int clientPid, uid_t clientUid, int servicePid, int halVersion,
810 int deviceVersion, apiLevel effectiveApiLevel,
Ruben Brunkcc776712015-02-17 20:18:47 -0800811 /*out*/sp<BasicClient>* client) {
812
Ruben Brunkcc776712015-02-17 20:18:47 -0800813 if (halVersion < 0 || halVersion == deviceVersion) {
814 // Default path: HAL version is unspecified by caller, create CameraClient
815 // based on device version reported by the HAL.
816 switch(deviceVersion) {
817 case CAMERA_DEVICE_API_VERSION_1_0:
818 if (effectiveApiLevel == API_1) { // Camera1 API route
819 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800820 *client = new CameraClient(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800821 api1CameraId, facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700822 getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800823 } else { // Camera2 API route
824 ALOGW("Camera using old HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800825 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800826 "Camera device \"%s\" HAL version %d does not support camera2 API",
827 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800828 }
829 break;
Ruben Brunkcc776712015-02-17 20:18:47 -0800830 case CAMERA_DEVICE_API_VERSION_3_0:
831 case CAMERA_DEVICE_API_VERSION_3_1:
832 case CAMERA_DEVICE_API_VERSION_3_2:
833 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -0700834 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -0700835 case CAMERA_DEVICE_API_VERSION_3_5:
Yin-Chia Yeh56d98ba2020-01-16 16:57:14 -0800836 case CAMERA_DEVICE_API_VERSION_3_6:
Ruben Brunkcc776712015-02-17 20:18:47 -0800837 if (effectiveApiLevel == API_1) { // Camera1 API route
838 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800839 *client = new Camera2Client(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800840 cameraId, api1CameraId,
841 facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700842 servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800843 } else { // Camera2 API route
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800844 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
845 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800846 *client = new CameraDeviceClient(cameraService, tmp, packageName, featureId,
847 cameraId, facing, clientPid, clientUid, servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800848 }
849 break;
850 default:
851 // Should not be reachable
852 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800853 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800854 "Camera device \"%s\" has unknown HAL version %d",
855 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800856 }
857 } else {
858 // A particular HAL version is requested by caller. Create CameraClient
859 // based on the requested HAL version.
860 if (deviceVersion > CAMERA_DEVICE_API_VERSION_1_0 &&
861 halVersion == CAMERA_DEVICE_API_VERSION_1_0) {
862 // Only support higher HAL version device opened as HAL1.0 device.
863 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800864 *client = new CameraClient(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800865 api1CameraId, facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700866 servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800867 } else {
868 // Other combinations (e.g. HAL3.x open as HAL2.x) are not supported yet.
869 ALOGE("Invalid camera HAL version %x: HAL %x device can only be"
870 " opened as HAL %x device", halVersion, deviceVersion,
871 CAMERA_DEVICE_API_VERSION_1_0);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800872 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800873 "Camera device \"%s\" (HAL version %d) cannot be opened as HAL version %d",
874 cameraId.string(), deviceVersion, halVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800875 }
876 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800877 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800878}
879
Ruben Brunk6267b532015-04-30 17:44:07 -0700880String8 CameraService::toString(std::set<userid_t> intSet) {
881 String8 s("");
882 bool first = true;
883 for (userid_t i : intSet) {
884 if (first) {
885 s.appendFormat("%d", i);
886 first = false;
887 } else {
888 s.appendFormat(", %d", i);
889 }
890 }
891 return s;
892}
893
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800894int32_t CameraService::mapToInterface(TorchModeStatus status) {
895 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
896 switch (status) {
897 case TorchModeStatus::NOT_AVAILABLE:
898 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
899 break;
900 case TorchModeStatus::AVAILABLE_OFF:
901 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
902 break;
903 case TorchModeStatus::AVAILABLE_ON:
904 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
905 break;
906 default:
907 ALOGW("Unknown new flash status: %d", status);
908 }
909 return serviceStatus;
910}
911
912CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
913 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
914 switch (status) {
915 case CameraDeviceStatus::NOT_PRESENT:
916 serviceStatus = StatusInternal::NOT_PRESENT;
917 break;
918 case CameraDeviceStatus::PRESENT:
919 serviceStatus = StatusInternal::PRESENT;
920 break;
921 case CameraDeviceStatus::ENUMERATING:
922 serviceStatus = StatusInternal::ENUMERATING;
923 break;
924 default:
925 ALOGW("Unknown new HAL device status: %d", status);
926 }
927 return serviceStatus;
928}
929
930int32_t CameraService::mapToInterface(StatusInternal status) {
931 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
932 switch (status) {
933 case StatusInternal::NOT_PRESENT:
934 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
935 break;
936 case StatusInternal::PRESENT:
937 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
938 break;
939 case StatusInternal::ENUMERATING:
940 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
941 break;
942 case StatusInternal::NOT_AVAILABLE:
943 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
944 break;
945 case StatusInternal::UNKNOWN:
946 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
947 break;
948 default:
949 ALOGW("Unknown new internal device status: %d", status);
950 }
951 return serviceStatus;
952}
953
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800954Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -0700955 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700956
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800957 String16 internalPackageName("cameraserver");
Ruben Brunkcc776712015-02-17 20:18:47 -0800958 String8 id = String8::format("%d", cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800959 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800960 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800961 if (!(ret = connectHelper<ICameraClient,Client>(
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800962 sp<ICameraClient>{nullptr}, id, cameraId,
963 static_cast<int>(CAMERA_HAL_API_VERSION_UNSPECIFIED),
Jooyung Hanb3f7cd22020-01-23 12:27:18 +0900964 internalPackageName, {}, uid, USE_CALLING_PID,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700965 API_1, /*shimUpdateOnly*/ true, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800966 ).isOk()) {
967 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
Ruben Brunkb2119af2014-05-09 19:57:56 -0700968 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800969 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700970}
971
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800972Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -0700973 /*out*/
974 CameraParameters* parameters) {
975
976 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
977
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800978 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -0700979
980 if (parameters == NULL) {
981 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800982 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -0700983 }
984
Ruben Brunkcc776712015-02-17 20:18:47 -0800985 String8 id = String8::format("%d", cameraId);
986
987 // Check if we already have parameters
988 {
989 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -0700990 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -0800991 auto cameraState = getCameraState(id);
992 if (cameraState == nullptr) {
993 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800994 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
995 "Invalid camera ID: %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -0800996 }
997 CameraParameters p = cameraState->getShimParams();
998 if (!p.isEmpty()) {
999 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001000 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001001 }
1002 }
1003
Jayant Chowdhary12361932018-08-27 14:46:13 -07001004 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001005 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001006 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001007 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001008 // Error already logged by callee
1009 return ret;
1010 }
1011
1012 // Check for parameters again
1013 {
1014 // Scope for service lock
1015 Mutex::Autolock lock(mServiceLock);
1016 auto cameraState = getCameraState(id);
1017 if (cameraState == nullptr) {
1018 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001019 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1020 "Invalid camera ID: %s", id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001021 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001022 CameraParameters p = cameraState->getShimParams();
1023 if (!p.isEmpty()) {
1024 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001025 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001026 }
1027 }
1028
Ruben Brunkcc776712015-02-17 20:18:47 -08001029 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1030 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001031 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001032}
1033
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001034// Can camera service trust the caller based on the calling UID?
1035static bool isTrustedCallingUid(uid_t uid) {
1036 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001037 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001038 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001039 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001040 return true;
1041 default:
1042 return false;
1043 }
1044}
1045
Nicholas Sauera3620332019-04-03 14:05:17 -07001046static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1047 PermissionController pc;
1048 uid = pc.getPackageUid(packageName, 0);
1049 if (uid <= 0) {
1050 ALOGE("Unknown package: '%s'", String8(packageName).string());
1051 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
1052 return BAD_VALUE;
1053 }
1054
1055 if (userId < 0) {
1056 ALOGE("Invalid user: %d", userId);
1057 dprintf(err, "Invalid user: %d\n", userId);
1058 return BAD_VALUE;
1059 }
1060
1061 uid = multiuser_get_uid(userId, uid);
1062 return NO_ERROR;
1063}
1064
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001065Status CameraService::validateConnectLocked(const String8& cameraId,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001066 const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
1067 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001068
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001069#ifdef __BRILLO__
1070 UNUSED(clientName8);
1071 UNUSED(clientUid);
1072 UNUSED(clientPid);
1073 UNUSED(originalClientPid);
1074#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001075 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1076 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001077 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001078 return allowed;
1079 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001080#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001081
Jayant Chowdhary12361932018-08-27 14:46:13 -07001082 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001083
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001084 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001085 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1086 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001087 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1088 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001089 }
1090
Ruben Brunkcc776712015-02-17 20:18:47 -08001091 if (getCameraState(cameraId) == nullptr) {
1092 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1093 cameraId.string());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001094 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1095 "No camera device with ID \"%s\" available", cameraId.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001096 }
1097
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001098 status_t err = checkIfDeviceIsUsable(cameraId);
1099 if (err != NO_ERROR) {
1100 switch(err) {
1101 case -ENODEV:
1102 case -EBUSY:
1103 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1104 "No camera device with ID \"%s\" currently available", cameraId.string());
1105 default:
1106 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1107 "Unknown error connecting to ID \"%s\"", cameraId.string());
1108 }
1109 }
1110 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001111}
1112
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001113Status CameraService::validateClientPermissionsLocked(const String8& cameraId,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001114 const String8& clientName8, int& clientUid, int& clientPid,
1115 /*out*/int& originalClientPid) const {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001116 int callingPid = CameraThreadState::getCallingPid();
1117 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001118
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001119 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001120 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001121 clientUid = callingUid;
1122 } else if (!isTrustedCallingUid(callingUid)) {
1123 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1124 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001125 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1126 "Untrusted caller (calling PID %d, UID %d) trying to "
1127 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1128 callingPid, callingUid, cameraId.string(),
1129 clientName8.string(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001130 }
1131
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001132 // Check if we can trust clientPid
1133 if (clientPid == USE_CALLING_PID) {
1134 clientPid = callingPid;
1135 } else if (!isTrustedCallingUid(callingUid)) {
1136 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1137 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001138 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1139 "Untrusted caller (calling PID %d, UID %d) trying to "
1140 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1141 callingPid, callingUid, cameraId.string(),
1142 clientName8.string(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001143 }
1144
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001145 if (shouldRejectSystemCameraConnection(cameraId)) {
1146 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1147 cameraId.c_str());
1148 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
1149 "available", cameraId.string());
1150 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001151 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1152 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1153 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
1154 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
1155 "found while trying to query device kind", cameraId.string());
1156
1157 }
1158
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001159 // If it's not calling from cameraserver, check the permission if the
1160 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1161 // android.permission.SYSTEM_CAMERA for system only camera devices).
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001162 if (callingPid != getpid() &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001163 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001164 !checkPermission(sCameraPermission, clientPid, clientUid)) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001165 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001166 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1167 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
1168 clientName8.string(), clientUid, clientPid, cameraId.string());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001169 }
1170
Svet Ganova453d0d2018-01-11 15:37:58 -08001171 // Make sure the UID is in an active state to use the camera
Svet Ganov7b4ab782018-03-25 12:48:10 -07001172 if (!mUidPolicy->isUidActive(callingUid, String16(clientName8))) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001173 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001174 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1175 clientPid, clientUid);
1176 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001177 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1178 "calling UID %d proc state %" PRId32 ")",
1179 clientName8.string(), clientUid, clientPid, cameraId.string(),
1180 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001181 }
1182
Michael Grooverd1d435a2018-12-18 17:39:42 -08001183 // If sensor privacy is enabled then prevent access to the camera
1184 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1185 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1186 return STATUS_ERROR_FMT(ERROR_DISABLED,
1187 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
1188 "is enabled", clientName8.string(), clientUid, clientPid, cameraId.string());
1189 }
1190
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001191 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1192 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001193 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001194 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001195
Ruben Brunk6267b532015-04-30 17:44:07 -07001196 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001197
Ruben Brunka8ca9152015-04-07 14:23:40 -07001198 // Only allow clients who are being used by the current foreground device user, unless calling
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001199 // from our own process OR the caller is using the cameraserver's HIDL interface.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001200 if (getCurrentServingCall() != BinderCallType::HWBINDER && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001201 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001202 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1203 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
1204 toString(mAllowedUsers).string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001205 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1206 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
1207 clientUserId, cameraId.string());
Ruben Brunk36597b22015-03-20 22:15:57 -07001208 }
1209
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001210 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001211}
1212
1213status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
1214 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001215 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001216 if (cameraState == nullptr) {
1217 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1218 cameraId.string());
1219 return -ENODEV;
1220 }
1221
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001222 StatusInternal currentStatus = cameraState->getStatus();
1223 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001224 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
1225 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001226 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001227 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001228 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
1229 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001230 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001231 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001232
Ruben Brunkcc776712015-02-17 20:18:47 -08001233 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001234}
1235
Ruben Brunkcc776712015-02-17 20:18:47 -08001236void CameraService::finishConnectLocked(const sp<BasicClient>& client,
1237 const CameraService::DescriptorPtr& desc) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001238
Ruben Brunkcc776712015-02-17 20:18:47 -08001239 // Make a descriptor for the incoming client
1240 auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
1241 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1242
1243 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
1244 String8(client->getPackageName()));
1245
1246 if (evicted.size() > 0) {
1247 // This should never happen - clients should already have been removed in disconnect
1248 for (auto& i : evicted) {
1249 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
1250 __FUNCTION__, i->getKey().string());
1251 }
1252
1253 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1254 __FUNCTION__);
1255 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001256
1257 // And register a death notification for the client callback. Do
1258 // this last to avoid Binder policy where a nested Binder
1259 // transaction might be pre-empted to service the client death
1260 // notification if the client process dies before linkToDeath is
1261 // invoked.
1262 sp<IBinder> remoteCallback = client->getRemote();
1263 if (remoteCallback != nullptr) {
1264 remoteCallback->linkToDeath(this);
1265 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001266}
1267
1268status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
1269 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
1270 /*out*/
1271 sp<BasicClient>* client,
1272 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001273 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001274 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001275 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001276 DescriptorPtr clientDescriptor;
1277 {
1278 if (effectiveApiLevel == API_1) {
1279 // If we are using API1, any existing client for this camera ID with the same remote
1280 // should be returned rather than evicted to allow MediaRecorder to work properly.
1281
1282 auto current = mActiveClientManager.get(cameraId);
1283 if (current != nullptr) {
1284 auto clientSp = current->getValue();
1285 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001286 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
1287 ALOGW("CameraService connect called from same client, but with a different"
1288 " API level, evicting prior client...");
1289 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001290 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001291 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001292 *client = clientSp;
1293 return NO_ERROR;
1294 }
1295 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001296 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001297 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001298
Ruben Brunkcc776712015-02-17 20:18:47 -08001299 // Get current active client PIDs
1300 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1301 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001302
Emilian Peev8131a262017-02-01 12:33:43 +00001303 std::vector<int> priorityScores(ownerPids.size());
1304 std::vector<int> states(ownerPids.size());
Igor Murashkine6800ce2013-03-04 17:25:57 -08001305
Emilian Peev8131a262017-02-01 12:33:43 +00001306 // Get priority scores of all active PIDs
1307 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1308 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1309 /*out*/&priorityScores[0]);
1310 if (err != OK) {
1311 ALOGE("%s: Priority score query failed: %d",
1312 __FUNCTION__, err);
1313 return err;
1314 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001315
Ruben Brunkcc776712015-02-17 20:18:47 -08001316 // Update all active clients' priorities
Emilian Peev8131a262017-02-01 12:33:43 +00001317 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
Ruben Brunkcc776712015-02-17 20:18:47 -08001318 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
Emilian Peev8131a262017-02-01 12:33:43 +00001319 pidToPriorityMap.emplace(ownerPids[i],
Jayant Chowdharyc578a502019-05-08 10:57:54 -07001320 resource_policy::ClientPriority(priorityScores[i], states[i],
1321 /* isVendorClient won't get copied over*/ false));
Ruben Brunkcc776712015-02-17 20:18:47 -08001322 }
1323 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001324
Ruben Brunkcc776712015-02-17 20:18:47 -08001325 // Get state for the given cameraId
1326 auto state = getCameraState(cameraId);
1327 if (state == nullptr) {
1328 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1329 clientPid, cameraId.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001330 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001331 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001332 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001333
1334 // Make descriptor for incoming client
Shuzhen Wang2db86ff2018-04-25 01:11:17 +00001335 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001336 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1337 state->getConflicting(),
Emilian Peev8131a262017-02-01 12:33:43 +00001338 priorityScores[priorityScores.size() - 1],
1339 clientPid,
1340 states[states.size() - 1]);
Ruben Brunkcc776712015-02-17 20:18:47 -08001341
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001342 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1343
Ruben Brunkcc776712015-02-17 20:18:47 -08001344 // Find clients that would be evicted
1345 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1346
1347 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1348 // background, so we cannot do evictions
1349 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1350 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1351 " priority).", clientPid);
1352
1353 sp<BasicClient> clientSp = clientDescriptor->getValue();
1354 String8 curTime = getFormattedCurrentTime();
1355 auto incompatibleClients =
1356 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1357
1358 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Emilian Peev8131a262017-02-01 12:33:43 +00001359 "(PID %d, score %d state %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001360 cameraId.string(), packageName.string(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001361 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001362
1363 for (auto& i : incompatibleClients) {
1364 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001365 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
1366 i->getKey().string(),
1367 String8{i->getValue()->getPackageName()}.string(),
1368 i->getOwnerId(), i->getPriority().getScore(),
1369 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001370 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00001371 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(),
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001372 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001373 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001374 }
1375
1376 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001377 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001378 mEventLog.add(msg);
1379
1380 return -EBUSY;
1381 }
1382
1383 for (auto& i : evicted) {
1384 sp<BasicClient> clientSp = i->getValue();
1385 if (clientSp.get() == nullptr) {
1386 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1387
1388 // TODO: Remove this
1389 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1390 __FUNCTION__);
1391 mActiveClientManager.remove(i);
1392 continue;
1393 }
1394
1395 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1396 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001397 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001398
Ruben Brunkcc776712015-02-17 20:18:47 -08001399 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001400 logEvent(String8::format("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00001401 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1402 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001403 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
Emilian Peev8131a262017-02-01 12:33:43 +00001404 i->getOwnerId(), i->getPriority().getScore(),
1405 i->getPriority().getState(), cameraId.string(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001406 packageName.string(), clientPid, clientPriority.getScore(),
1407 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08001408
1409 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001410 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001411 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001412 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001413 }
1414
Ruben Brunkcc776712015-02-17 20:18:47 -08001415 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1416 // other clients from connecting in mServiceLockWrapper if held
1417 mServiceLock.unlock();
1418
1419 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07001420 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001421
1422 // Destroy evicted clients
1423 for (auto& i : evictedClients) {
1424 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001425 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001426 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001427
Jayant Chowdhary12361932018-08-27 14:46:13 -07001428 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08001429
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001430 for (const auto& i : evictedClients) {
1431 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1432 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1433 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1434 if (ret == TIMED_OUT) {
1435 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1436 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1437 mActiveClientManager.toString().string());
1438 return -EBUSY;
1439 }
1440 if (ret != NO_ERROR) {
1441 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1442 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1443 ret, mActiveClientManager.toString().string());
1444 return ret;
1445 }
1446 }
1447
1448 evictedClients.clear();
1449
Ruben Brunkcc776712015-02-17 20:18:47 -08001450 // Once clients have been disconnected, relock
1451 mServiceLock.lock();
1452
1453 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1454 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1455 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001456 }
1457
Ruben Brunkcc776712015-02-17 20:18:47 -08001458 *partial = clientDescriptor;
1459 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001460}
1461
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001462Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001463 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001464 int api1CameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001465 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001466 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001467 int clientPid,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001468 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001469 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001470
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001471 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001472 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001473
1474 String8 id = cameraIdIntToStr(api1CameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001475 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001476 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001477 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, {},
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001478 clientUid, clientPid, API_1, /*shimUpdateOnly*/ false, /*out*/client);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001479
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001480 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001481 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001482 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001483 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001484 }
1485
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001486 *device = client;
1487 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001488}
1489
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001490Status CameraService::connectLegacy(
Zhijun Heb10cdad2014-06-16 16:38:35 -07001491 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001492 int api1CameraId, int halVersion,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001493 const String16& clientPackageName,
Zhijun Heb10cdad2014-06-16 16:38:35 -07001494 int clientUid,
1495 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001496 sp<ICamera>* device) {
Zhijun Heb10cdad2014-06-16 16:38:35 -07001497
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001498 ATRACE_CALL();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001499 String8 id = cameraIdIntToStr(api1CameraId);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001500
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001501 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001502 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001503 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId, halVersion,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001504 clientPackageName, {}, clientUid, USE_CALLING_PID, API_1,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001505 /*shimUpdateOnly*/ false, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001506
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001507 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001508 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001509 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001510 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001511 }
1512
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001513 *device = client;
1514 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001515}
1516
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001517bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
1518 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001519 // If the client is not a vendor client, don't add listener if
1520 // a) the camera is a publicly hidden secure camera OR
1521 // b) the camera is a system only camera and the client doesn't
1522 // have android.permission.SYSTEM_CAMERA permissions.
1523 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
1524 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1525 !hasPermissionsForSystemCamera(clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001526 return true;
1527 }
1528 return false;
1529}
1530
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001531bool CameraService::shouldRejectSystemCameraConnection(const String8& cameraId) const {
1532 // Rules for rejection:
1533 // 1) If cameraserver tries to access this camera device, accept the
1534 // connection.
1535 // 2) The camera device is a publicly hidden secure camera device AND some
1536 // component is trying to access it on a non-hwbinder thread (generally a non HAL client),
1537 // reject it.
1538 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
1539 // and the serving thread is a non hwbinder thread, the client must have
1540 // android.permission.SYSTEM_CAMERA permissions to connect.
1541
1542 int cPid = CameraThreadState::getCallingPid();
1543 int cUid = CameraThreadState::getCallingUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001544 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
1545 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
1546 ALOGE("%s: Invalid camera id %s, ", __FUNCTION__, cameraId.c_str());
1547 return true;
1548 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001549
1550 // (1) Cameraserver trying to connect, accept.
1551 if (CameraThreadState::getCallingPid() == getpid()) {
1552 return false;
1553 }
1554 // (2)
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001555 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001556 systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
1557 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
1558 return true;
1559 }
1560 // (3) Here we only check for permissions if it is a system only camera device. This is since
1561 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
1562 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
1563 // same behavior for system camera devices.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001564 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001565 systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1566 !hasPermissionsForSystemCamera(cPid, cUid)) {
1567 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
1568 cameraId.c_str());
1569 return true;
1570 }
1571
1572 return false;
1573}
1574
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001575Status CameraService::connectDevice(
1576 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001577 const String16& cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001578 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001579 const std::optional<String16>& clientFeatureId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001580 int clientUid,
1581 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001582 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001583
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001584 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001585 Status ret = Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001586 String8 id = String8(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001587 sp<CameraDeviceClient> client = nullptr;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001588 String16 clientPackageNameAdj = clientPackageName;
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001589
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001590 if (getCurrentServingCall() == BinderCallType::HWBINDER) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001591 std::string vendorClient =
1592 StringPrintf("vendor.client.pid<%d>", CameraThreadState::getCallingPid());
1593 clientPackageNameAdj = String16(vendorClient.c_str());
1594 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001595 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001596 /*api1CameraId*/-1,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001597 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageNameAdj, clientFeatureId,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001598 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08001599
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001600 if(!ret.isOk()) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001601 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageNameAdj),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001602 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001603 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001604 }
1605
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001606 *device = client;
1607 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001608}
1609
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001610template<class CALLBACK, class CLIENT>
1611Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001612 int api1CameraId, int halVersion, const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001613 const std::optional<String16>& clientFeatureId, int clientUid, int clientPid,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001614 apiLevel effectiveApiLevel, bool shimUpdateOnly,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001615 /*out*/sp<CLIENT>& device) {
1616 binder::Status ret = binder::Status::ok();
1617
1618 String8 clientName8(clientPackageName);
1619
1620 int originalClientPid = 0;
1621
1622 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) for HAL version %s and "
1623 "Camera API version %d", clientPid, clientName8.string(), cameraId.string(),
1624 (halVersion == -1) ? "default" : std::to_string(halVersion).c_str(),
1625 static_cast<int>(effectiveApiLevel));
1626
1627 sp<CLIENT> client = nullptr;
1628 {
1629 // Acquire mServiceLock and prevent other clients from connecting
1630 std::unique_ptr<AutoConditionLock> lock =
1631 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1632
1633 if (lock == nullptr) {
1634 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
1635 , clientPid);
1636 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1637 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
1638 cameraId.string(), clientName8.string(), clientPid);
1639 }
1640
1641 // Enforce client permissions and do basic sanity checks
1642 if(!(ret = validateConnectLocked(cameraId, clientName8,
1643 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
1644 return ret;
1645 }
1646
1647 // Check the shim parameters after acquiring lock, if they have already been updated and
1648 // we were doing a shim update, return immediately
1649 if (shimUpdateOnly) {
1650 auto cameraState = getCameraState(cameraId);
1651 if (cameraState != nullptr) {
1652 if (!cameraState->getShimParams().isEmpty()) return ret;
1653 }
1654 }
1655
1656 status_t err;
1657
1658 sp<BasicClient> clientTmp = nullptr;
1659 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
1660 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
1661 IInterface::asBinder(cameraCb), clientName8, /*out*/&clientTmp,
1662 /*out*/&partial)) != NO_ERROR) {
1663 switch (err) {
1664 case -ENODEV:
1665 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1666 "No camera device with ID \"%s\" currently available",
1667 cameraId.string());
1668 case -EBUSY:
1669 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1670 "Higher-priority client using camera, ID \"%s\" currently unavailable",
1671 cameraId.string());
1672 default:
1673 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1674 "Unexpected error %s (%d) opening camera \"%s\"",
1675 strerror(-err), err, cameraId.string());
1676 }
1677 }
1678
1679 if (clientTmp.get() != nullptr) {
1680 // Handle special case for API1 MediaRecorder where the existing client is returned
1681 device = static_cast<CLIENT*>(clientTmp.get());
1682 return ret;
1683 }
1684
1685 // give flashlight a chance to close devices if necessary.
1686 mFlashlight->prepareDeviceOpen(cameraId);
1687
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001688 int facing = -1;
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001689 int deviceVersion = getDeviceVersion(cameraId, /*out*/&facing);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08001690 if (facing == -1) {
1691 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.string());
1692 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1693 "Unable to get camera device \"%s\" facing", cameraId.string());
1694 }
1695
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001696 sp<BasicClient> tmp = nullptr;
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001697 if(!(ret = makeClient(this, cameraCb, clientPackageName, clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001698 cameraId, api1CameraId, facing,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001699 clientPid, clientUid, getpid(),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001700 halVersion, deviceVersion, effectiveApiLevel,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001701 /*out*/&tmp)).isOk()) {
1702 return ret;
1703 }
1704 client = static_cast<CLIENT*>(tmp.get());
1705
1706 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
1707 __FUNCTION__);
1708
Emilian Peevbd8c5032018-02-14 23:05:40 +00001709 err = client->initialize(mCameraProviderManager, mMonitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001710 if (err != OK) {
1711 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001712 // Errors could be from the HAL module open call or from AppOpsManager
1713 switch(err) {
1714 case BAD_VALUE:
1715 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1716 "Illegal argument to HAL module for camera \"%s\"", cameraId.string());
1717 case -EBUSY:
1718 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1719 "Camera \"%s\" is already open", cameraId.string());
1720 case -EUSERS:
1721 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1722 "Too many cameras already open, cannot open camera \"%s\"",
1723 cameraId.string());
1724 case PERMISSION_DENIED:
1725 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1726 "No permission to open camera \"%s\"", cameraId.string());
1727 case -EACCES:
1728 return STATUS_ERROR_FMT(ERROR_DISABLED,
1729 "Camera \"%s\" disabled by policy", cameraId.string());
1730 case -ENODEV:
1731 default:
1732 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1733 "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
1734 strerror(-err), err);
1735 }
1736 }
1737
1738 // Update shim paremeters for legacy clients
1739 if (effectiveApiLevel == API_1) {
1740 // Assume we have always received a Client subclass for API1
1741 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
1742 String8 rawParams = shimClient->getParameters();
1743 CameraParameters params(rawParams);
1744
1745 auto cameraState = getCameraState(cameraId);
1746 if (cameraState != nullptr) {
1747 cameraState->setShimParams(params);
1748 } else {
1749 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
1750 __FUNCTION__, cameraId.string());
1751 }
1752 }
1753
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001754 // Set rotate-and-crop override behavior
1755 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
1756 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
1757 }
1758
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001759 if (shimUpdateOnly) {
1760 // If only updating legacy shim parameters, immediately disconnect client
1761 mServiceLock.unlock();
1762 client->disconnect();
1763 mServiceLock.lock();
1764 } else {
1765 // Otherwise, add client to active clients list
1766 finishConnectLocked(client, partial);
1767 }
1768 } // lock is destroyed, allow further connect calls
1769
1770 // Important: release the mutex here so the client can call back into the service from its
1771 // destructor (can be at the end of the call)
1772 device = client;
1773 return ret;
1774}
1775
Emilian Peevb2bc5a42019-11-20 16:02:14 -08001776status_t CameraService::addOfflineClient(String8 cameraId, sp<BasicClient> offlineClient) {
1777 if (offlineClient.get() == nullptr) {
1778 return BAD_VALUE;
1779 }
1780
1781 {
1782 // Acquire mServiceLock and prevent other clients from connecting
1783 std::unique_ptr<AutoConditionLock> lock =
1784 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1785
1786 if (lock == nullptr) {
1787 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
1788 , __FUNCTION__, offlineClient->getClientPid());
1789 return TIMED_OUT;
1790 }
1791
1792 auto onlineClientDesc = mActiveClientManager.get(cameraId);
1793 if (onlineClientDesc.get() == nullptr) {
1794 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
1795 cameraId.c_str());
1796 return BAD_VALUE;
1797 }
1798
1799 // Offline clients do not evict or conflict with other online devices. Resource sharing
1800 // conflicts are handled by the camera provider which will either succeed or fail before
1801 // reaching this method.
1802 const auto& onlinePriority = onlineClientDesc->getPriority();
1803 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
1804 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
1805 /*conflictingKeys*/ std::set<String8>(), onlinePriority.getScore(),
1806 onlineClientDesc->getOwnerId(), onlinePriority.getState());
1807
1808 // Allow only one offline device per camera
1809 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
1810 if (!incompatibleClients.empty()) {
1811 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
1812 return BAD_VALUE;
1813 }
1814
1815 auto err = offlineClient->initialize(mCameraProviderManager, mMonitorTags);
1816 if (err != OK) {
1817 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
1818 return err;
1819 }
1820
1821 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
1822 if (evicted.size() > 0) {
1823 for (auto& i : evicted) {
1824 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
1825 __FUNCTION__, i->getKey().string());
1826 }
1827
1828 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
1829 "properly", __FUNCTION__);
1830
1831 return BAD_VALUE;
1832 }
1833
1834 logConnectedOffline(offlineClientDesc->getKey(),
1835 static_cast<int>(offlineClientDesc->getOwnerId()),
1836 String8(offlineClient->getPackageName()));
1837
1838 sp<IBinder> remoteCallback = offlineClient->getRemote();
1839 if (remoteCallback != nullptr) {
1840 remoteCallback->linkToDeath(this);
1841 }
1842 } // lock is destroyed, allow further connect calls
1843
1844 return OK;
1845}
1846
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001847Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001848 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001849 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001850
1851 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07001852 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001853 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001854 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1855 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001856 }
1857
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001858 String8 id = String8(cameraId.string());
Jayant Chowdhary12361932018-08-27 14:46:13 -07001859 int uid = CameraThreadState::getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001860
1861 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08001862 auto state = getCameraState(id);
1863 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001864 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001865 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1866 "Camera ID \"%s\" is a not valid camera ID", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001867 }
1868
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001869 StatusInternal cameraStatus = state->getStatus();
1870 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001871 cameraStatus != StatusInternal::NOT_AVAILABLE) {
1872 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001873 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1874 "Camera ID \"%s\" is a not valid camera ID", id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001875 }
1876
1877 {
1878 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001879 TorchModeStatus status;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001880 status_t err = getTorchStatusLocked(id, &status);
1881 if (err != OK) {
1882 if (err == NAME_NOT_FOUND) {
1883 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1884 "Camera \"%s\" does not have a flash unit", id.string());
1885 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001886 ALOGE("%s: getting current torch status failed for camera %s",
1887 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001888 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1889 "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
1890 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001891 }
1892
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001893 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001894 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001895 ALOGE("%s: torch mode of camera %s is not available because "
1896 "camera is in use", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001897 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1898 "Torch for camera \"%s\" is not available due to an existing camera user",
1899 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001900 } else {
1901 ALOGE("%s: torch mode of camera %s is not available due to "
1902 "insufficient resources", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001903 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1904 "Torch for camera \"%s\" is not available due to insufficient resources",
1905 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001906 }
1907 }
1908 }
1909
Ruben Brunk99e69712015-05-26 17:25:07 -07001910 {
1911 // Update UID map - this is used in the torch status changed callbacks, so must be done
1912 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07001913 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -07001914 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
1915 mTorchUidMap[id].first = uid;
1916 mTorchUidMap[id].second = uid;
1917 } else {
1918 // Set the pending UID
1919 mTorchUidMap[id].first = uid;
1920 }
1921 }
1922
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001923 status_t err = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07001924
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001925 if (err != OK) {
1926 int32_t errorCode;
1927 String8 msg;
1928 switch (err) {
1929 case -ENOSYS:
1930 msg = String8::format("Camera \"%s\" has no flashlight",
1931 id.string());
1932 errorCode = ERROR_ILLEGAL_ARGUMENT;
1933 break;
1934 default:
1935 msg = String8::format(
1936 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
1937 id.string(), enabled, strerror(-err), err);
1938 errorCode = ERROR_INVALID_OPERATION;
1939 }
1940 ALOGE("%s: %s", __FUNCTION__, msg.string());
1941 return STATUS_ERROR(errorCode, msg.string());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001942 }
1943
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001944 {
1945 // update the link to client's death
1946 Mutex::Autolock al(mTorchClientMapMutex);
1947 ssize_t index = mTorchClientMap.indexOfKey(id);
1948 if (enabled) {
1949 if (index == NAME_NOT_FOUND) {
1950 mTorchClientMap.add(id, clientBinder);
1951 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07001952 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001953 mTorchClientMap.replaceValueAt(index, clientBinder);
1954 }
1955 clientBinder->linkToDeath(this);
1956 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07001957 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001958 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001959 }
1960
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07001961 int clientPid = CameraThreadState::getCallingPid();
1962 const char *id_cstr = id.c_str();
1963 const char *torchState = enabled ? "on" : "off";
1964 ALOGI("Torch for camera id %s turned %s for client PID %d", id_cstr, torchState, clientPid);
1965 logTorchEvent(id_cstr, torchState , clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001966 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001967}
1968
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001969Status CameraService::notifySystemEvent(int32_t eventId,
1970 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001971 const int pid = CameraThreadState::getCallingPid();
1972 const int selfPid = getpid();
1973
1974 // Permission checks
1975 if (pid != selfPid) {
1976 // Ensure we're being called by system_server, or similar process with
1977 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001978 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001979 const int uid = CameraThreadState::getCallingUid();
1980 ALOGE("Permission Denial: cannot send updates to camera service about system"
1981 " events from pid=%d, uid=%d", pid, uid);
1982 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09001983 "No permission to send updates to camera service about system events"
1984 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001985 }
1986 }
1987
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001988 ATRACE_CALL();
1989
Ruben Brunk36597b22015-03-20 22:15:57 -07001990 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001991 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001992 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07001993 // from a system server crash
1994 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08001995 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001996 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07001997 break;
1998 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001999 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07002000 default: {
2001 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
2002 eventId);
2003 break;
2004 }
2005 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002006 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002007}
2008
Emilian Peev53722fa2019-02-22 17:47:20 -08002009void CameraService::notifyMonitoredUids() {
2010 Mutex::Autolock lock(mStatusListenerLock);
2011
2012 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002013 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Emilian Peev53722fa2019-02-22 17:47:20 -08002014 if (!ret.isOk()) {
2015 ALOGE("%s: Failed to trigger permission callback: %d", __FUNCTION__,
2016 ret.exceptionCode());
2017 }
2018 }
2019}
2020
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002021Status CameraService::notifyDeviceStateChange(int64_t newState) {
2022 const int pid = CameraThreadState::getCallingPid();
2023 const int selfPid = getpid();
2024
2025 // Permission checks
2026 if (pid != selfPid) {
2027 // Ensure we're being called by system_server, or similar process with
2028 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002029 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002030 const int uid = CameraThreadState::getCallingUid();
2031 ALOGE("Permission Denial: cannot send updates to camera service about device"
2032 " state changes from pid=%d, uid=%d", pid, uid);
2033 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2034 "No permission to send updates to camera service about device state"
2035 " changes from pid=%d, uid=%d", pid, uid);
2036 }
2037 }
2038
2039 ATRACE_CALL();
2040
2041 using hardware::camera::provider::V2_5::DeviceState;
2042 hardware::hidl_bitfield<DeviceState> newDeviceState{};
2043 if (newState & ICameraService::DEVICE_STATE_BACK_COVERED) {
2044 newDeviceState |= DeviceState::BACK_COVERED;
2045 }
2046 if (newState & ICameraService::DEVICE_STATE_FRONT_COVERED) {
2047 newDeviceState |= DeviceState::FRONT_COVERED;
2048 }
2049 if (newState & ICameraService::DEVICE_STATE_FOLDED) {
2050 newDeviceState |= DeviceState::FOLDED;
2051 }
2052 // Only map vendor bits directly
2053 uint64_t vendorBits = static_cast<uint64_t>(newState) & 0xFFFFFFFF00000000l;
2054 newDeviceState |= vendorBits;
2055
2056 ALOGV("%s: New device state 0x%" PRIx64, __FUNCTION__, newDeviceState);
2057 Mutex::Autolock l(mServiceLock);
2058 mCameraProviderManager->notifyDeviceStateChange(newDeviceState);
2059
2060 return Status::ok();
2061}
2062
Jayant Chowdharycad23c22020-03-10 15:04:59 -07002063 Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002064 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
2065 ATRACE_CALL();
2066 if (!concurrentCameraIds) {
2067 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
2068 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
2069 }
2070
2071 if (!mInitialized) {
2072 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2073 return STATUS_ERROR(ERROR_DISCONNECTED,
2074 "Camera subsystem is not available");
2075 }
2076 // First call into the provider and get the set of concurrent camera
2077 // combinations
2078 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07002079 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002080 for (auto &combination : concurrentCameraCombinations) {
2081 std::vector<std::string> validCombination;
2082 for (auto &cameraId : combination) {
2083 // if the camera state is not present, skip
2084 String8 cameraIdStr(cameraId.c_str());
2085 auto state = getCameraState(cameraIdStr);
2086 if (state == nullptr) {
2087 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
2088 continue;
2089 }
2090 StatusInternal status = state->getStatus();
2091 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
2092 continue;
2093 }
2094 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
2095 continue;
2096 }
2097 validCombination.push_back(cameraId);
2098 }
2099 if (validCombination.size() != 0) {
2100 concurrentCameraIds->push_back(std::move(validCombination));
2101 }
2102 }
2103 return Status::ok();
2104}
2105
2106Status CameraService::isConcurrentSessionConfigurationSupported(
2107 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
2108 /*out*/bool* isSupported) {
2109 if (!isSupported) {
2110 ALOGE("%s: isSupported is NULL", __FUNCTION__);
2111 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
2112 }
2113
2114 if (!mInitialized) {
2115 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2116 return STATUS_ERROR(ERROR_DISCONNECTED,
2117 "Camera subsystem is not available");
2118 }
2119
2120 // Check for camera permissions
2121 int callingPid = CameraThreadState::getCallingPid();
2122 int callingUid = CameraThreadState::getCallingUid();
2123 if ((callingPid != getpid()) && !checkPermission(sCameraPermission, callingPid, callingUid)) {
2124 ALOGE("%s: pid %d doesn't have camera permissions", __FUNCTION__, callingPid);
2125 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2126 "android.permission.CAMERA needed to call"
2127 "isConcurrentSessionConfigurationSupported");
2128 }
2129
2130 status_t res =
2131 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
2132 cameraIdsAndSessionConfigurations, isSupported);
2133 if (res != OK) {
2134 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
2135 "support %s (%d)", strerror(-res), res);
2136 }
2137 return Status::ok();
2138}
2139
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002140Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
2141 /*out*/
2142 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002143 return addListenerHelper(listener, cameraStatuses);
2144}
2145
2146Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
2147 /*out*/
2148 std::vector<hardware::CameraStatus> *cameraStatuses,
2149 bool isVendorListener) {
2150
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002151 ATRACE_CALL();
2152
Igor Murashkinbfc99152013-02-27 12:55:20 -08002153 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08002154
Ruben Brunk3450ba72015-06-16 11:00:37 -07002155 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002156 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002157 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002158 }
2159
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002160 auto clientUid = CameraThreadState::getCallingUid();
2161 auto clientPid = CameraThreadState::getCallingPid();
Shuzhen Wang695044d2020-03-06 09:02:23 -08002162 bool openCloseCallbackAllowed = checkPermission(sCameraOpenCloseListenerPermission,
2163 clientPid, clientUid);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002164
Igor Murashkinbfc99152013-02-27 12:55:20 -08002165 Mutex::Autolock lock(mServiceLock);
2166
Ruben Brunkcc776712015-02-17 20:18:47 -08002167 {
2168 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08002169 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002170 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002171 ALOGW("%s: Tried to add listener %p which was already subscribed",
2172 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002173 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08002174 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002175 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002176
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002177 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08002178 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
2179 openCloseCallbackAllowed);
Emilian Peev53722fa2019-02-22 17:47:20 -08002180 auto ret = serviceListener->initialize();
2181 if (ret != NO_ERROR) {
2182 String8 msg = String8::format("Failed to initialize service listener: %s (%d)",
2183 strerror(-ret), ret);
2184 ALOGE("%s: %s", __FUNCTION__, msg.string());
2185 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
2186 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002187 // The listener still needs to be added to the list of listeners, regardless of what
2188 // permissions the listener process has / whether it is a vendor listener. Since it might be
2189 // eligible to listen to other camera ids.
2190 mListenerList.emplace_back(serviceListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08002191 mUidPolicy->registerMonitorUid(clientUid);
Igor Murashkinbfc99152013-02-27 12:55:20 -08002192 }
2193
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002194 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07002195 {
Ruben Brunkcc776712015-02-17 20:18:47 -08002196 Mutex::Autolock lock(mCameraStatesLock);
2197 for (auto& i : mCameraStates) {
Shuzhen Wang43858162020-01-10 13:42:15 -08002198 cameraStatuses->emplace_back(i.first,
2199 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds());
Igor Murashkincba2c162013-03-20 15:56:31 -07002200 }
2201 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002202 // Remove the camera statuses that should be hidden from the client, we do
2203 // this after collecting the states in order to avoid holding
2204 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
2205 // the same time.
2206 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
2207 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
2208 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
2209 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
2210 ALOGE("%s: Invalid camera id %s, skipping status update",
2211 __FUNCTION__, s.cameraId.c_str());
2212 return true;
2213 }
2214 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
2215 clientUid);}), cameraStatuses->end());
2216
Igor Murashkincba2c162013-03-20 15:56:31 -07002217
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002218 /*
2219 * Immediately signal current torch status to this listener only
2220 * This may be a subset of all the devices, so don't include it in the response directly
2221 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002222 {
2223 Mutex::Autolock al(mTorchStatusMutex);
2224 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002225 String16 id = String16(mTorchStatusMap.keyAt(i).string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002226 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002227 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002228 }
2229
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002230 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08002231}
Ruben Brunkcc776712015-02-17 20:18:47 -08002232
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002233Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002234 ATRACE_CALL();
2235
Igor Murashkinbfc99152013-02-27 12:55:20 -08002236 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
2237
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002238 if (listener == 0) {
2239 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002240 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002241 }
2242
Igor Murashkinbfc99152013-02-27 12:55:20 -08002243 Mutex::Autolock lock(mServiceLock);
2244
Ruben Brunkcc776712015-02-17 20:18:47 -08002245 {
2246 Mutex::Autolock lock(mStatusListenerLock);
2247 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002248 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
2249 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid());
2250 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08002251 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002252 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002253 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002254 }
2255 }
2256
2257 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
2258 __FUNCTION__, listener.get());
2259
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002260 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08002261}
2262
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002263Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002264
2265 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002266 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
2267
2268 if (parameters == NULL) {
2269 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002270 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07002271 }
2272
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002273 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002274
2275 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002276 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07002277 // Error logged by caller
2278 return ret;
2279 }
2280
2281 String8 shimParamsString8 = shimParams.flatten();
2282 String16 shimParamsString16 = String16(shimParamsString8);
2283
2284 *parameters = shimParamsString16;
2285
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002286 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07002287}
2288
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002289Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
2290 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002291 ATRACE_CALL();
2292
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002293 const String8 id = String8(cameraId);
2294
2295 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002296
2297 switch (apiVersion) {
2298 case API_VERSION_1:
2299 case API_VERSION_2:
2300 break;
2301 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002302 String8 msg = String8::format("Unknown API version %d", apiVersion);
2303 ALOGE("%s: %s", __FUNCTION__, msg.string());
2304 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002305 }
2306
Emilian Peev28ad2ea2017-02-07 16:14:32 +00002307 int deviceVersion = getDeviceVersion(id);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002308 switch (deviceVersion) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002309 case CAMERA_DEVICE_API_VERSION_1_0:
2310 case CAMERA_DEVICE_API_VERSION_3_0:
2311 case CAMERA_DEVICE_API_VERSION_3_1:
2312 if (apiVersion == API_VERSION_2) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002313 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without shim",
2314 __FUNCTION__, id.string(), deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002315 *isSupported = false;
2316 } else { // if (apiVersion == API_VERSION_1) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002317 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always supported",
2318 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002319 *isSupported = true;
2320 }
2321 break;
2322 case CAMERA_DEVICE_API_VERSION_3_2:
2323 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -07002324 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002325 case CAMERA_DEVICE_API_VERSION_3_5:
Yin-Chia Yeh56d98ba2020-01-16 16:57:14 -08002326 case CAMERA_DEVICE_API_VERSION_3_6:
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002327 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
2328 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002329 *isSupported = true;
2330 break;
2331 case -1: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002332 String8 msg = String8::format("Unknown camera ID %s", id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002333 ALOGE("%s: %s", __FUNCTION__, msg.string());
2334 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002335 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002336 default: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002337 String8 msg = String8::format("Unknown device version %x for device %s",
2338 deviceVersion, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002339 ALOGE("%s: %s", __FUNCTION__, msg.string());
2340 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
2341 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07002342 }
2343
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002344 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002345}
2346
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002347Status CameraService::isHiddenPhysicalCamera(const String16& cameraId,
2348 /*out*/ bool *isSupported) {
2349 ATRACE_CALL();
2350
2351 const String8 id = String8(cameraId);
2352
2353 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
2354 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(id.string());
2355
2356 return Status::ok();
2357}
2358
Ruben Brunkcc776712015-02-17 20:18:47 -08002359void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002360 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002361 for (auto& i : mActiveClientManager.getAll()) {
2362 auto clientSp = i->getValue();
2363 if (clientSp.get() == client) {
2364 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08002365 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07002366 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002367 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08002368}
2369
Ruben Brunkcc776712015-02-17 20:18:47 -08002370bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002371 bool ret = false;
2372 {
2373 // Acquire mServiceLock and prevent other clients from connecting
2374 std::unique_ptr<AutoConditionLock> lock =
2375 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08002376
Igor Murashkin634a5152013-02-20 17:15:11 -08002377
Ruben Brunkcc776712015-02-17 20:18:47 -08002378 std::vector<sp<BasicClient>> evicted;
2379 for (auto& i : mActiveClientManager.getAll()) {
2380 auto clientSp = i->getValue();
2381 if (clientSp.get() == nullptr) {
2382 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2383 mActiveClientManager.remove(i);
2384 continue;
2385 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08002386 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002387 mActiveClientManager.remove(i);
2388 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08002389
Ruben Brunkcc776712015-02-17 20:18:47 -08002390 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002391 clientSp->notifyError(
2392 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002393 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08002394 }
2395 }
2396
Ruben Brunkcc776712015-02-17 20:18:47 -08002397 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2398 // other clients from connecting in mServiceLockWrapper if held
2399 mServiceLock.unlock();
2400
Ruben Brunk36597b22015-03-20 22:15:57 -07002401 // Do not clear caller identity, remote caller should be client proccess
2402
Ruben Brunkcc776712015-02-17 20:18:47 -08002403 for (auto& i : evicted) {
2404 if (i.get() != nullptr) {
2405 i->disconnect();
2406 ret = true;
2407 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002408 }
2409
Ruben Brunkcc776712015-02-17 20:18:47 -08002410 // Reacquire mServiceLock
2411 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08002412
Ruben Brunkcc776712015-02-17 20:18:47 -08002413 } // lock is destroyed, allow further connect calls
2414
2415 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07002416}
2417
Ruben Brunkcc776712015-02-17 20:18:47 -08002418std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
2419 const String8& cameraId) const {
2420 std::shared_ptr<CameraState> state;
2421 {
2422 Mutex::Autolock lock(mCameraStatesLock);
2423 auto iter = mCameraStates.find(cameraId);
2424 if (iter != mCameraStates.end()) {
2425 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002426 }
2427 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002428 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002429}
2430
Ruben Brunkcc776712015-02-17 20:18:47 -08002431sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
2432 // Remove from active clients list
2433 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
2434 if (clientDescriptorPtr == nullptr) {
2435 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
2436 cameraId.string());
2437 return sp<BasicClient>{nullptr};
2438 }
2439
2440 return clientDescriptorPtr->getValue();
Keun young Parkd8973a72012-03-28 14:13:09 -07002441}
2442
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002443void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07002444 // Acquire mServiceLock and prevent other clients from connecting
2445 std::unique_ptr<AutoConditionLock> lock =
2446 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
2447
Ruben Brunk6267b532015-04-30 17:44:07 -07002448 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002449 for (size_t i = 0; i < newUserIds.size(); i++) {
2450 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07002451 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002452 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07002453 return;
2454 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002455 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07002456 }
2457
Ruben Brunka8ca9152015-04-07 14:23:40 -07002458
Ruben Brunk6267b532015-04-30 17:44:07 -07002459 if (newAllowedUsers == mAllowedUsers) {
2460 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
2461 return;
2462 }
2463
2464 logUserSwitch(mAllowedUsers, newAllowedUsers);
2465
2466 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07002467
2468 // Current user has switched, evict all current clients.
2469 std::vector<sp<BasicClient>> evicted;
2470 for (auto& i : mActiveClientManager.getAll()) {
2471 auto clientSp = i->getValue();
2472
2473 if (clientSp.get() == nullptr) {
2474 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2475 continue;
2476 }
2477
Ruben Brunk6267b532015-04-30 17:44:07 -07002478 // Don't evict clients that are still allowed.
2479 uid_t clientUid = clientSp->getClientUid();
2480 userid_t clientUserId = multiuser_get_user_id(clientUid);
2481 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
2482 continue;
2483 }
2484
Ruben Brunk36597b22015-03-20 22:15:57 -07002485 evicted.push_back(clientSp);
2486
2487 String8 curTime = getFormattedCurrentTime();
2488
2489 ALOGE("Evicting conflicting client for camera ID %s due to user change",
2490 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07002491
Ruben Brunk36597b22015-03-20 22:15:57 -07002492 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002493 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00002494 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
2495 " to user switch.", i->getKey().string(),
2496 String8{clientSp->getPackageName()}.string(),
2497 i->getOwnerId(), i->getPriority().getScore(),
2498 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07002499
2500 }
2501
2502 // Do not hold mServiceLock while disconnecting clients, but retain the condition
2503 // blocking other clients from connecting in mServiceLockWrapper if held.
2504 mServiceLock.unlock();
2505
2506 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07002507 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07002508
2509 for (auto& i : evicted) {
2510 i->disconnect();
2511 }
2512
Jayant Chowdhary12361932018-08-27 14:46:13 -07002513 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07002514
2515 // Reacquire mServiceLock
2516 mServiceLock.lock();
2517}
Ruben Brunkcc776712015-02-17 20:18:47 -08002518
Ruben Brunka8ca9152015-04-07 14:23:40 -07002519void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002520 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07002521 Mutex::Autolock l(mLogLock);
2522 mEventLog.add(String8::format("%s : %s", curTime.string(), event));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002523}
2524
Ruben Brunka8ca9152015-04-07 14:23:40 -07002525void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002526 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002527 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002528 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002529 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002530}
2531
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002532void CameraService::logDisconnectedOffline(const char* cameraId, int clientPid,
2533 const char* clientPackage) {
2534 // Log the clients evicted
2535 logEvent(String8::format("DISCONNECT offline device %s client for package %s (PID %d)",
2536 cameraId, clientPackage, clientPid));
2537}
2538
Ruben Brunka8ca9152015-04-07 14:23:40 -07002539void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002540 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002541 // Log the clients evicted
2542 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002543 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002544}
2545
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002546void CameraService::logConnectedOffline(const char* cameraId, int clientPid,
2547 const char* clientPackage) {
2548 // Log the clients evicted
2549 logEvent(String8::format("CONNECT offline device %s client for package %s (PID %d)", cameraId,
2550 clientPackage, clientPid));
2551}
2552
Ruben Brunka8ca9152015-04-07 14:23:40 -07002553void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002554 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002555 // Log the client rejected
2556 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002557 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002558}
2559
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002560void CameraService::logTorchEvent(const char* cameraId, const char *torchState, int clientPid) {
2561 // Log torch event
2562 logEvent(String8::format("Torch for camera id %s turned %s for client PID %d", cameraId,
2563 torchState, clientPid));
2564}
2565
Ruben Brunk6267b532015-04-30 17:44:07 -07002566void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
2567 const std::set<userid_t>& newUserIds) {
2568 String8 newUsers = toString(newUserIds);
2569 String8 oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002570 if (oldUsers.size() == 0) {
2571 oldUsers = "<None>";
2572 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07002573 // Log the new and old users
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002574 logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
Ruben Brunk6267b532015-04-30 17:44:07 -07002575 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002576}
2577
2578void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
2579 // Log the device removal
2580 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
2581}
2582
2583void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
2584 // Log the device removal
2585 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
2586}
2587
2588void CameraService::logClientDied(int clientPid, const char* reason) {
2589 // Log the device removal
2590 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07002591}
2592
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002593void CameraService::logServiceError(const char* msg, int errorCode) {
2594 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002595 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002596}
2597
Ruben Brunk36597b22015-03-20 22:15:57 -07002598status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
2599 uint32_t flags) {
2600
Mathias Agopian65ab4712010-07-14 17:59:35 -07002601 // Permission checks
2602 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002603 case SHELL_COMMAND_TRANSACTION: {
2604 int in = data.readFileDescriptor();
2605 int out = data.readFileDescriptor();
2606 int err = data.readFileDescriptor();
2607 int argc = data.readInt32();
2608 Vector<String16> args;
2609 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
2610 args.add(data.readString16());
2611 }
2612 sp<IBinder> unusedCallback;
2613 sp<IResultReceiver> resultReceiver;
2614 status_t status;
2615 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
2616 return status;
2617 }
2618 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
2619 return status;
2620 }
2621 status = shellCommand(in, out, err, args);
2622 if (resultReceiver != nullptr) {
2623 resultReceiver->send(status);
2624 }
2625 return NO_ERROR;
2626 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002627 }
2628
2629 return BnCameraService::onTransact(code, data, reply, flags);
2630}
2631
Mathias Agopian65ab4712010-07-14 17:59:35 -07002632// We share the media players for shutter and recording sound for all clients.
2633// A reference count is kept to determine when we will actually release the
2634// media players.
2635
Jaekyun Seokef498052018-03-23 13:09:44 +09002636sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
2637 sp<MediaPlayer> mp = new MediaPlayer();
2638 status_t error;
2639 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08002640 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09002641 error = mp->prepare();
2642 }
2643 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00002644 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09002645 mp->disconnect();
2646 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002647 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002648 }
2649 return mp;
2650}
2651
username5755fea2018-12-27 09:48:08 +08002652void CameraService::increaseSoundRef() {
2653 Mutex::Autolock lock(mSoundLock);
2654 mSoundRef++;
2655}
2656
2657void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002658 ATRACE_CALL();
2659
username5755fea2018-12-27 09:48:08 +08002660 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
2661 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
2662 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
2663 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
2664 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
2665 }
2666 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
2667 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
2668 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
2669 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002670 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08002671 }
2672 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
2673 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
2674 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
2675 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
2676 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002677 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002678}
2679
username5755fea2018-12-27 09:48:08 +08002680void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002681 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002682 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002683 if (--mSoundRef) return;
2684
2685 for (int i = 0; i < NUM_SOUNDS; i++) {
2686 if (mSoundPlayer[i] != 0) {
2687 mSoundPlayer[i]->disconnect();
2688 mSoundPlayer[i].clear();
2689 }
2690 }
2691}
2692
2693void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002694 ATRACE_CALL();
2695
Mathias Agopian65ab4712010-07-14 17:59:35 -07002696 LOG1("playSound(%d)", kind);
2697 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002698 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002699 sp<MediaPlayer> player = mSoundPlayer[kind];
2700 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08002701 player->seekTo(0);
2702 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002703 }
2704}
2705
2706// ----------------------------------------------------------------------------
2707
2708CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07002709 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002710 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09002711 const std::optional<String16>& clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002712 const String8& cameraIdStr,
2713 int api1CameraId, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002714 int clientPid, uid_t clientUid,
2715 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002716 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08002717 IInterface::asBinder(cameraClient),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002718 clientPackageName, clientFeatureId,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002719 cameraIdStr, cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002720 clientPid, clientUid,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002721 servicePid),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002722 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08002723{
Jayant Chowdhary12361932018-08-27 14:46:13 -07002724 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002725 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002726
Igor Murashkin44cfcf02013-03-01 16:22:28 -08002727 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002728
username5755fea2018-12-27 09:48:08 +08002729 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002730
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002731 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002732}
2733
Mathias Agopian65ab4712010-07-14 17:59:35 -07002734// tear down the client
2735CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002736 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08002737 mDestructionStarted = true;
2738
username5755fea2018-12-27 09:48:08 +08002739 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002740 // unconditionally disconnect. function is idempotent
2741 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002742}
2743
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002744sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
2745
Igor Murashkin634a5152013-02-20 17:15:11 -08002746CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002747 const sp<IBinder>& remoteCallback,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09002748 const String16& clientPackageName, const std::optional<String16>& clientFeatureId,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002749 const String8& cameraIdStr, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002750 int clientPid, uid_t clientUid,
2751 int servicePid):
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002752 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing),
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09002753 mClientPackageName(clientPackageName), mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002754 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002755 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07002756 mDisconnected(false), mUidIsTrusted(false),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002757 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002758 mRemoteBinder(remoteCallback)
Igor Murashkin634a5152013-02-20 17:15:11 -08002759{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002760 if (sCameraService == nullptr) {
2761 sCameraService = cameraService;
2762 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002763 mOpsActive = false;
Igor Murashkin634a5152013-02-20 17:15:11 -08002764 mDestructionStarted = false;
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08002765
2766 // In some cases the calling code has no access to the package it runs under.
2767 // For example, NDK camera API.
2768 // In this case we will get the packages for the calling UID and pick the first one
2769 // for attributing the app op. This will work correctly for runtime permissions
2770 // as for legacy apps we will toggle the app op for all packages in the UID.
2771 // The caveat is that the operation may be attributed to the wrong package and
2772 // stats based on app ops may be slightly off.
2773 if (mClientPackageName.size() <= 0) {
2774 sp<IServiceManager> sm = defaultServiceManager();
2775 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
2776 if (binder == 0) {
2777 ALOGE("Cannot get permission service");
2778 // Leave mClientPackageName unchanged (empty) and the further interaction
2779 // with camera will fail in BasicClient::startCameraOps
2780 return;
2781 }
2782
2783 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
2784 Vector<String16> packages;
2785
2786 permCtrl->getPackagesForUid(mClientUid, packages);
2787
2788 if (packages.isEmpty()) {
2789 ALOGE("No packages for calling UID");
2790 // Leave mClientPackageName unchanged (empty) and the further interaction
2791 // with camera will fail in BasicClient::startCameraOps
2792 return;
2793 }
2794 mClientPackageName = packages[0];
2795 }
Steven Moreland89a2c5c2020-01-31 15:02:25 -08002796 if (getCurrentServingCall() != BinderCallType::HWBINDER) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002797 mAppOpsManager = std::make_unique<AppOpsManager>();
2798 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07002799
2800 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08002801}
2802
2803CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002804 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08002805 mDestructionStarted = true;
2806}
2807
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002808binder::Status CameraService::BasicClient::disconnect() {
2809 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002810 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002811 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07002812 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07002813 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002814
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002815 sCameraService->removeByClient(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002816 sCameraService->logDisconnected(mCameraIdStr, mClientPid, String8(mClientPackageName));
Peter Kalauskasa29c1352018-10-10 12:05:42 -07002817 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
2818 mCameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002819
2820 sp<IBinder> remote = getRemote();
2821 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002822 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08002823 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002824
2825 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07002826 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002827 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
2828 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
2829 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002830
Igor Murashkincba2c162013-03-20 15:56:31 -07002831 // client shouldn't be able to call into us anymore
2832 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002833
2834 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08002835}
2836
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002837status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
2838 // No dumping of clients directly over Binder,
2839 // must go through CameraService::dump
2840 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07002841 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002842 return OK;
2843}
2844
Ruben Brunkcc776712015-02-17 20:18:47 -08002845String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002846 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08002847}
2848
2849
2850int CameraService::BasicClient::getClientPid() const {
2851 return mClientPid;
2852}
2853
Ruben Brunk6267b532015-04-30 17:44:07 -07002854uid_t CameraService::BasicClient::getClientUid() const {
2855 return mClientUid;
2856}
2857
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002858bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
2859 // Defaults to API2.
2860 return level == API_2;
2861}
2862
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002863status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002864 {
2865 Mutex::Autolock l(mAudioRestrictionLock);
2866 mAudioRestriction = mode;
2867 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002868 sCameraService->updateAudioRestriction();
2869 return OK;
2870}
2871
2872int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002873 return sCameraService->updateAudioRestriction();
2874}
2875
2876int32_t CameraService::BasicClient::getAudioRestriction() const {
2877 Mutex::Autolock l(mAudioRestrictionLock);
2878 return mAudioRestriction;
2879}
2880
2881bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
2882 switch (mode) {
2883 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
2884 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
2885 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
2886 return true;
2887 default:
2888 return false;
2889 }
2890}
2891
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002892status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002893 ATRACE_CALL();
2894
Igor Murashkine6800ce2013-03-04 17:25:57 -08002895 {
2896 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002897 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08002898 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002899 if (mAppOpsManager != nullptr) {
2900 // Notify app ops that the camera is not available
2901 mOpsCallback = new OpsCallback(this);
2902 int32_t res;
2903 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
2904 mClientPackageName, mOpsCallback);
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002905 res = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
2906 mClientPackageName, /*startIfModeDefault*/ false, mClientFeatureId,
2907 String16("start camera ") + String16(mCameraIdStr));
Igor Murashkine6800ce2013-03-04 17:25:57 -08002908
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002909 if (res == AppOpsManager::MODE_ERRORED) {
2910 ALOGI("Camera %s: Access for \"%s\" has been revoked",
2911 mCameraIdStr.string(), String8(mClientPackageName).string());
2912 return PERMISSION_DENIED;
2913 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002914
Shuzhen Wang2c656792020-04-13 17:36:49 -07002915 // If the calling Uid is trusted (a native service), the AppOpsManager could
2916 // return MODE_IGNORED. Do not treat such case as error.
2917 if (!mUidIsTrusted && res == AppOpsManager::MODE_IGNORED) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002918 ALOGI("Camera %s: Access for \"%s\" has been restricted",
2919 mCameraIdStr.string(), String8(mClientPackageName).string());
2920 // Return the same error as for device policy manager rejection
2921 return -EACCES;
2922 }
Svetoslav28e8ef72015-05-11 19:21:31 -07002923 }
2924
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002925 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002926
2927 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002928 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002929
Emilian Peev573291c2018-02-10 02:10:56 +00002930 int apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_1;
2931 if (canCastToApiClient(API_2)) {
2932 apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_2;
2933 }
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002934 // Transition device state to OPEN
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002935 sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_OPEN,
Emilian Peev573291c2018-02-10 02:10:56 +00002936 mCameraIdStr, mCameraFacing, mClientPackageName, apiLevel);
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002937
Emilian Peev53722fa2019-02-22 17:47:20 -08002938 sCameraService->mUidPolicy->registerMonitorUid(mClientUid);
2939
Shuzhen Wang695044d2020-03-06 09:02:23 -08002940 // Notify listeners of camera open/close status
2941 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
2942
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002943 return OK;
2944}
2945
2946status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002947 ATRACE_CALL();
2948
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002949 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002950 if (mOpsActive) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002951 // Notify app ops that the camera is available again
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002952 if (mAppOpsManager != nullptr) {
2953 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002954 mClientPackageName, mClientFeatureId);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002955 mOpsActive = false;
2956 }
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002957 // This function is called when a client disconnects. This should
2958 // release the camera, but actually only if it was in a proper
2959 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002960 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002961 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002962
Ruben Brunkcc776712015-02-17 20:18:47 -08002963 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002964 sCameraService->updateStatus(StatusInternal::PRESENT,
2965 mCameraIdStr, rejected);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002966
Emilian Peev573291c2018-02-10 02:10:56 +00002967 int apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_1;
2968 if (canCastToApiClient(API_2)) {
2969 apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_2;
2970 }
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002971 // Transition device state to CLOSED
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002972 sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_CLOSED,
Emilian Peev573291c2018-02-10 02:10:56 +00002973 mCameraIdStr, mCameraFacing, mClientPackageName, apiLevel);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002974 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002975 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002976 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
2977 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002978 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002979 mOpsCallback.clear();
2980
Emilian Peev53722fa2019-02-22 17:47:20 -08002981 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid);
2982
Shuzhen Wang695044d2020-03-06 09:02:23 -08002983 // Notify listeners of camera open/close status
2984 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
2985
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002986 return OK;
2987}
2988
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002989void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002990 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002991 if (mAppOpsManager == nullptr) {
2992 return;
2993 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002994 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002995 if (op != AppOpsManager::OP_CAMERA) {
2996 ALOGW("Unexpected app ops notification received: %d", op);
2997 return;
2998 }
2999
3000 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003001 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003002 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003003 ALOGV("checkOp returns: %d, %s ", res,
3004 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
3005 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
3006 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
3007 "UNKNOWN");
3008
3009 if (res != AppOpsManager::MODE_ALLOWED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003010 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003011 String8(mClientPackageName).string());
Svet Ganova453d0d2018-01-11 15:37:58 -08003012 block();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003013 }
3014}
3015
Svet Ganova453d0d2018-01-11 15:37:58 -08003016void CameraService::BasicClient::block() {
3017 ATRACE_CALL();
3018
3019 // Reset the client PID to allow server-initiated disconnect,
3020 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003021 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08003022 CaptureResultExtras resultExtras; // a dummy result (invalid)
3023 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
3024 disconnect();
3025}
3026
Mathias Agopian65ab4712010-07-14 17:59:35 -07003027// ----------------------------------------------------------------------------
3028
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003029void CameraService::Client::notifyError(int32_t errorCode,
Jianing Weicb0652e2014-03-12 18:29:36 -07003030 const CaptureResultExtras& resultExtras) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08003031 (void) resultExtras;
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003032 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07003033 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
3034 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
3035 api1ErrorCode = CAMERA_ERROR_DISABLED;
3036 }
3037 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003038 } else {
3039 ALOGE("mRemoteCallback is NULL!!");
3040 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003041}
3042
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003043// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003044binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003045 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003046 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08003047}
3048
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003049bool CameraService::Client::canCastToApiClient(apiLevel level) const {
3050 return level == API_1;
3051}
3052
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003053CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
3054 mClient(client) {
3055}
3056
3057void CameraService::Client::OpsCallback::opChanged(int32_t op,
3058 const String16& packageName) {
3059 sp<BasicClient> client = mClient.promote();
3060 if (client != NULL) {
3061 client->opChanged(op, packageName);
3062 }
3063}
3064
Mathias Agopian65ab4712010-07-14 17:59:35 -07003065// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08003066// UidPolicy
3067// ----------------------------------------------------------------------------
3068
3069void CameraService::UidPolicy::registerSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003070 Mutex::Autolock _l(mUidLock);
3071
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003072 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07003073 status_t res = mAm.linkToDeath(this);
3074 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08003075 | ActivityManager::UID_OBSERVER_IDLE
Emilian Peev53722fa2019-02-22 17:47:20 -08003076 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganova453d0d2018-01-11 15:37:58 -08003077 ActivityManager::PROCESS_STATE_UNKNOWN,
3078 String16("cameraserver"));
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003079 if (res == OK) {
3080 mRegistered = true;
3081 ALOGV("UidPolicy: Registered with ActivityManager");
3082 }
Svet Ganova453d0d2018-01-11 15:37:58 -08003083}
3084
3085void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003086 Mutex::Autolock _l(mUidLock);
3087
Steven Moreland2f348142019-07-02 15:59:07 -07003088 mAm.unregisterUidObserver(this);
3089 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003090 mRegistered = false;
3091 mActiveUids.clear();
3092 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08003093}
3094
3095void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
3096 onUidIdle(uid, disabled);
3097}
3098
3099void CameraService::UidPolicy::onUidActive(uid_t uid) {
3100 Mutex::Autolock _l(mUidLock);
3101 mActiveUids.insert(uid);
3102}
3103
3104void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
3105 bool deleted = false;
3106 {
3107 Mutex::Autolock _l(mUidLock);
3108 if (mActiveUids.erase(uid) > 0) {
3109 deleted = true;
3110 }
3111 }
3112 if (deleted) {
3113 sp<CameraService> service = mService.promote();
3114 if (service != nullptr) {
3115 service->blockClientsForUid(uid);
3116 }
3117 }
3118}
3119
Emilian Peev53722fa2019-02-22 17:47:20 -08003120void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07003121 int64_t procStateSeq __unused, int32_t capability __unused) {
Emilian Peev53722fa2019-02-22 17:47:20 -08003122 bool procStateChange = false;
3123 {
3124 Mutex::Autolock _l(mUidLock);
3125 if ((mMonitoredUids.find(uid) != mMonitoredUids.end()) &&
3126 (mMonitoredUids[uid].first != procState)) {
3127 mMonitoredUids[uid].first = procState;
3128 procStateChange = true;
3129 }
3130 }
3131
3132 if (procStateChange) {
3133 sp<CameraService> service = mService.promote();
3134 if (service != nullptr) {
3135 service->notifyMonitoredUids();
3136 }
3137 }
3138}
3139
3140void CameraService::UidPolicy::registerMonitorUid(uid_t uid) {
3141 Mutex::Autolock _l(mUidLock);
3142 auto it = mMonitoredUids.find(uid);
3143 if (it != mMonitoredUids.end()) {
3144 it->second.second++;
3145 } else {
3146 mMonitoredUids.emplace(
3147 std::pair<uid_t, std::pair<int32_t, size_t>> (uid,
3148 std::pair<int32_t, size_t> (ActivityManager::PROCESS_STATE_NONEXISTENT, 1)));
3149 }
3150}
3151
3152void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid) {
3153 Mutex::Autolock _l(mUidLock);
3154 auto it = mMonitoredUids.find(uid);
3155 if (it != mMonitoredUids.end()) {
3156 it->second.second--;
3157 if (it->second.second == 0) {
3158 mMonitoredUids.erase(it);
3159 }
3160 } else {
3161 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
3162 }
3163}
3164
Svet Ganov7b4ab782018-03-25 12:48:10 -07003165bool CameraService::UidPolicy::isUidActive(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003166 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003167 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003168}
3169
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003170static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
3171static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003172
Svet Ganov7b4ab782018-03-25 12:48:10 -07003173bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003174 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003175 // If activity manager is unreachable, assume everything is active
3176 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003177 return true;
3178 }
3179 auto it = mOverrideUids.find(uid);
3180 if (it != mOverrideUids.end()) {
3181 return it->second;
3182 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003183 bool active = mActiveUids.find(uid) != mActiveUids.end();
3184 if (!active) {
3185 // We want active UIDs to always access camera with their first attempt since
3186 // there is no guarantee the app is robustly written and would retry getting
3187 // the camera on failure. The inverse case is not a problem as we would take
3188 // camera away soon once we get the callback that the uid is no longer active.
3189 ActivityManager am;
3190 // Okay to access with a lock held as UID changes are dispatched without
3191 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07003192 int64_t startTimeMillis = 0;
3193 do {
3194 // TODO: Fix this b/109950150!
3195 // Okay this is a hack. There is a race between the UID turning active and
3196 // activity being resumed. The proper fix is very risky, so we temporary add
3197 // some polling which should happen pretty rarely anyway as the race is hard
3198 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003199 active = mActiveUids.find(uid) != mActiveUids.end();
Hui Yu12c7ec72020-05-04 17:40:52 +00003200 if (!active) active = am.isUidActive(uid, callingPackage);
Svet Ganov94ec46f2018-06-08 15:03:46 -07003201 if (active) {
3202 break;
3203 }
3204 if (startTimeMillis <= 0) {
3205 startTimeMillis = uptimeMillis();
3206 }
3207 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003208 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003209 if (remainingTimeMillis <= 0) {
3210 break;
3211 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003212 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
3213
3214 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003215 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003216 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003217 } while (true);
3218
Svet Ganov7b4ab782018-03-25 12:48:10 -07003219 if (active) {
3220 // Now that we found out the UID is actually active, cache that
3221 mActiveUids.insert(uid);
3222 }
3223 }
3224 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08003225}
3226
Varun Shahb42f1eb2019-04-16 14:45:13 -07003227int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
3228 Mutex::Autolock _l(mUidLock);
3229 return getProcStateLocked(uid);
3230}
3231
3232int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
3233 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
3234 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
3235 procState = mMonitoredUids[uid].first;
3236 }
3237 return procState;
3238}
3239
Svet Ganov7b4ab782018-03-25 12:48:10 -07003240void CameraService::UidPolicy::UidPolicy::addOverrideUid(uid_t uid,
3241 String16 callingPackage, bool active) {
3242 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08003243}
3244
Svet Ganov7b4ab782018-03-25 12:48:10 -07003245void CameraService::UidPolicy::removeOverrideUid(uid_t uid, String16 callingPackage) {
3246 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08003247}
3248
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003249void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
3250 Mutex::Autolock _l(mUidLock);
3251 ALOGV("UidPolicy: ActivityManager has died");
3252 mRegistered = false;
3253 mActiveUids.clear();
3254}
3255
Svet Ganov7b4ab782018-03-25 12:48:10 -07003256void CameraService::UidPolicy::updateOverrideUid(uid_t uid, String16 callingPackage,
3257 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003258 bool wasActive = false;
3259 bool isActive = false;
3260 {
3261 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003262 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003263 mOverrideUids.erase(uid);
3264 if (insert) {
3265 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
3266 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003267 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003268 }
3269 if (wasActive != isActive && !isActive) {
3270 sp<CameraService> service = mService.promote();
3271 if (service != nullptr) {
3272 service->blockClientsForUid(uid);
3273 }
3274 }
3275}
3276
3277// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08003278// SensorPrivacyPolicy
3279// ----------------------------------------------------------------------------
3280void CameraService::SensorPrivacyPolicy::registerSelf() {
3281 Mutex::Autolock _l(mSensorPrivacyLock);
3282 if (mRegistered) {
3283 return;
3284 }
Steven Moreland3cf67172020-01-29 11:44:22 -08003285 mSpm.addSensorPrivacyListener(this);
3286 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
3287 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003288 if (res == OK) {
3289 mRegistered = true;
3290 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
3291 }
3292}
3293
3294void CameraService::SensorPrivacyPolicy::unregisterSelf() {
3295 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08003296 mSpm.removeSensorPrivacyListener(this);
3297 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003298 mRegistered = false;
3299 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
3300}
3301
3302bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
3303 Mutex::Autolock _l(mSensorPrivacyLock);
3304 return mSensorPrivacyEnabled;
3305}
3306
3307binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
3308 {
3309 Mutex::Autolock _l(mSensorPrivacyLock);
3310 mSensorPrivacyEnabled = enabled;
3311 }
3312 // if sensor privacy is enabled then block all clients from accessing the camera
3313 if (enabled) {
3314 sp<CameraService> service = mService.promote();
3315 if (service != nullptr) {
3316 service->blockAllClients();
3317 }
3318 }
3319 return binder::Status::ok();
3320}
3321
3322void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
3323 Mutex::Autolock _l(mSensorPrivacyLock);
3324 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
3325 mRegistered = false;
3326}
3327
3328// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003329// CameraState
3330// ----------------------------------------------------------------------------
3331
3332CameraService::CameraState::CameraState(const String8& id, int cost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003333 const std::set<String8>& conflicting, SystemCameraKind systemCameraKind) : mId(id),
3334 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
3335 mSystemCameraKind(systemCameraKind) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08003336
3337CameraService::CameraState::~CameraState() {}
3338
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003339CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003340 Mutex::Autolock lock(mStatusLock);
3341 return mStatus;
3342}
3343
Shuzhen Wang43858162020-01-10 13:42:15 -08003344std::vector<String8> CameraService::CameraState::getUnavailablePhysicalIds() const {
3345 Mutex::Autolock lock(mStatusLock);
3346 std::vector<String8> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
3347 return res;
3348}
3349
Ruben Brunkcc776712015-02-17 20:18:47 -08003350CameraParameters CameraService::CameraState::getShimParams() const {
3351 return mShimParams;
3352}
3353
3354void CameraService::CameraState::setShimParams(const CameraParameters& params) {
3355 mShimParams = params;
3356}
3357
3358int CameraService::CameraState::getCost() const {
3359 return mCost;
3360}
3361
3362std::set<String8> CameraService::CameraState::getConflicting() const {
3363 return mConflicting;
3364}
3365
3366String8 CameraService::CameraState::getId() const {
3367 return mId;
3368}
3369
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003370SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
3371 return mSystemCameraKind;
3372}
3373
Shuzhen Wang43858162020-01-10 13:42:15 -08003374bool CameraService::CameraState::addUnavailablePhysicalId(const String8& physicalId) {
3375 Mutex::Autolock lock(mStatusLock);
3376 auto result = mUnavailablePhysicalIds.insert(physicalId);
3377 return result.second;
3378}
3379
3380bool CameraService::CameraState::removeUnavailablePhysicalId(const String8& physicalId) {
3381 Mutex::Autolock lock(mStatusLock);
3382 auto count = mUnavailablePhysicalIds.erase(physicalId);
3383 return count > 0;
3384}
3385
Ruben Brunkcc776712015-02-17 20:18:47 -08003386// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07003387// ClientEventListener
3388// ----------------------------------------------------------------------------
3389
3390void CameraService::ClientEventListener::onClientAdded(
3391 const resource_policy::ClientDescriptor<String8,
3392 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003393 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003394 if (basicClient.get() != nullptr) {
3395 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3396 notifier.noteStartCamera(descriptor.getKey(),
3397 static_cast<int>(basicClient->getClientUid()));
3398 }
3399}
3400
3401void CameraService::ClientEventListener::onClientRemoved(
3402 const resource_policy::ClientDescriptor<String8,
3403 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003404 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003405 if (basicClient.get() != nullptr) {
3406 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3407 notifier.noteStopCamera(descriptor.getKey(),
3408 static_cast<int>(basicClient->getClientUid()));
3409 }
3410}
3411
3412
3413// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003414// CameraClientManager
3415// ----------------------------------------------------------------------------
3416
Ruben Brunk99e69712015-05-26 17:25:07 -07003417CameraService::CameraClientManager::CameraClientManager() {
3418 setListener(std::make_shared<ClientEventListener>());
3419}
3420
Ruben Brunkcc776712015-02-17 20:18:47 -08003421CameraService::CameraClientManager::~CameraClientManager() {}
3422
3423sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
3424 const String8& id) const {
3425 auto descriptor = get(id);
3426 if (descriptor == nullptr) {
3427 return sp<BasicClient>{nullptr};
3428 }
3429 return descriptor->getValue();
3430}
3431
3432String8 CameraService::CameraClientManager::toString() const {
3433 auto all = getAll();
3434 String8 ret("[");
3435 bool hasAny = false;
3436 for (auto& i : all) {
3437 hasAny = true;
3438 String8 key = i->getKey();
3439 int32_t cost = i->getCost();
3440 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00003441 int32_t score = i->getPriority().getScore();
3442 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08003443 auto conflicting = i->getConflicting();
3444 auto clientSp = i->getValue();
3445 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07003446 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08003447 if (clientSp.get() != nullptr) {
3448 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07003449 uid_t clientUid = clientSp->getClientUid();
3450 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003451 }
Emilian Peev8131a262017-02-01 12:33:43 +00003452 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
3453 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08003454
Ruben Brunk6267b532015-04-30 17:44:07 -07003455 if (clientSp.get() != nullptr) {
3456 ret.appendFormat("User Id: %d, ", clientUserId);
3457 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003458 if (packageName.size() != 0) {
3459 ret.appendFormat("Client Package Name: %s", packageName.string());
3460 }
3461
3462 ret.append(", Conflicting Client Devices: {");
3463 for (auto& j : conflicting) {
3464 ret.appendFormat("%s, ", j.string());
3465 }
3466 ret.append("})");
3467 }
3468 if (hasAny) ret.append("\n");
3469 ret.append("]\n");
3470 return ret;
3471}
3472
3473CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3474 const String8& key, const sp<BasicClient>& value, int32_t cost,
Emilian Peev8131a262017-02-01 12:33:43 +00003475 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
3476 int32_t state) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003477
Steven Moreland89a2c5c2020-01-31 15:02:25 -08003478 bool isVendorClient = getCurrentServingCall() == BinderCallType::HWBINDER;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003479 int32_t score_adj = isVendorClient ? kVendorClientScore : score;
3480 int32_t state_adj = isVendorClient ? kVendorClientState: state;
3481
Ruben Brunkcc776712015-02-17 20:18:47 -08003482 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003483 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj, isVendorClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08003484}
3485
3486CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3487 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
3488 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00003489 partial->getConflicting(), partial->getPriority().getScore(),
3490 partial->getOwnerId(), partial->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08003491}
3492
3493// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07003494
3495static const int kDumpLockRetries = 50;
3496static const int kDumpLockSleep = 60000;
3497
3498static bool tryLock(Mutex& mutex)
3499{
3500 bool locked = false;
3501 for (int i = 0; i < kDumpLockRetries; ++i) {
3502 if (mutex.tryLock() == NO_ERROR) {
3503 locked = true;
3504 break;
3505 }
3506 usleep(kDumpLockSleep);
3507 }
3508 return locked;
3509}
3510
3511status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003512 ATRACE_CALL();
3513
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003514 if (checkCallingPermission(sDumpPermission) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003515 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07003516 CameraThreadState::getCallingPid(),
3517 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003518 return NO_ERROR;
3519 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003520 bool locked = tryLock(mServiceLock);
3521 // failed to lock - CameraService is probably deadlocked
3522 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003523 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003524 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003525
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003526 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003527 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07003528
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003529 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003530 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08003531
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003532 if (locked) mServiceLock.unlock();
3533 return NO_ERROR;
3534 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003535 dprintf(fd, "\n== Service global info: ==\n\n");
3536 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003537 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07003538 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
3539 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003540 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
3541 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
3542 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003543 String8 activeClientString = mActiveClientManager.toString();
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003544 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
3545 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003546
3547 dumpEventLog(fd);
3548
3549 bool stateLocked = tryLock(mCameraStatesLock);
3550 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003551 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003552 }
3553
Emilian Peevbd8c5032018-02-14 23:05:40 +00003554 int argSize = args.size();
3555 for (int i = 0; i < argSize; i++) {
3556 if (args[i] == TagMonitor::kMonitorOption) {
3557 if (i + 1 < argSize) {
3558 mMonitorTags = String8(args[i + 1]);
3559 }
3560 break;
3561 }
3562 }
3563
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003564 for (auto& state : mCameraStates) {
3565 String8 cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003566
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003567 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003568
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003569 CameraParameters p = state.second->getShimParams();
3570 if (!p.isEmpty()) {
3571 dprintf(fd, " Camera1 API shim is using parameters:\n ");
3572 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003573 }
3574
3575 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08003576 if (clientDescriptor != nullptr) {
3577 dprintf(fd, " Device %s is open. Client instance dump:\n",
3578 cameraId.string());
3579 dprintf(fd, " Client priority score: %d state: %d\n",
3580 clientDescriptor->getPriority().getScore(),
3581 clientDescriptor->getPriority().getState());
3582 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
3583
3584 auto client = clientDescriptor->getValue();
3585 dprintf(fd, " Client package: %s\n",
3586 String8(client->getPackageName()).string());
3587
3588 client->dumpClient(fd, args);
3589 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003590 dprintf(fd, " Device %s is closed, no client instance\n",
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003591 cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003592 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003593
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003594 }
3595
3596 if (stateLocked) mCameraStatesLock.unlock();
3597
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003598 if (locked) mServiceLock.unlock();
3599
Emilian Peevf53f66e2017-04-11 14:29:43 +01003600 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003601
3602 dprintf(fd, "\n== Vendor tags: ==\n\n");
3603
3604 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
3605 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00003606 sp<VendorTagDescriptorCache> cache =
3607 VendorTagDescriptorCache::getGlobalVendorTagCache();
3608 if (cache == NULL) {
3609 dprintf(fd, "No vendor tags.\n");
3610 } else {
3611 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
3612 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003613 } else {
3614 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
3615 }
3616
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003617 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003618 dprintf(fd, "\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003619 camera3::CameraTraces::dump(fd, args);
3620
3621 // Process dump arguments, if any
3622 int n = args.size();
3623 String16 verboseOption("-v");
3624 String16 unreachableOption("--unreachable");
3625 for (int i = 0; i < n; i++) {
3626 if (args[i] == verboseOption) {
3627 // change logging level
3628 if (i + 1 >= n) continue;
3629 String8 levelStr(args[i+1]);
3630 int level = atoi(levelStr.string());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003631 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003632 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003633 } else if (args[i] == unreachableOption) {
3634 // Dump memory analysis
3635 // TODO - should limit be an argument parameter?
3636 UnreachableMemoryInfo info;
3637 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
3638 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003639 dprintf(fd, "\n== Unable to dump unreachable memory. "
3640 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003641 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003642 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003643 std::string s = info.ToString(/*log_contents*/ true);
3644 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003645 }
3646 }
3647 }
3648 return NO_ERROR;
3649}
3650
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003651void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003652 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003653
3654 Mutex::Autolock l(mLogLock);
3655 for (const auto& msg : mEventLog) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003656 dprintf(fd, " %s\n", msg.string());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003657 }
3658
3659 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003660 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003661 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003662 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003663 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003664 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003665}
3666
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003667void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003668 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003669 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
3670 if (mTorchClientMap[i] == who) {
3671 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003672 String8 cameraId = mTorchClientMap.keyAt(i);
3673 status_t res = mFlashlight->setTorchMode(cameraId, false);
3674 if (res) {
3675 ALOGE("%s: torch client died but couldn't turn off torch: "
3676 "%s (%d)", __FUNCTION__, strerror(-res), res);
3677 return;
3678 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003679 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003680 break;
3681 }
3682 }
3683}
3684
Ruben Brunkcc776712015-02-17 20:18:47 -08003685/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003686
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003687 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07003688 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
3689 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003690 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003691 // PID here is approximate and can be wrong.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003692 logClientDied(CameraThreadState::getCallingPid(), String8("Binder died unexpectedly"));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003693
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003694 // check torch client
3695 handleTorchClientBinderDied(who);
3696
3697 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08003698 if(!evictClientIdByRemote(who)) {
3699 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003700 return;
3701 }
3702
Ruben Brunkcc776712015-02-17 20:18:47 -08003703 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
3704 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003705}
3706
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003707void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003708 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08003709}
3710
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003711void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
3712 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003713 // Do not lock mServiceLock here or can get into a deadlock from
3714 // connect() -> disconnect -> updateStatus
3715
3716 auto state = getCameraState(cameraId);
3717
3718 if (state == nullptr) {
3719 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
3720 cameraId.string());
3721 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07003722 }
3723
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003724 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
3725 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3726 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3727 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
3728 return;
3729 }
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003730 bool supportsHAL3 = false;
3731 // supportsCameraApi also holds mInterfaceMutex, we can't call it in the
3732 // HIDL onStatusChanged wrapper call (we'll hold mStatusListenerLock and
3733 // mInterfaceMutex together, which can lead to deadlocks)
3734 binder::Status sRet =
3735 supportsCameraApi(String16(cameraId), hardware::ICameraService::API_VERSION_2,
3736 &supportsHAL3);
3737 if (!sRet.isOk()) {
3738 ALOGW("%s: Failed to determine if device supports HAL3 %s, supportsCameraApi call failed",
3739 __FUNCTION__, cameraId.string());
3740 return;
3741 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003742 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08003743 // of the listeners with both the mStatusLock and mStatusListenerLock held
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003744 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind, &supportsHAL3]
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003745 (const String8& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003746
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003747 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003748 // Update torch status if it has a flash unit.
3749 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003750 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003751 if (getTorchStatusLocked(cameraId, &torchStatus) !=
3752 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003753 TorchModeStatus newTorchStatus =
3754 status == StatusInternal::PRESENT ?
3755 TorchModeStatus::AVAILABLE_OFF :
3756 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003757 if (torchStatus != newTorchStatus) {
3758 onTorchStatusChangedLocked(cameraId, newTorchStatus);
3759 }
3760 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003761 }
3762
3763 Mutex::Autolock lock(mStatusListenerLock);
3764
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07003765 notifyPhysicalCameraStatusLocked(mapToInterface(status), cameraId, deviceKind);
Shuzhen Wang43858162020-01-10 13:42:15 -08003766
Ruben Brunkcc776712015-02-17 20:18:47 -08003767 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003768 bool isVendorListener = listener->isVendorListener();
3769 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
3770 listener->getListenerPid(), listener->getListenerUid()) ||
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07003771 (isVendorListener && !supportsHAL3)) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003772 ALOGV("Skipping discovery callback for system-only camera/HAL1 device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003773 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003774 continue;
3775 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003776 listener->getListener()->onStatusChanged(mapToInterface(status),
Emilian Peev53722fa2019-02-22 17:47:20 -08003777 String16(cameraId));
Ruben Brunkcc776712015-02-17 20:18:47 -08003778 }
3779 });
Igor Murashkincba2c162013-03-20 15:56:31 -07003780}
3781
Shuzhen Wang695044d2020-03-06 09:02:23 -08003782void CameraService::updateOpenCloseStatus(const String8& cameraId, bool open,
3783 const String16& clientPackageName) {
3784 Mutex::Autolock lock(mStatusListenerLock);
3785
3786 for (const auto& it : mListenerList) {
3787 if (!it->isOpenCloseCallbackAllowed()) {
3788 continue;
3789 }
3790
3791 binder::Status ret;
3792 String16 cameraId64(cameraId);
3793 if (open) {
3794 ret = it->getListener()->onCameraOpened(cameraId64, clientPackageName);
3795 } else {
3796 ret = it->getListener()->onCameraClosed(cameraId64);
3797 }
3798 if (!ret.isOk()) {
3799 ALOGE("%s: Failed to trigger onCameraOpened/onCameraClosed callback: %d", __FUNCTION__,
3800 ret.exceptionCode());
3801 }
3802 }
3803}
3804
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003805template<class Func>
3806void CameraService::CameraState::updateStatus(StatusInternal status,
3807 const String8& cameraId,
3808 std::initializer_list<StatusInternal> rejectSourceStates,
3809 Func onStatusUpdatedLocked) {
3810 Mutex::Autolock lock(mStatusLock);
3811 StatusInternal oldStatus = mStatus;
3812 mStatus = status;
3813
3814 if (oldStatus == status) {
3815 return;
3816 }
3817
3818 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
3819 cameraId.string(), oldStatus, status);
3820
3821 if (oldStatus == StatusInternal::NOT_PRESENT &&
3822 (status != StatusInternal::PRESENT &&
3823 status != StatusInternal::ENUMERATING)) {
3824
3825 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
3826 __FUNCTION__);
3827 mStatus = oldStatus;
3828 return;
3829 }
3830
3831 /**
3832 * Sometimes we want to conditionally do a transition.
3833 * For example if a client disconnects, we want to go to PRESENT
3834 * only if we weren't already in NOT_PRESENT or ENUMERATING.
3835 */
3836 for (auto& rejectStatus : rejectSourceStates) {
3837 if (oldStatus == rejectStatus) {
3838 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
3839 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
3840 mStatus = oldStatus;
3841 return;
3842 }
3843 }
3844
3845 onStatusUpdatedLocked(cameraId, status);
3846}
3847
Eino-Ville Talvalae8c96c72017-06-27 12:24:07 -07003848void CameraService::updateProxyDeviceState(int newState,
Emilian Peev573291c2018-02-10 02:10:56 +00003849 const String8& cameraId, int facing, const String16& clientName, int apiLevel) {
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07003850 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
3851 if (proxyBinder == nullptr) return;
3852 String16 id(cameraId);
Emilian Peev573291c2018-02-10 02:10:56 +00003853 proxyBinder->notifyCameraState(id, newState, facing, clientName, apiLevel);
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07003854}
3855
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003856status_t CameraService::getTorchStatusLocked(
3857 const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003858 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003859 if (!status) {
3860 return BAD_VALUE;
3861 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003862 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3863 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003864 // invalid camera ID or the camera doesn't have a flash unit
3865 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003866 }
3867
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003868 *status = mTorchStatusMap.valueAt(index);
3869 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003870}
3871
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003872status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003873 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003874 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3875 if (index == NAME_NOT_FOUND) {
3876 return BAD_VALUE;
3877 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003878 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003879
3880 return OK;
3881}
3882
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07003883void CameraService::notifyPhysicalCameraStatusLocked(int32_t status, const String8& cameraId,
3884 SystemCameraKind deviceKind) {
Shuzhen Wang43858162020-01-10 13:42:15 -08003885 Mutex::Autolock lock(mCameraStatesLock);
3886 for (const auto& state : mCameraStates) {
3887 std::vector<std::string> physicalCameraIds;
3888 if (!mCameraProviderManager->isLogicalCamera(state.first.c_str(), &physicalCameraIds)) {
3889 // This is not a logical multi-camera.
3890 continue;
3891 }
3892 if (std::find(physicalCameraIds.begin(), physicalCameraIds.end(), cameraId.c_str())
3893 == physicalCameraIds.end()) {
3894 // cameraId is not a physical camera of this logical multi-camera.
3895 continue;
3896 }
3897
3898 String16 id16(state.first), physicalId16(cameraId);
3899 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07003900 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
3901 listener->getListenerPid(), listener->getListenerUid())) {
3902 ALOGV("Skipping discovery callback for system-only camera device %s",
3903 cameraId.c_str());
3904 continue;
3905 }
Shuzhen Wang43858162020-01-10 13:42:15 -08003906 listener->getListener()->onPhysicalCameraStatusChanged(status,
3907 id16, physicalId16);
3908 }
3909 }
3910}
3911
Svet Ganova453d0d2018-01-11 15:37:58 -08003912void CameraService::blockClientsForUid(uid_t uid) {
3913 const auto clients = mActiveClientManager.getAll();
3914 for (auto& current : clients) {
3915 if (current != nullptr) {
3916 const auto basicClient = current->getValue();
3917 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
3918 basicClient->block();
3919 }
3920 }
3921 }
3922}
3923
Michael Grooverd1d435a2018-12-18 17:39:42 -08003924void CameraService::blockAllClients() {
3925 const auto clients = mActiveClientManager.getAll();
3926 for (auto& current : clients) {
3927 if (current != nullptr) {
3928 const auto basicClient = current->getValue();
3929 if (basicClient.get() != nullptr) {
3930 basicClient->block();
3931 }
3932 }
3933 }
3934}
3935
Svet Ganova453d0d2018-01-11 15:37:58 -08003936// NOTE: This is a remote API - make sure all args are validated
3937status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
3938 if (!checkCallingPermission(sManageCameraPermission, nullptr, nullptr)) {
3939 return PERMISSION_DENIED;
3940 }
3941 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
3942 return BAD_VALUE;
3943 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003944 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003945 return handleSetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07003946 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003947 return handleResetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07003948 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003949 return handleGetUidState(args, out, err);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003950 } else if (args.size() >= 2 && args[0] == String16("set-rotate-and-crop")) {
3951 return handleSetRotateAndCrop(args);
3952 } else if (args.size() >= 1 && args[0] == String16("get-rotate-and-crop")) {
3953 return handleGetRotateAndCrop(out);
Svet Ganova453d0d2018-01-11 15:37:58 -08003954 } else if (args.size() == 1 && args[0] == String16("help")) {
3955 printHelp(out);
3956 return NO_ERROR;
3957 }
3958 printHelp(err);
3959 return BAD_VALUE;
3960}
3961
3962status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07003963 String16 packageName = args[1];
3964
Svet Ganova453d0d2018-01-11 15:37:58 -08003965 bool active = false;
3966 if (args[2] == String16("active")) {
3967 active = true;
3968 } else if ((args[2] != String16("idle"))) {
3969 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
3970 return BAD_VALUE;
3971 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003972
3973 int userId = 0;
3974 if (args.size() >= 5 && args[3] == String16("--user")) {
3975 userId = atoi(String8(args[4]));
3976 }
3977
3978 uid_t uid;
3979 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
3980 return BAD_VALUE;
3981 }
3982
3983 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08003984 return NO_ERROR;
3985}
3986
3987status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07003988 String16 packageName = args[1];
3989
3990 int userId = 0;
3991 if (args.size() >= 4 && args[2] == String16("--user")) {
3992 userId = atoi(String8(args[3]));
3993 }
3994
3995 uid_t uid;
3996 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003997 return BAD_VALUE;
3998 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003999
4000 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08004001 return NO_ERROR;
4002}
4003
4004status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004005 String16 packageName = args[1];
4006
4007 int userId = 0;
4008 if (args.size() >= 4 && args[2] == String16("--user")) {
4009 userId = atoi(String8(args[3]));
4010 }
4011
4012 uid_t uid;
4013 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004014 return BAD_VALUE;
4015 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004016
4017 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004018 return dprintf(out, "active\n");
4019 } else {
4020 return dprintf(out, "idle\n");
4021 }
4022}
4023
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004024status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
4025 int rotateValue = atoi(String8(args[1]));
4026 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
4027 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
4028 Mutex::Autolock lock(mServiceLock);
4029
4030 mOverrideRotateAndCropMode = rotateValue;
4031
4032 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
4033
4034 const auto clients = mActiveClientManager.getAll();
4035 for (auto& current : clients) {
4036 if (current != nullptr) {
4037 const auto basicClient = current->getValue();
4038 if (basicClient.get() != nullptr) {
4039 basicClient->setRotateAndCropOverride(rotateValue);
4040 }
4041 }
4042 }
4043
4044 return OK;
4045}
4046
4047status_t CameraService::handleGetRotateAndCrop(int out) {
4048 Mutex::Autolock lock(mServiceLock);
4049
4050 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
4051}
4052
Svet Ganova453d0d2018-01-11 15:37:58 -08004053status_t CameraService::printHelp(int out) {
4054 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07004055 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
4056 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
4057 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004058 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
4059 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
4060 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08004061 " help print this message\n");
4062}
4063
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004064int32_t CameraService::updateAudioRestriction() {
4065 Mutex::Autolock lock(mServiceLock);
4066 return updateAudioRestrictionLocked();
4067}
4068
4069int32_t CameraService::updateAudioRestrictionLocked() {
4070 int32_t mode = 0;
4071 // iterate through all active client
4072 for (const auto& i : mActiveClientManager.getAll()) {
4073 const auto clientSp = i->getValue();
4074 mode |= clientSp->getAudioRestriction();
4075 }
4076
4077 bool modeChanged = (mAudioRestriction != mode);
4078 mAudioRestriction = mode;
4079 if (modeChanged) {
4080 mAppOps.setCameraAudioRestriction(mode);
4081 }
4082 return mode;
4083}
4084
Mathias Agopian65ab4712010-07-14 17:59:35 -07004085}; // namespace android