blob: 24288d6bafe4fd3cd5b5b4a427d9926d7fcb7479 [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{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800499 clientToDisconnect->disconnect();
500 }
501}
502
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800503void CameraService::onTorchStatusChanged(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800504 TorchModeStatus newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800505 Mutex::Autolock al(mTorchStatusMutex);
506 onTorchStatusChangedLocked(cameraId, newStatus);
507}
508
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800509void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800510 TorchModeStatus newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800511 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
512 __FUNCTION__, cameraId.string(), newStatus);
513
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800514 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800515 status_t res = getTorchStatusLocked(cameraId, &status);
516 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700517 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
518 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800519 return;
520 }
521 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800522 return;
523 }
524
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800525 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800526 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800527 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
528 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800529 return;
530 }
531
Ruben Brunkcc776712015-02-17 20:18:47 -0800532 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700533 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700534 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700535 auto iter = mTorchUidMap.find(cameraId);
536 if (iter != mTorchUidMap.end()) {
537 int oldUid = iter->second.second;
538 int newUid = iter->second.first;
539 BatteryNotifier& notifier(BatteryNotifier::getInstance());
540 if (oldUid != newUid) {
541 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800542 if (status == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700543 notifier.noteFlashlightOff(cameraId, oldUid);
544 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800545 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700546 notifier.noteFlashlightOn(cameraId, newUid);
547 }
548 iter->second.second = newUid;
549 } else {
550 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800551 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700552 notifier.noteFlashlightOn(cameraId, oldUid);
553 } else {
554 notifier.noteFlashlightOff(cameraId, oldUid);
555 }
556 }
557 }
558 }
559
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800560 broadcastTorchModeStatus(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800561}
562
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700563static bool hasPermissionsForSystemCamera(int callingPid, int callingUid) {
564 return checkPermission(sSystemCameraPermission, callingPid, callingUid) &&
565 checkPermission(sCameraPermission, callingPid, callingUid);
566}
567
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800568Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700569 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100570 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700571 bool hasSystemCameraPermissions =
572 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
573 CameraThreadState::getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700574 switch (type) {
575 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700576 if (hasSystemCameraPermissions) {
577 *numCameras = static_cast<int>(mNormalDeviceIds.size());
578 } else {
579 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
580 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800581 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700582 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700583 if (hasSystemCameraPermissions) {
584 *numCameras = mNumberOfCameras;
585 } else {
586 *numCameras = mNumberOfCamerasWithoutSystemCamera;
587 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800588 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700589 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800590 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700591 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800592 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
593 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700594 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800595 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700596}
597
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800598Status CameraService::getCameraInfo(int cameraId,
599 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700600 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100601 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700602 std::string cameraIdStr = cameraIdIntToStrLocked(cameraId);
603 if (shouldRejectSystemCameraConnection(String8(cameraIdStr.c_str()))) {
604 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
605 "characteristics for system only device %s: ", cameraIdStr.c_str());
606 }
Emilian Peevaee727d2017-05-04 16:35:48 +0100607
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800608 if (!mInitialized) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800609 return STATUS_ERROR(ERROR_DISCONNECTED,
610 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -0700611 }
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700612 bool hasSystemCameraPermissions =
613 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
614 CameraThreadState::getCallingUid());
615 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
616 if (hasSystemCameraPermissions) {
617 cameraIdBound = mNumberOfCameras;
618 }
619 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800620 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
621 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700622 }
623
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800624 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800625 status_t err = mCameraProviderManager->getCameraInfo(
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700626 cameraIdStr.c_str(), cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100627 if (err != OK) {
628 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
629 "Error retrieving camera info from device %d: %s (%d)", cameraId,
630 strerror(-err), err);
Ruben Brunkcc776712015-02-17 20:18:47 -0800631 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100632
Ruben Brunkcc776712015-02-17 20:18:47 -0800633 return ret;
634}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700635
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800636std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700637 const std::vector<std::string> *deviceIds = &mNormalDeviceIdsWithoutSystemCamera;
638 auto callingPid = CameraThreadState::getCallingPid();
639 auto callingUid = CameraThreadState::getCallingUid();
640 if (checkPermission(sSystemCameraPermission, callingPid, callingUid) ||
641 getpid() == callingPid) {
642 deviceIds = &mNormalDeviceIds;
643 }
644 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(deviceIds->size())) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800645 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700646 __FUNCTION__, cameraIdInt, deviceIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800647 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800648 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800649
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700650 return (*deviceIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800651}
652
653String8 CameraService::cameraIdIntToStr(int cameraIdInt) {
654 Mutex::Autolock lock(mServiceLock);
655 return String8(cameraIdIntToStrLocked(cameraIdInt).c_str());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800656}
657
658Status CameraService::getCameraCharacteristics(const String16& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800659 CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700660 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700661 if (!cameraInfo) {
662 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800663 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -0700664 }
665
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800666 if (!mInitialized) {
667 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800668 return STATUS_ERROR(ERROR_DISCONNECTED,
669 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -0700670 }
671
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700672 if (shouldRejectSystemCameraConnection(String8(cameraId))) {
673 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
674 "characteristics for system only device %s: ", String8(cameraId).string());
675 }
676
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800677 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800678
Emilian Peevf53f66e2017-04-11 14:29:43 +0100679 status_t res = mCameraProviderManager->getCameraCharacteristics(
680 String8(cameraId).string(), cameraInfo);
681 if (res != OK) {
682 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
683 "characteristics for device %s: %s (%d)", String8(cameraId).string(),
684 strerror(-res), res);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700685 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700686 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
687 if (getSystemCameraKind(String8(cameraId), &deviceKind) != OK) {
688 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, String8(cameraId).string());
689 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera kind "
690 "for device %s", String8(cameraId).string());
691 }
Jayant Chowdhary12361932018-08-27 14:46:13 -0700692 int callingPid = CameraThreadState::getCallingPid();
693 int callingUid = CameraThreadState::getCallingUid();
Emilian Peeve20c6372018-08-14 18:45:53 +0100694 std::vector<int32_t> tagsRemoved;
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700695 // If it's not calling from cameraserver, check the permission only if
696 // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
697 // it would've already been checked in shouldRejectSystemCameraConnection.
Emilian Peeve20c6372018-08-14 18:45:53 +0100698 if ((callingPid != getpid()) &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700699 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700700 !checkPermission(sCameraPermission, callingPid, callingUid)) {
Emilian Peeve20c6372018-08-14 18:45:53 +0100701 res = cameraInfo->removePermissionEntries(
702 mCameraProviderManager->getProviderTagIdLocked(String8(cameraId).string()),
703 &tagsRemoved);
704 if (res != OK) {
705 cameraInfo->clear();
706 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
707 " characteristics needing camera permission for device %s: %s (%d)",
708 String8(cameraId).string(), strerror(-res), res);
709 }
710 }
711
712 if (!tagsRemoved.empty()) {
713 res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
714 tagsRemoved.data(), tagsRemoved.size());
715 if (res != OK) {
716 cameraInfo->clear();
717 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
718 "keys needing permission for device %s: %s (%d)", String8(cameraId).string(),
719 strerror(-res), res);
720 }
721 }
722
Zhijun He2b59be82013-09-25 10:14:30 -0700723 return ret;
724}
725
Ruben Brunkcc776712015-02-17 20:18:47 -0800726String8 CameraService::getFormattedCurrentTime() {
727 time_t now = time(nullptr);
728 char formattedTime[64];
729 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
730 return String8(formattedTime);
731}
732
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800733Status CameraService::getCameraVendorTagDescriptor(
734 /*out*/
735 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700736 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800737 if (!mInitialized) {
738 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800739 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800740 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -0800741 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
742 if (globalDescriptor != nullptr) {
743 *desc = *(globalDescriptor.get());
744 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800745 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800746}
747
Emilian Peev71c73a22017-03-21 16:35:51 +0000748Status CameraService::getCameraVendorTagCache(
749 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
750 ATRACE_CALL();
751 if (!mInitialized) {
752 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
753 return STATUS_ERROR(ERROR_DISCONNECTED,
754 "Camera subsystem not available");
755 }
756 sp<VendorTagDescriptorCache> globalCache =
757 VendorTagDescriptorCache::getGlobalVendorTagCache();
758 if (globalCache != nullptr) {
759 *cache = *(globalCache.get());
760 }
761 return Status::ok();
762}
763
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800764int CameraService::getDeviceVersion(const String8& cameraId, int* facing) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700765 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800766
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800767 int deviceVersion = 0;
768
Emilian Peevf53f66e2017-04-11 14:29:43 +0100769 status_t res;
770 hardware::hidl_version maxVersion{0,0};
771 res = mCameraProviderManager->getHighestSupportedVersion(cameraId.string(),
772 &maxVersion);
773 if (res != OK) return -1;
774 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800775
Emilian Peevf53f66e2017-04-11 14:29:43 +0100776 hardware::CameraInfo info;
777 if (facing) {
778 res = mCameraProviderManager->getCameraInfo(cameraId.string(), &info);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -0800779 if (res != OK) return -1;
Emilian Peevf53f66e2017-04-11 14:29:43 +0100780 *facing = info.facing;
Igor Murashkin634a5152013-02-20 17:15:11 -0800781 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100782
Igor Murashkin634a5152013-02-20 17:15:11 -0800783 return deviceVersion;
784}
785
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800786Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700787 switch(err) {
788 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800789 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800790 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800791 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
792 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800793 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800794 return STATUS_ERROR(ERROR_DISCONNECTED,
795 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700796 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800797 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
798 "Camera HAL encountered error %d: %s",
799 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700800 }
Igor Murashkinbfc99152013-02-27 12:55:20 -0800801}
802
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800803Status CameraService::makeClient(const sp<CameraService>& cameraService,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800804 const sp<IInterface>& cameraCb, const String16& packageName,
805 const std::unique_ptr<String16>& featureId, const String8& cameraId, int api1CameraId,
806 int facing, int clientPid, uid_t clientUid, int servicePid, int halVersion,
807 int deviceVersion, apiLevel effectiveApiLevel,
Ruben Brunkcc776712015-02-17 20:18:47 -0800808 /*out*/sp<BasicClient>* client) {
809
Ruben Brunkcc776712015-02-17 20:18:47 -0800810 if (halVersion < 0 || halVersion == deviceVersion) {
811 // Default path: HAL version is unspecified by caller, create CameraClient
812 // based on device version reported by the HAL.
813 switch(deviceVersion) {
814 case CAMERA_DEVICE_API_VERSION_1_0:
815 if (effectiveApiLevel == API_1) { // Camera1 API route
816 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800817 *client = new CameraClient(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800818 api1CameraId, facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700819 getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800820 } else { // Camera2 API route
821 ALOGW("Camera using old HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800822 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800823 "Camera device \"%s\" HAL version %d does not support camera2 API",
824 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800825 }
826 break;
Ruben Brunkcc776712015-02-17 20:18:47 -0800827 case CAMERA_DEVICE_API_VERSION_3_0:
828 case CAMERA_DEVICE_API_VERSION_3_1:
829 case CAMERA_DEVICE_API_VERSION_3_2:
830 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -0700831 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -0700832 case CAMERA_DEVICE_API_VERSION_3_5:
Yin-Chia Yeh56d98ba2020-01-16 16:57:14 -0800833 case CAMERA_DEVICE_API_VERSION_3_6:
Ruben Brunkcc776712015-02-17 20:18:47 -0800834 if (effectiveApiLevel == API_1) { // Camera1 API route
835 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800836 *client = new Camera2Client(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800837 cameraId, api1CameraId,
838 facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700839 servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800840 } else { // Camera2 API route
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800841 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
842 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800843 *client = new CameraDeviceClient(cameraService, tmp, packageName, featureId,
844 cameraId, facing, clientPid, clientUid, servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800845 }
846 break;
847 default:
848 // Should not be reachable
849 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800850 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800851 "Camera device \"%s\" has unknown HAL version %d",
852 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800853 }
854 } else {
855 // A particular HAL version is requested by caller. Create CameraClient
856 // based on the requested HAL version.
857 if (deviceVersion > CAMERA_DEVICE_API_VERSION_1_0 &&
858 halVersion == CAMERA_DEVICE_API_VERSION_1_0) {
859 // Only support higher HAL version device opened as HAL1.0 device.
860 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800861 *client = new CameraClient(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800862 api1CameraId, facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700863 servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800864 } else {
865 // Other combinations (e.g. HAL3.x open as HAL2.x) are not supported yet.
866 ALOGE("Invalid camera HAL version %x: HAL %x device can only be"
867 " opened as HAL %x device", halVersion, deviceVersion,
868 CAMERA_DEVICE_API_VERSION_1_0);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800869 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800870 "Camera device \"%s\" (HAL version %d) cannot be opened as HAL version %d",
871 cameraId.string(), deviceVersion, halVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800872 }
873 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800874 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800875}
876
Ruben Brunk6267b532015-04-30 17:44:07 -0700877String8 CameraService::toString(std::set<userid_t> intSet) {
878 String8 s("");
879 bool first = true;
880 for (userid_t i : intSet) {
881 if (first) {
882 s.appendFormat("%d", i);
883 first = false;
884 } else {
885 s.appendFormat(", %d", i);
886 }
887 }
888 return s;
889}
890
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800891int32_t CameraService::mapToInterface(TorchModeStatus status) {
892 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
893 switch (status) {
894 case TorchModeStatus::NOT_AVAILABLE:
895 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
896 break;
897 case TorchModeStatus::AVAILABLE_OFF:
898 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
899 break;
900 case TorchModeStatus::AVAILABLE_ON:
901 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
902 break;
903 default:
904 ALOGW("Unknown new flash status: %d", status);
905 }
906 return serviceStatus;
907}
908
909CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
910 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
911 switch (status) {
912 case CameraDeviceStatus::NOT_PRESENT:
913 serviceStatus = StatusInternal::NOT_PRESENT;
914 break;
915 case CameraDeviceStatus::PRESENT:
916 serviceStatus = StatusInternal::PRESENT;
917 break;
918 case CameraDeviceStatus::ENUMERATING:
919 serviceStatus = StatusInternal::ENUMERATING;
920 break;
921 default:
922 ALOGW("Unknown new HAL device status: %d", status);
923 }
924 return serviceStatus;
925}
926
927int32_t CameraService::mapToInterface(StatusInternal status) {
928 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
929 switch (status) {
930 case StatusInternal::NOT_PRESENT:
931 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
932 break;
933 case StatusInternal::PRESENT:
934 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
935 break;
936 case StatusInternal::ENUMERATING:
937 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
938 break;
939 case StatusInternal::NOT_AVAILABLE:
940 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
941 break;
942 case StatusInternal::UNKNOWN:
943 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
944 break;
945 default:
946 ALOGW("Unknown new internal device status: %d", status);
947 }
948 return serviceStatus;
949}
950
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800951Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -0700952 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700953
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800954 String16 internalPackageName("cameraserver");
Ruben Brunkcc776712015-02-17 20:18:47 -0800955 String8 id = String8::format("%d", cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800956 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800957 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800958 if (!(ret = connectHelper<ICameraClient,Client>(
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800959 sp<ICameraClient>{nullptr}, id, cameraId,
960 static_cast<int>(CAMERA_HAL_API_VERSION_UNSPECIFIED),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800961 internalPackageName, std::unique_ptr<String16>(), uid, USE_CALLING_PID,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700962 API_1, /*shimUpdateOnly*/ true, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800963 ).isOk()) {
964 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
Ruben Brunkb2119af2014-05-09 19:57:56 -0700965 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800966 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700967}
968
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800969Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -0700970 /*out*/
971 CameraParameters* parameters) {
972
973 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
974
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800975 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -0700976
977 if (parameters == NULL) {
978 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800979 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -0700980 }
981
Ruben Brunkcc776712015-02-17 20:18:47 -0800982 String8 id = String8::format("%d", cameraId);
983
984 // Check if we already have parameters
985 {
986 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -0700987 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -0800988 auto cameraState = getCameraState(id);
989 if (cameraState == nullptr) {
990 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800991 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
992 "Invalid camera ID: %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -0800993 }
994 CameraParameters p = cameraState->getShimParams();
995 if (!p.isEmpty()) {
996 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800997 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700998 }
999 }
1000
Jayant Chowdhary12361932018-08-27 14:46:13 -07001001 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001002 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001003 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001004 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001005 // Error already logged by callee
1006 return ret;
1007 }
1008
1009 // Check for parameters again
1010 {
1011 // Scope for service lock
1012 Mutex::Autolock lock(mServiceLock);
1013 auto cameraState = getCameraState(id);
1014 if (cameraState == nullptr) {
1015 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001016 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1017 "Invalid camera ID: %s", id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001018 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001019 CameraParameters p = cameraState->getShimParams();
1020 if (!p.isEmpty()) {
1021 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001022 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001023 }
1024 }
1025
Ruben Brunkcc776712015-02-17 20:18:47 -08001026 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1027 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001028 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001029}
1030
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001031// Can camera service trust the caller based on the calling UID?
1032static bool isTrustedCallingUid(uid_t uid) {
1033 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001034 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001035 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001036 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001037 return true;
1038 default:
1039 return false;
1040 }
1041}
1042
Nicholas Sauera3620332019-04-03 14:05:17 -07001043static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1044 PermissionController pc;
1045 uid = pc.getPackageUid(packageName, 0);
1046 if (uid <= 0) {
1047 ALOGE("Unknown package: '%s'", String8(packageName).string());
1048 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
1049 return BAD_VALUE;
1050 }
1051
1052 if (userId < 0) {
1053 ALOGE("Invalid user: %d", userId);
1054 dprintf(err, "Invalid user: %d\n", userId);
1055 return BAD_VALUE;
1056 }
1057
1058 uid = multiuser_get_uid(userId, uid);
1059 return NO_ERROR;
1060}
1061
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001062Status CameraService::validateConnectLocked(const String8& cameraId,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001063 const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
1064 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001065
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001066#ifdef __BRILLO__
1067 UNUSED(clientName8);
1068 UNUSED(clientUid);
1069 UNUSED(clientPid);
1070 UNUSED(originalClientPid);
1071#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001072 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1073 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001074 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001075 return allowed;
1076 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001077#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001078
Jayant Chowdhary12361932018-08-27 14:46:13 -07001079 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001080
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001081 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001082 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1083 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001084 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1085 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001086 }
1087
Ruben Brunkcc776712015-02-17 20:18:47 -08001088 if (getCameraState(cameraId) == nullptr) {
1089 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1090 cameraId.string());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001091 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1092 "No camera device with ID \"%s\" available", cameraId.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001093 }
1094
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001095 status_t err = checkIfDeviceIsUsable(cameraId);
1096 if (err != NO_ERROR) {
1097 switch(err) {
1098 case -ENODEV:
1099 case -EBUSY:
1100 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1101 "No camera device with ID \"%s\" currently available", cameraId.string());
1102 default:
1103 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1104 "Unknown error connecting to ID \"%s\"", cameraId.string());
1105 }
1106 }
1107 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001108}
1109
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001110Status CameraService::validateClientPermissionsLocked(const String8& cameraId,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001111 const String8& clientName8, int& clientUid, int& clientPid,
1112 /*out*/int& originalClientPid) const {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001113 int callingPid = CameraThreadState::getCallingPid();
1114 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001115
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001116 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001117 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001118 clientUid = callingUid;
1119 } else if (!isTrustedCallingUid(callingUid)) {
1120 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1121 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001122 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1123 "Untrusted caller (calling PID %d, UID %d) trying to "
1124 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1125 callingPid, callingUid, cameraId.string(),
1126 clientName8.string(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001127 }
1128
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001129 // Check if we can trust clientPid
1130 if (clientPid == USE_CALLING_PID) {
1131 clientPid = callingPid;
1132 } else if (!isTrustedCallingUid(callingUid)) {
1133 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1134 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001135 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1136 "Untrusted caller (calling PID %d, UID %d) trying to "
1137 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1138 callingPid, callingUid, cameraId.string(),
1139 clientName8.string(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001140 }
1141
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001142 if (shouldRejectSystemCameraConnection(cameraId)) {
1143 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1144 cameraId.c_str());
1145 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
1146 "available", cameraId.string());
1147 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001148 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1149 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1150 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
1151 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
1152 "found while trying to query device kind", cameraId.string());
1153
1154 }
1155
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001156 // If it's not calling from cameraserver, check the permission if the
1157 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1158 // android.permission.SYSTEM_CAMERA for system only camera devices).
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001159 if (callingPid != getpid() &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001160 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001161 !checkPermission(sCameraPermission, clientPid, clientUid)) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001162 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001163 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1164 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
1165 clientName8.string(), clientUid, clientPid, cameraId.string());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001166 }
1167
Svet Ganova453d0d2018-01-11 15:37:58 -08001168 // Make sure the UID is in an active state to use the camera
Svet Ganov7b4ab782018-03-25 12:48:10 -07001169 if (!mUidPolicy->isUidActive(callingUid, String16(clientName8))) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001170 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001171 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1172 clientPid, clientUid);
1173 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001174 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1175 "calling UID %d proc state %" PRId32 ")",
1176 clientName8.string(), clientUid, clientPid, cameraId.string(),
1177 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001178 }
1179
Michael Grooverd1d435a2018-12-18 17:39:42 -08001180 // If sensor privacy is enabled then prevent access to the camera
1181 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1182 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1183 return STATUS_ERROR_FMT(ERROR_DISABLED,
1184 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
1185 "is enabled", clientName8.string(), clientUid, clientPid, cameraId.string());
1186 }
1187
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001188 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1189 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001190 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001191 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001192
Ruben Brunk6267b532015-04-30 17:44:07 -07001193 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001194
Ruben Brunka8ca9152015-04-07 14:23:40 -07001195 // Only allow clients who are being used by the current foreground device user, unless calling
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001196 // from our own process OR the caller is using the cameraserver's HIDL interface.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001197 if (getCurrentServingCall() != BinderCallType::HWBINDER && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001198 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001199 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1200 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
1201 toString(mAllowedUsers).string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001202 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1203 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
1204 clientUserId, cameraId.string());
Ruben Brunk36597b22015-03-20 22:15:57 -07001205 }
1206
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001207 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001208}
1209
1210status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
1211 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001212 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001213 if (cameraState == nullptr) {
1214 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1215 cameraId.string());
1216 return -ENODEV;
1217 }
1218
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001219 StatusInternal currentStatus = cameraState->getStatus();
1220 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001221 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
1222 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001223 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001224 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001225 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
1226 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001227 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001228 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001229
Ruben Brunkcc776712015-02-17 20:18:47 -08001230 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001231}
1232
Ruben Brunkcc776712015-02-17 20:18:47 -08001233void CameraService::finishConnectLocked(const sp<BasicClient>& client,
1234 const CameraService::DescriptorPtr& desc) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001235
Ruben Brunkcc776712015-02-17 20:18:47 -08001236 // Make a descriptor for the incoming client
1237 auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
1238 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1239
1240 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
1241 String8(client->getPackageName()));
1242
1243 if (evicted.size() > 0) {
1244 // This should never happen - clients should already have been removed in disconnect
1245 for (auto& i : evicted) {
1246 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
1247 __FUNCTION__, i->getKey().string());
1248 }
1249
1250 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1251 __FUNCTION__);
1252 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001253
1254 // And register a death notification for the client callback. Do
1255 // this last to avoid Binder policy where a nested Binder
1256 // transaction might be pre-empted to service the client death
1257 // notification if the client process dies before linkToDeath is
1258 // invoked.
1259 sp<IBinder> remoteCallback = client->getRemote();
1260 if (remoteCallback != nullptr) {
1261 remoteCallback->linkToDeath(this);
1262 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001263}
1264
1265status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
1266 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
1267 /*out*/
1268 sp<BasicClient>* client,
1269 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001270 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001271 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001272 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001273 DescriptorPtr clientDescriptor;
1274 {
1275 if (effectiveApiLevel == API_1) {
1276 // If we are using API1, any existing client for this camera ID with the same remote
1277 // should be returned rather than evicted to allow MediaRecorder to work properly.
1278
1279 auto current = mActiveClientManager.get(cameraId);
1280 if (current != nullptr) {
1281 auto clientSp = current->getValue();
1282 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001283 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
1284 ALOGW("CameraService connect called from same client, but with a different"
1285 " API level, evicting prior client...");
1286 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001287 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001288 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001289 *client = clientSp;
1290 return NO_ERROR;
1291 }
1292 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001293 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001294 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001295
Ruben Brunkcc776712015-02-17 20:18:47 -08001296 // Get current active client PIDs
1297 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1298 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001299
Emilian Peev8131a262017-02-01 12:33:43 +00001300 std::vector<int> priorityScores(ownerPids.size());
1301 std::vector<int> states(ownerPids.size());
Igor Murashkine6800ce2013-03-04 17:25:57 -08001302
Emilian Peev8131a262017-02-01 12:33:43 +00001303 // Get priority scores of all active PIDs
1304 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1305 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1306 /*out*/&priorityScores[0]);
1307 if (err != OK) {
1308 ALOGE("%s: Priority score query failed: %d",
1309 __FUNCTION__, err);
1310 return err;
1311 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001312
Ruben Brunkcc776712015-02-17 20:18:47 -08001313 // Update all active clients' priorities
Emilian Peev8131a262017-02-01 12:33:43 +00001314 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
Ruben Brunkcc776712015-02-17 20:18:47 -08001315 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
Emilian Peev8131a262017-02-01 12:33:43 +00001316 pidToPriorityMap.emplace(ownerPids[i],
Jayant Chowdharyc578a502019-05-08 10:57:54 -07001317 resource_policy::ClientPriority(priorityScores[i], states[i],
1318 /* isVendorClient won't get copied over*/ false));
Ruben Brunkcc776712015-02-17 20:18:47 -08001319 }
1320 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001321
Ruben Brunkcc776712015-02-17 20:18:47 -08001322 // Get state for the given cameraId
1323 auto state = getCameraState(cameraId);
1324 if (state == nullptr) {
1325 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1326 clientPid, cameraId.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001327 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001328 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001329 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001330
1331 // Make descriptor for incoming client
Shuzhen Wang2db86ff2018-04-25 01:11:17 +00001332 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001333 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1334 state->getConflicting(),
Emilian Peev8131a262017-02-01 12:33:43 +00001335 priorityScores[priorityScores.size() - 1],
1336 clientPid,
1337 states[states.size() - 1]);
Ruben Brunkcc776712015-02-17 20:18:47 -08001338
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001339 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1340
Ruben Brunkcc776712015-02-17 20:18:47 -08001341 // Find clients that would be evicted
1342 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1343
1344 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1345 // background, so we cannot do evictions
1346 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1347 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1348 " priority).", clientPid);
1349
1350 sp<BasicClient> clientSp = clientDescriptor->getValue();
1351 String8 curTime = getFormattedCurrentTime();
1352 auto incompatibleClients =
1353 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1354
1355 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Emilian Peev8131a262017-02-01 12:33:43 +00001356 "(PID %d, score %d state %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001357 cameraId.string(), packageName.string(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001358 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001359
1360 for (auto& i : incompatibleClients) {
1361 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001362 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
1363 i->getKey().string(),
1364 String8{i->getValue()->getPackageName()}.string(),
1365 i->getOwnerId(), i->getPriority().getScore(),
1366 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001367 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00001368 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(),
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001369 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001370 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001371 }
1372
1373 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001374 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001375 mEventLog.add(msg);
1376
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001377 auto current = mActiveClientManager.get(cameraId);
1378 if (current != nullptr) {
1379 return -EBUSY; // CAMERA_IN_USE
1380 } else {
1381 return -EUSERS; // MAX_CAMERAS_IN_USE
1382 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001383 }
1384
1385 for (auto& i : evicted) {
1386 sp<BasicClient> clientSp = i->getValue();
1387 if (clientSp.get() == nullptr) {
1388 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1389
1390 // TODO: Remove this
1391 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1392 __FUNCTION__);
1393 mActiveClientManager.remove(i);
1394 continue;
1395 }
1396
1397 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1398 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001399 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001400
Ruben Brunkcc776712015-02-17 20:18:47 -08001401 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001402 logEvent(String8::format("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00001403 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1404 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001405 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
Emilian Peev8131a262017-02-01 12:33:43 +00001406 i->getOwnerId(), i->getPriority().getScore(),
1407 i->getPriority().getState(), cameraId.string(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001408 packageName.string(), clientPid, clientPriority.getScore(),
1409 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08001410
1411 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001412 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001413 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001414 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001415 }
1416
Ruben Brunkcc776712015-02-17 20:18:47 -08001417 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1418 // other clients from connecting in mServiceLockWrapper if held
1419 mServiceLock.unlock();
1420
1421 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07001422 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001423
1424 // Destroy evicted clients
1425 for (auto& i : evictedClients) {
1426 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001427 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001428 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001429
Jayant Chowdhary12361932018-08-27 14:46:13 -07001430 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08001431
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001432 for (const auto& i : evictedClients) {
1433 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1434 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1435 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1436 if (ret == TIMED_OUT) {
1437 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1438 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1439 mActiveClientManager.toString().string());
1440 return -EBUSY;
1441 }
1442 if (ret != NO_ERROR) {
1443 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1444 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1445 ret, mActiveClientManager.toString().string());
1446 return ret;
1447 }
1448 }
1449
1450 evictedClients.clear();
1451
Ruben Brunkcc776712015-02-17 20:18:47 -08001452 // Once clients have been disconnected, relock
1453 mServiceLock.lock();
1454
1455 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1456 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1457 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001458 }
1459
Ruben Brunkcc776712015-02-17 20:18:47 -08001460 *partial = clientDescriptor;
1461 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001462}
1463
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001464Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001465 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001466 int api1CameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001467 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001468 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001469 int clientPid,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001470 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001471 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001472
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001473 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001474 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001475
1476 String8 id = cameraIdIntToStr(api1CameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001477 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001478 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001479 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, std::unique_ptr<String16>(),
1480 clientUid, clientPid, API_1, /*shimUpdateOnly*/ false, /*out*/client);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001481
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001482 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001483 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001484 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001485 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001486 }
1487
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001488 *device = client;
1489 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001490}
1491
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001492Status CameraService::connectLegacy(
Zhijun Heb10cdad2014-06-16 16:38:35 -07001493 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001494 int api1CameraId, int halVersion,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001495 const String16& clientPackageName,
Zhijun Heb10cdad2014-06-16 16:38:35 -07001496 int clientUid,
1497 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001498 sp<ICamera>* device) {
Zhijun Heb10cdad2014-06-16 16:38:35 -07001499
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001500 ATRACE_CALL();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001501 String8 id = cameraIdIntToStr(api1CameraId);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001502
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001503 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001504 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001505 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId, halVersion,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001506 clientPackageName, std::unique_ptr<String16>(), clientUid, USE_CALLING_PID, API_1,
1507 /*shimUpdateOnly*/ false, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001508
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001509 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001510 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001511 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001512 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001513 }
1514
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001515 *device = client;
1516 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001517}
1518
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001519bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
1520 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001521 // If the client is not a vendor client, don't add listener if
1522 // a) the camera is a publicly hidden secure camera OR
1523 // b) the camera is a system only camera and the client doesn't
1524 // have android.permission.SYSTEM_CAMERA permissions.
1525 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
1526 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1527 !hasPermissionsForSystemCamera(clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001528 return true;
1529 }
1530 return false;
1531}
1532
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001533bool CameraService::shouldRejectSystemCameraConnection(const String8& cameraId) const {
1534 // Rules for rejection:
1535 // 1) If cameraserver tries to access this camera device, accept the
1536 // connection.
1537 // 2) The camera device is a publicly hidden secure camera device AND some
1538 // component is trying to access it on a non-hwbinder thread (generally a non HAL client),
1539 // reject it.
1540 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
1541 // and the serving thread is a non hwbinder thread, the client must have
1542 // android.permission.SYSTEM_CAMERA permissions to connect.
1543
1544 int cPid = CameraThreadState::getCallingPid();
1545 int cUid = CameraThreadState::getCallingUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001546 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
1547 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
1548 ALOGE("%s: Invalid camera id %s, ", __FUNCTION__, cameraId.c_str());
1549 return true;
1550 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001551
1552 // (1) Cameraserver trying to connect, accept.
1553 if (CameraThreadState::getCallingPid() == getpid()) {
1554 return false;
1555 }
1556 // (2)
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001557 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001558 systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
1559 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
1560 return true;
1561 }
1562 // (3) Here we only check for permissions if it is a system only camera device. This is since
1563 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
1564 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
1565 // same behavior for system camera devices.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001566 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001567 systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1568 !hasPermissionsForSystemCamera(cPid, cUid)) {
1569 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
1570 cameraId.c_str());
1571 return true;
1572 }
1573
1574 return false;
1575}
1576
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001577Status CameraService::connectDevice(
1578 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001579 const String16& cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001580 const String16& clientPackageName,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001581 const std::unique_ptr<String16>& clientFeatureId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001582 int clientUid,
1583 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001584 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001585
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001586 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001587 Status ret = Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001588 String8 id = String8(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001589 sp<CameraDeviceClient> client = nullptr;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001590 String16 clientPackageNameAdj = clientPackageName;
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001591
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001592 if (getCurrentServingCall() == BinderCallType::HWBINDER) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001593 std::string vendorClient =
1594 StringPrintf("vendor.client.pid<%d>", CameraThreadState::getCallingPid());
1595 clientPackageNameAdj = String16(vendorClient.c_str());
1596 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001597 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001598 /*api1CameraId*/-1,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001599 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageNameAdj, clientFeatureId,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001600 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08001601
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001602 if(!ret.isOk()) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001603 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageNameAdj),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001604 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001605 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001606 }
1607
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001608 *device = client;
1609 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001610}
1611
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001612template<class CALLBACK, class CLIENT>
1613Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001614 int api1CameraId, int halVersion, const String16& clientPackageName,
1615 const std::unique_ptr<String16>& clientFeatureId, int clientUid, int clientPid,
1616 apiLevel effectiveApiLevel, bool shimUpdateOnly,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001617 /*out*/sp<CLIENT>& device) {
1618 binder::Status ret = binder::Status::ok();
1619
1620 String8 clientName8(clientPackageName);
1621
1622 int originalClientPid = 0;
1623
1624 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) for HAL version %s and "
1625 "Camera API version %d", clientPid, clientName8.string(), cameraId.string(),
1626 (halVersion == -1) ? "default" : std::to_string(halVersion).c_str(),
1627 static_cast<int>(effectiveApiLevel));
1628
1629 sp<CLIENT> client = nullptr;
1630 {
1631 // Acquire mServiceLock and prevent other clients from connecting
1632 std::unique_ptr<AutoConditionLock> lock =
1633 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1634
1635 if (lock == nullptr) {
1636 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
1637 , clientPid);
1638 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1639 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
1640 cameraId.string(), clientName8.string(), clientPid);
1641 }
1642
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07001643 // Enforce client permissions and do basic validity checks
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001644 if(!(ret = validateConnectLocked(cameraId, clientName8,
1645 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
1646 return ret;
1647 }
1648
1649 // Check the shim parameters after acquiring lock, if they have already been updated and
1650 // we were doing a shim update, return immediately
1651 if (shimUpdateOnly) {
1652 auto cameraState = getCameraState(cameraId);
1653 if (cameraState != nullptr) {
1654 if (!cameraState->getShimParams().isEmpty()) return ret;
1655 }
1656 }
1657
1658 status_t err;
1659
1660 sp<BasicClient> clientTmp = nullptr;
1661 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
1662 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
1663 IInterface::asBinder(cameraCb), clientName8, /*out*/&clientTmp,
1664 /*out*/&partial)) != NO_ERROR) {
1665 switch (err) {
1666 case -ENODEV:
1667 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1668 "No camera device with ID \"%s\" currently available",
1669 cameraId.string());
1670 case -EBUSY:
1671 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1672 "Higher-priority client using camera, ID \"%s\" currently unavailable",
1673 cameraId.string());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001674 case -EUSERS:
1675 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1676 "Too many cameras already open, cannot open camera \"%s\"",
1677 cameraId.string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001678 default:
1679 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1680 "Unexpected error %s (%d) opening camera \"%s\"",
1681 strerror(-err), err, cameraId.string());
1682 }
1683 }
1684
1685 if (clientTmp.get() != nullptr) {
1686 // Handle special case for API1 MediaRecorder where the existing client is returned
1687 device = static_cast<CLIENT*>(clientTmp.get());
1688 return ret;
1689 }
1690
1691 // give flashlight a chance to close devices if necessary.
1692 mFlashlight->prepareDeviceOpen(cameraId);
1693
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001694 int facing = -1;
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001695 int deviceVersion = getDeviceVersion(cameraId, /*out*/&facing);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08001696 if (facing == -1) {
1697 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.string());
1698 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1699 "Unable to get camera device \"%s\" facing", cameraId.string());
1700 }
1701
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001702 sp<BasicClient> tmp = nullptr;
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001703 if(!(ret = makeClient(this, cameraCb, clientPackageName, clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001704 cameraId, api1CameraId, facing,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001705 clientPid, clientUid, getpid(),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001706 halVersion, deviceVersion, effectiveApiLevel,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001707 /*out*/&tmp)).isOk()) {
1708 return ret;
1709 }
1710 client = static_cast<CLIENT*>(tmp.get());
1711
1712 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
1713 __FUNCTION__);
1714
Emilian Peevbd8c5032018-02-14 23:05:40 +00001715 err = client->initialize(mCameraProviderManager, mMonitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001716 if (err != OK) {
1717 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001718 // Errors could be from the HAL module open call or from AppOpsManager
1719 switch(err) {
1720 case BAD_VALUE:
1721 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1722 "Illegal argument to HAL module for camera \"%s\"", cameraId.string());
1723 case -EBUSY:
1724 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1725 "Camera \"%s\" is already open", cameraId.string());
1726 case -EUSERS:
1727 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1728 "Too many cameras already open, cannot open camera \"%s\"",
1729 cameraId.string());
1730 case PERMISSION_DENIED:
1731 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1732 "No permission to open camera \"%s\"", cameraId.string());
1733 case -EACCES:
1734 return STATUS_ERROR_FMT(ERROR_DISABLED,
1735 "Camera \"%s\" disabled by policy", cameraId.string());
1736 case -ENODEV:
1737 default:
1738 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1739 "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
1740 strerror(-err), err);
1741 }
1742 }
1743
1744 // Update shim paremeters for legacy clients
1745 if (effectiveApiLevel == API_1) {
1746 // Assume we have always received a Client subclass for API1
1747 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
1748 String8 rawParams = shimClient->getParameters();
1749 CameraParameters params(rawParams);
1750
1751 auto cameraState = getCameraState(cameraId);
1752 if (cameraState != nullptr) {
1753 cameraState->setShimParams(params);
1754 } else {
1755 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
1756 __FUNCTION__, cameraId.string());
1757 }
1758 }
1759
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001760 // Set rotate-and-crop override behavior
1761 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
1762 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
1763 }
1764
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001765 if (shimUpdateOnly) {
1766 // If only updating legacy shim parameters, immediately disconnect client
1767 mServiceLock.unlock();
1768 client->disconnect();
1769 mServiceLock.lock();
1770 } else {
1771 // Otherwise, add client to active clients list
1772 finishConnectLocked(client, partial);
1773 }
1774 } // lock is destroyed, allow further connect calls
1775
1776 // Important: release the mutex here so the client can call back into the service from its
1777 // destructor (can be at the end of the call)
1778 device = client;
1779 return ret;
1780}
1781
Emilian Peevb2bc5a42019-11-20 16:02:14 -08001782status_t CameraService::addOfflineClient(String8 cameraId, sp<BasicClient> offlineClient) {
1783 if (offlineClient.get() == nullptr) {
1784 return BAD_VALUE;
1785 }
1786
1787 {
1788 // Acquire mServiceLock and prevent other clients from connecting
1789 std::unique_ptr<AutoConditionLock> lock =
1790 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1791
1792 if (lock == nullptr) {
1793 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
1794 , __FUNCTION__, offlineClient->getClientPid());
1795 return TIMED_OUT;
1796 }
1797
1798 auto onlineClientDesc = mActiveClientManager.get(cameraId);
1799 if (onlineClientDesc.get() == nullptr) {
1800 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
1801 cameraId.c_str());
1802 return BAD_VALUE;
1803 }
1804
1805 // Offline clients do not evict or conflict with other online devices. Resource sharing
1806 // conflicts are handled by the camera provider which will either succeed or fail before
1807 // reaching this method.
1808 const auto& onlinePriority = onlineClientDesc->getPriority();
1809 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
1810 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
1811 /*conflictingKeys*/ std::set<String8>(), onlinePriority.getScore(),
1812 onlineClientDesc->getOwnerId(), onlinePriority.getState());
1813
1814 // Allow only one offline device per camera
1815 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
1816 if (!incompatibleClients.empty()) {
1817 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
1818 return BAD_VALUE;
1819 }
1820
1821 auto err = offlineClient->initialize(mCameraProviderManager, mMonitorTags);
1822 if (err != OK) {
1823 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
1824 return err;
1825 }
1826
1827 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
1828 if (evicted.size() > 0) {
1829 for (auto& i : evicted) {
1830 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
1831 __FUNCTION__, i->getKey().string());
1832 }
1833
1834 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
1835 "properly", __FUNCTION__);
1836
1837 return BAD_VALUE;
1838 }
1839
1840 logConnectedOffline(offlineClientDesc->getKey(),
1841 static_cast<int>(offlineClientDesc->getOwnerId()),
1842 String8(offlineClient->getPackageName()));
1843
1844 sp<IBinder> remoteCallback = offlineClient->getRemote();
1845 if (remoteCallback != nullptr) {
1846 remoteCallback->linkToDeath(this);
1847 }
1848 } // lock is destroyed, allow further connect calls
1849
1850 return OK;
1851}
1852
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001853Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001854 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001855 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001856
1857 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07001858 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001859 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001860 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1861 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001862 }
1863
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001864 String8 id = String8(cameraId.string());
Jayant Chowdhary12361932018-08-27 14:46:13 -07001865 int uid = CameraThreadState::getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001866
1867 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08001868 auto state = getCameraState(id);
1869 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001870 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001871 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1872 "Camera ID \"%s\" is a not valid camera ID", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001873 }
1874
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001875 StatusInternal cameraStatus = state->getStatus();
1876 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001877 cameraStatus != StatusInternal::NOT_AVAILABLE) {
1878 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001879 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1880 "Camera ID \"%s\" is a not valid camera ID", id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001881 }
1882
1883 {
1884 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001885 TorchModeStatus status;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001886 status_t err = getTorchStatusLocked(id, &status);
1887 if (err != OK) {
1888 if (err == NAME_NOT_FOUND) {
1889 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1890 "Camera \"%s\" does not have a flash unit", id.string());
1891 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001892 ALOGE("%s: getting current torch status failed for camera %s",
1893 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001894 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1895 "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
1896 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001897 }
1898
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001899 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001900 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001901 ALOGE("%s: torch mode of camera %s is not available because "
1902 "camera is in use", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001903 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1904 "Torch for camera \"%s\" is not available due to an existing camera user",
1905 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001906 } else {
1907 ALOGE("%s: torch mode of camera %s is not available due to "
1908 "insufficient resources", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001909 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1910 "Torch for camera \"%s\" is not available due to insufficient resources",
1911 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001912 }
1913 }
1914 }
1915
Ruben Brunk99e69712015-05-26 17:25:07 -07001916 {
1917 // Update UID map - this is used in the torch status changed callbacks, so must be done
1918 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07001919 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -07001920 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
1921 mTorchUidMap[id].first = uid;
1922 mTorchUidMap[id].second = uid;
1923 } else {
1924 // Set the pending UID
1925 mTorchUidMap[id].first = uid;
1926 }
1927 }
1928
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001929 status_t err = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07001930
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001931 if (err != OK) {
1932 int32_t errorCode;
1933 String8 msg;
1934 switch (err) {
1935 case -ENOSYS:
1936 msg = String8::format("Camera \"%s\" has no flashlight",
1937 id.string());
1938 errorCode = ERROR_ILLEGAL_ARGUMENT;
1939 break;
1940 default:
1941 msg = String8::format(
1942 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
1943 id.string(), enabled, strerror(-err), err);
1944 errorCode = ERROR_INVALID_OPERATION;
1945 }
1946 ALOGE("%s: %s", __FUNCTION__, msg.string());
1947 return STATUS_ERROR(errorCode, msg.string());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001948 }
1949
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001950 {
1951 // update the link to client's death
1952 Mutex::Autolock al(mTorchClientMapMutex);
1953 ssize_t index = mTorchClientMap.indexOfKey(id);
1954 if (enabled) {
1955 if (index == NAME_NOT_FOUND) {
1956 mTorchClientMap.add(id, clientBinder);
1957 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07001958 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001959 mTorchClientMap.replaceValueAt(index, clientBinder);
1960 }
1961 clientBinder->linkToDeath(this);
1962 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07001963 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001964 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001965 }
1966
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07001967 int clientPid = CameraThreadState::getCallingPid();
1968 const char *id_cstr = id.c_str();
1969 const char *torchState = enabled ? "on" : "off";
1970 ALOGI("Torch for camera id %s turned %s for client PID %d", id_cstr, torchState, clientPid);
1971 logTorchEvent(id_cstr, torchState , clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001972 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001973}
1974
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001975Status CameraService::notifySystemEvent(int32_t eventId,
1976 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001977 const int pid = CameraThreadState::getCallingPid();
1978 const int selfPid = getpid();
1979
1980 // Permission checks
1981 if (pid != selfPid) {
1982 // Ensure we're being called by system_server, or similar process with
1983 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001984 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001985 const int uid = CameraThreadState::getCallingUid();
1986 ALOGE("Permission Denial: cannot send updates to camera service about system"
1987 " events from pid=%d, uid=%d", pid, uid);
1988 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09001989 "No permission to send updates to camera service about system events"
1990 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001991 }
1992 }
1993
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001994 ATRACE_CALL();
1995
Ruben Brunk36597b22015-03-20 22:15:57 -07001996 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001997 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001998 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07001999 // from a system server crash
2000 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08002001 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002002 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07002003 break;
2004 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002005 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07002006 default: {
2007 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
2008 eventId);
2009 break;
2010 }
2011 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002012 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002013}
2014
Emilian Peev53722fa2019-02-22 17:47:20 -08002015void CameraService::notifyMonitoredUids() {
2016 Mutex::Autolock lock(mStatusListenerLock);
2017
2018 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002019 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Emilian Peev53722fa2019-02-22 17:47:20 -08002020 if (!ret.isOk()) {
2021 ALOGE("%s: Failed to trigger permission callback: %d", __FUNCTION__,
2022 ret.exceptionCode());
2023 }
2024 }
2025}
2026
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002027Status CameraService::notifyDeviceStateChange(int64_t newState) {
2028 const int pid = CameraThreadState::getCallingPid();
2029 const int selfPid = getpid();
2030
2031 // Permission checks
2032 if (pid != selfPid) {
2033 // Ensure we're being called by system_server, or similar process with
2034 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002035 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002036 const int uid = CameraThreadState::getCallingUid();
2037 ALOGE("Permission Denial: cannot send updates to camera service about device"
2038 " state changes from pid=%d, uid=%d", pid, uid);
2039 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2040 "No permission to send updates to camera service about device state"
2041 " changes from pid=%d, uid=%d", pid, uid);
2042 }
2043 }
2044
2045 ATRACE_CALL();
2046
2047 using hardware::camera::provider::V2_5::DeviceState;
2048 hardware::hidl_bitfield<DeviceState> newDeviceState{};
2049 if (newState & ICameraService::DEVICE_STATE_BACK_COVERED) {
2050 newDeviceState |= DeviceState::BACK_COVERED;
2051 }
2052 if (newState & ICameraService::DEVICE_STATE_FRONT_COVERED) {
2053 newDeviceState |= DeviceState::FRONT_COVERED;
2054 }
2055 if (newState & ICameraService::DEVICE_STATE_FOLDED) {
2056 newDeviceState |= DeviceState::FOLDED;
2057 }
2058 // Only map vendor bits directly
2059 uint64_t vendorBits = static_cast<uint64_t>(newState) & 0xFFFFFFFF00000000l;
2060 newDeviceState |= vendorBits;
2061
2062 ALOGV("%s: New device state 0x%" PRIx64, __FUNCTION__, newDeviceState);
2063 Mutex::Autolock l(mServiceLock);
2064 mCameraProviderManager->notifyDeviceStateChange(newDeviceState);
2065
2066 return Status::ok();
2067}
2068
Jayant Chowdharycad23c22020-03-10 15:04:59 -07002069 Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002070 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
2071 ATRACE_CALL();
2072 if (!concurrentCameraIds) {
2073 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
2074 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
2075 }
2076
2077 if (!mInitialized) {
2078 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2079 return STATUS_ERROR(ERROR_DISCONNECTED,
2080 "Camera subsystem is not available");
2081 }
2082 // First call into the provider and get the set of concurrent camera
2083 // combinations
2084 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07002085 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002086 for (auto &combination : concurrentCameraCombinations) {
2087 std::vector<std::string> validCombination;
2088 for (auto &cameraId : combination) {
2089 // if the camera state is not present, skip
2090 String8 cameraIdStr(cameraId.c_str());
2091 auto state = getCameraState(cameraIdStr);
2092 if (state == nullptr) {
2093 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
2094 continue;
2095 }
2096 StatusInternal status = state->getStatus();
2097 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
2098 continue;
2099 }
2100 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
2101 continue;
2102 }
2103 validCombination.push_back(cameraId);
2104 }
2105 if (validCombination.size() != 0) {
2106 concurrentCameraIds->push_back(std::move(validCombination));
2107 }
2108 }
2109 return Status::ok();
2110}
2111
2112Status CameraService::isConcurrentSessionConfigurationSupported(
2113 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
2114 /*out*/bool* isSupported) {
2115 if (!isSupported) {
2116 ALOGE("%s: isSupported is NULL", __FUNCTION__);
2117 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
2118 }
2119
2120 if (!mInitialized) {
2121 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2122 return STATUS_ERROR(ERROR_DISCONNECTED,
2123 "Camera subsystem is not available");
2124 }
2125
2126 // Check for camera permissions
2127 int callingPid = CameraThreadState::getCallingPid();
2128 int callingUid = CameraThreadState::getCallingUid();
2129 if ((callingPid != getpid()) && !checkPermission(sCameraPermission, callingPid, callingUid)) {
2130 ALOGE("%s: pid %d doesn't have camera permissions", __FUNCTION__, callingPid);
2131 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2132 "android.permission.CAMERA needed to call"
2133 "isConcurrentSessionConfigurationSupported");
2134 }
2135
2136 status_t res =
2137 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
2138 cameraIdsAndSessionConfigurations, isSupported);
2139 if (res != OK) {
2140 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
2141 "support %s (%d)", strerror(-res), res);
2142 }
2143 return Status::ok();
2144}
2145
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002146Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
2147 /*out*/
2148 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002149 return addListenerHelper(listener, cameraStatuses);
2150}
2151
2152Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
2153 /*out*/
2154 std::vector<hardware::CameraStatus> *cameraStatuses,
2155 bool isVendorListener) {
2156
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002157 ATRACE_CALL();
2158
Igor Murashkinbfc99152013-02-27 12:55:20 -08002159 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08002160
Ruben Brunk3450ba72015-06-16 11:00:37 -07002161 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002162 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002163 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002164 }
2165
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002166 auto clientUid = CameraThreadState::getCallingUid();
2167 auto clientPid = CameraThreadState::getCallingPid();
Shuzhen Wang695044d2020-03-06 09:02:23 -08002168 bool openCloseCallbackAllowed = checkPermission(sCameraOpenCloseListenerPermission,
2169 clientPid, clientUid);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002170
Igor Murashkinbfc99152013-02-27 12:55:20 -08002171 Mutex::Autolock lock(mServiceLock);
2172
Ruben Brunkcc776712015-02-17 20:18:47 -08002173 {
2174 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08002175 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002176 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002177 ALOGW("%s: Tried to add listener %p which was already subscribed",
2178 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002179 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08002180 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002181 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002182
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002183 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08002184 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
2185 openCloseCallbackAllowed);
Emilian Peev53722fa2019-02-22 17:47:20 -08002186 auto ret = serviceListener->initialize();
2187 if (ret != NO_ERROR) {
2188 String8 msg = String8::format("Failed to initialize service listener: %s (%d)",
2189 strerror(-ret), ret);
2190 ALOGE("%s: %s", __FUNCTION__, msg.string());
2191 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
2192 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002193 // The listener still needs to be added to the list of listeners, regardless of what
2194 // permissions the listener process has / whether it is a vendor listener. Since it might be
2195 // eligible to listen to other camera ids.
2196 mListenerList.emplace_back(serviceListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08002197 mUidPolicy->registerMonitorUid(clientUid);
Igor Murashkinbfc99152013-02-27 12:55:20 -08002198 }
2199
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002200 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07002201 {
Ruben Brunkcc776712015-02-17 20:18:47 -08002202 Mutex::Autolock lock(mCameraStatesLock);
2203 for (auto& i : mCameraStates) {
Shuzhen Wang43858162020-01-10 13:42:15 -08002204 cameraStatuses->emplace_back(i.first,
2205 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds());
Igor Murashkincba2c162013-03-20 15:56:31 -07002206 }
2207 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002208 // Remove the camera statuses that should be hidden from the client, we do
2209 // this after collecting the states in order to avoid holding
2210 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
2211 // the same time.
2212 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
2213 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
2214 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
2215 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
2216 ALOGE("%s: Invalid camera id %s, skipping status update",
2217 __FUNCTION__, s.cameraId.c_str());
2218 return true;
2219 }
2220 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
2221 clientUid);}), cameraStatuses->end());
2222
Igor Murashkincba2c162013-03-20 15:56:31 -07002223
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002224 /*
2225 * Immediately signal current torch status to this listener only
2226 * This may be a subset of all the devices, so don't include it in the response directly
2227 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002228 {
2229 Mutex::Autolock al(mTorchStatusMutex);
2230 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002231 String16 id = String16(mTorchStatusMap.keyAt(i).string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002232 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002233 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002234 }
2235
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002236 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08002237}
Ruben Brunkcc776712015-02-17 20:18:47 -08002238
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002239Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002240 ATRACE_CALL();
2241
Igor Murashkinbfc99152013-02-27 12:55:20 -08002242 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
2243
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002244 if (listener == 0) {
2245 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002246 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002247 }
2248
Igor Murashkinbfc99152013-02-27 12:55:20 -08002249 Mutex::Autolock lock(mServiceLock);
2250
Ruben Brunkcc776712015-02-17 20:18:47 -08002251 {
2252 Mutex::Autolock lock(mStatusListenerLock);
2253 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002254 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
2255 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid());
2256 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08002257 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002258 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002259 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002260 }
2261 }
2262
2263 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
2264 __FUNCTION__, listener.get());
2265
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002266 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08002267}
2268
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002269Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002270
2271 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002272 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
2273
2274 if (parameters == NULL) {
2275 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002276 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07002277 }
2278
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002279 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002280
2281 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002282 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07002283 // Error logged by caller
2284 return ret;
2285 }
2286
2287 String8 shimParamsString8 = shimParams.flatten();
2288 String16 shimParamsString16 = String16(shimParamsString8);
2289
2290 *parameters = shimParamsString16;
2291
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002292 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07002293}
2294
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002295Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
2296 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002297 ATRACE_CALL();
2298
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002299 const String8 id = String8(cameraId);
2300
2301 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002302
2303 switch (apiVersion) {
2304 case API_VERSION_1:
2305 case API_VERSION_2:
2306 break;
2307 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002308 String8 msg = String8::format("Unknown API version %d", apiVersion);
2309 ALOGE("%s: %s", __FUNCTION__, msg.string());
2310 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002311 }
2312
Emilian Peev28ad2ea2017-02-07 16:14:32 +00002313 int deviceVersion = getDeviceVersion(id);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002314 switch (deviceVersion) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002315 case CAMERA_DEVICE_API_VERSION_1_0:
2316 case CAMERA_DEVICE_API_VERSION_3_0:
2317 case CAMERA_DEVICE_API_VERSION_3_1:
2318 if (apiVersion == API_VERSION_2) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002319 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without shim",
2320 __FUNCTION__, id.string(), deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002321 *isSupported = false;
2322 } else { // if (apiVersion == API_VERSION_1) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002323 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always supported",
2324 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002325 *isSupported = true;
2326 }
2327 break;
2328 case CAMERA_DEVICE_API_VERSION_3_2:
2329 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -07002330 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002331 case CAMERA_DEVICE_API_VERSION_3_5:
Yin-Chia Yeh56d98ba2020-01-16 16:57:14 -08002332 case CAMERA_DEVICE_API_VERSION_3_6:
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002333 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
2334 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002335 *isSupported = true;
2336 break;
2337 case -1: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002338 String8 msg = String8::format("Unknown camera ID %s", id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002339 ALOGE("%s: %s", __FUNCTION__, msg.string());
2340 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002341 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002342 default: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002343 String8 msg = String8::format("Unknown device version %x for device %s",
2344 deviceVersion, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002345 ALOGE("%s: %s", __FUNCTION__, msg.string());
2346 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
2347 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07002348 }
2349
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002350 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002351}
2352
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002353Status CameraService::isHiddenPhysicalCamera(const String16& cameraId,
2354 /*out*/ bool *isSupported) {
2355 ATRACE_CALL();
2356
2357 const String8 id = String8(cameraId);
2358
2359 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
2360 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(id.string());
2361
2362 return Status::ok();
2363}
2364
Ruben Brunkcc776712015-02-17 20:18:47 -08002365void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002366 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002367 for (auto& i : mActiveClientManager.getAll()) {
2368 auto clientSp = i->getValue();
2369 if (clientSp.get() == client) {
2370 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08002371 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07002372 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002373 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08002374}
2375
Ruben Brunkcc776712015-02-17 20:18:47 -08002376bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002377 bool ret = false;
2378 {
2379 // Acquire mServiceLock and prevent other clients from connecting
2380 std::unique_ptr<AutoConditionLock> lock =
2381 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08002382
Igor Murashkin634a5152013-02-20 17:15:11 -08002383
Ruben Brunkcc776712015-02-17 20:18:47 -08002384 std::vector<sp<BasicClient>> evicted;
2385 for (auto& i : mActiveClientManager.getAll()) {
2386 auto clientSp = i->getValue();
2387 if (clientSp.get() == nullptr) {
2388 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2389 mActiveClientManager.remove(i);
2390 continue;
2391 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08002392 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002393 mActiveClientManager.remove(i);
2394 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08002395
Ruben Brunkcc776712015-02-17 20:18:47 -08002396 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002397 clientSp->notifyError(
2398 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002399 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08002400 }
2401 }
2402
Ruben Brunkcc776712015-02-17 20:18:47 -08002403 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2404 // other clients from connecting in mServiceLockWrapper if held
2405 mServiceLock.unlock();
2406
Ruben Brunk36597b22015-03-20 22:15:57 -07002407 // Do not clear caller identity, remote caller should be client proccess
2408
Ruben Brunkcc776712015-02-17 20:18:47 -08002409 for (auto& i : evicted) {
2410 if (i.get() != nullptr) {
2411 i->disconnect();
2412 ret = true;
2413 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002414 }
2415
Ruben Brunkcc776712015-02-17 20:18:47 -08002416 // Reacquire mServiceLock
2417 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08002418
Ruben Brunkcc776712015-02-17 20:18:47 -08002419 } // lock is destroyed, allow further connect calls
2420
2421 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07002422}
2423
Ruben Brunkcc776712015-02-17 20:18:47 -08002424std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
2425 const String8& cameraId) const {
2426 std::shared_ptr<CameraState> state;
2427 {
2428 Mutex::Autolock lock(mCameraStatesLock);
2429 auto iter = mCameraStates.find(cameraId);
2430 if (iter != mCameraStates.end()) {
2431 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002432 }
2433 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002434 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002435}
2436
Ruben Brunkcc776712015-02-17 20:18:47 -08002437sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
2438 // Remove from active clients list
2439 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
2440 if (clientDescriptorPtr == nullptr) {
2441 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
2442 cameraId.string());
2443 return sp<BasicClient>{nullptr};
2444 }
2445
2446 return clientDescriptorPtr->getValue();
Keun young Parkd8973a72012-03-28 14:13:09 -07002447}
2448
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002449void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07002450 // Acquire mServiceLock and prevent other clients from connecting
2451 std::unique_ptr<AutoConditionLock> lock =
2452 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
2453
Ruben Brunk6267b532015-04-30 17:44:07 -07002454 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002455 for (size_t i = 0; i < newUserIds.size(); i++) {
2456 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07002457 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002458 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07002459 return;
2460 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002461 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07002462 }
2463
Ruben Brunka8ca9152015-04-07 14:23:40 -07002464
Ruben Brunk6267b532015-04-30 17:44:07 -07002465 if (newAllowedUsers == mAllowedUsers) {
2466 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
2467 return;
2468 }
2469
2470 logUserSwitch(mAllowedUsers, newAllowedUsers);
2471
2472 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07002473
2474 // Current user has switched, evict all current clients.
2475 std::vector<sp<BasicClient>> evicted;
2476 for (auto& i : mActiveClientManager.getAll()) {
2477 auto clientSp = i->getValue();
2478
2479 if (clientSp.get() == nullptr) {
2480 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2481 continue;
2482 }
2483
Ruben Brunk6267b532015-04-30 17:44:07 -07002484 // Don't evict clients that are still allowed.
2485 uid_t clientUid = clientSp->getClientUid();
2486 userid_t clientUserId = multiuser_get_user_id(clientUid);
2487 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
2488 continue;
2489 }
2490
Ruben Brunk36597b22015-03-20 22:15:57 -07002491 evicted.push_back(clientSp);
2492
2493 String8 curTime = getFormattedCurrentTime();
2494
2495 ALOGE("Evicting conflicting client for camera ID %s due to user change",
2496 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07002497
Ruben Brunk36597b22015-03-20 22:15:57 -07002498 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002499 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00002500 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
2501 " to user switch.", i->getKey().string(),
2502 String8{clientSp->getPackageName()}.string(),
2503 i->getOwnerId(), i->getPriority().getScore(),
2504 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07002505
2506 }
2507
2508 // Do not hold mServiceLock while disconnecting clients, but retain the condition
2509 // blocking other clients from connecting in mServiceLockWrapper if held.
2510 mServiceLock.unlock();
2511
2512 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07002513 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07002514
2515 for (auto& i : evicted) {
2516 i->disconnect();
2517 }
2518
Jayant Chowdhary12361932018-08-27 14:46:13 -07002519 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07002520
2521 // Reacquire mServiceLock
2522 mServiceLock.lock();
2523}
Ruben Brunkcc776712015-02-17 20:18:47 -08002524
Ruben Brunka8ca9152015-04-07 14:23:40 -07002525void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002526 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07002527 Mutex::Autolock l(mLogLock);
2528 mEventLog.add(String8::format("%s : %s", curTime.string(), event));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002529}
2530
Ruben Brunka8ca9152015-04-07 14:23:40 -07002531void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002532 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002533 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002534 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002535 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002536}
2537
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002538void CameraService::logDisconnectedOffline(const char* cameraId, int clientPid,
2539 const char* clientPackage) {
2540 // Log the clients evicted
2541 logEvent(String8::format("DISCONNECT offline device %s client for package %s (PID %d)",
2542 cameraId, clientPackage, clientPid));
2543}
2544
Ruben Brunka8ca9152015-04-07 14:23:40 -07002545void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002546 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002547 // Log the clients evicted
2548 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002549 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002550}
2551
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002552void CameraService::logConnectedOffline(const char* cameraId, int clientPid,
2553 const char* clientPackage) {
2554 // Log the clients evicted
2555 logEvent(String8::format("CONNECT offline device %s client for package %s (PID %d)", cameraId,
2556 clientPackage, clientPid));
2557}
2558
Ruben Brunka8ca9152015-04-07 14:23:40 -07002559void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002560 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002561 // Log the client rejected
2562 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002563 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002564}
2565
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002566void CameraService::logTorchEvent(const char* cameraId, const char *torchState, int clientPid) {
2567 // Log torch event
2568 logEvent(String8::format("Torch for camera id %s turned %s for client PID %d", cameraId,
2569 torchState, clientPid));
2570}
2571
Ruben Brunk6267b532015-04-30 17:44:07 -07002572void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
2573 const std::set<userid_t>& newUserIds) {
2574 String8 newUsers = toString(newUserIds);
2575 String8 oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002576 if (oldUsers.size() == 0) {
2577 oldUsers = "<None>";
2578 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07002579 // Log the new and old users
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002580 logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
Ruben Brunk6267b532015-04-30 17:44:07 -07002581 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002582}
2583
2584void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
2585 // Log the device removal
2586 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
2587}
2588
2589void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
2590 // Log the device removal
2591 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
2592}
2593
2594void CameraService::logClientDied(int clientPid, const char* reason) {
2595 // Log the device removal
2596 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07002597}
2598
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002599void CameraService::logServiceError(const char* msg, int errorCode) {
2600 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002601 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002602}
2603
Ruben Brunk36597b22015-03-20 22:15:57 -07002604status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
2605 uint32_t flags) {
2606
Mathias Agopian65ab4712010-07-14 17:59:35 -07002607 // Permission checks
2608 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002609 case SHELL_COMMAND_TRANSACTION: {
2610 int in = data.readFileDescriptor();
2611 int out = data.readFileDescriptor();
2612 int err = data.readFileDescriptor();
2613 int argc = data.readInt32();
2614 Vector<String16> args;
2615 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
2616 args.add(data.readString16());
2617 }
2618 sp<IBinder> unusedCallback;
2619 sp<IResultReceiver> resultReceiver;
2620 status_t status;
2621 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
2622 return status;
2623 }
2624 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
2625 return status;
2626 }
2627 status = shellCommand(in, out, err, args);
2628 if (resultReceiver != nullptr) {
2629 resultReceiver->send(status);
2630 }
2631 return NO_ERROR;
2632 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002633 }
2634
2635 return BnCameraService::onTransact(code, data, reply, flags);
2636}
2637
Mathias Agopian65ab4712010-07-14 17:59:35 -07002638// We share the media players for shutter and recording sound for all clients.
2639// A reference count is kept to determine when we will actually release the
2640// media players.
2641
Jaekyun Seokef498052018-03-23 13:09:44 +09002642sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
2643 sp<MediaPlayer> mp = new MediaPlayer();
2644 status_t error;
2645 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08002646 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09002647 error = mp->prepare();
2648 }
2649 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00002650 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09002651 mp->disconnect();
2652 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002653 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002654 }
2655 return mp;
2656}
2657
username5755fea2018-12-27 09:48:08 +08002658void CameraService::increaseSoundRef() {
2659 Mutex::Autolock lock(mSoundLock);
2660 mSoundRef++;
2661}
2662
2663void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002664 ATRACE_CALL();
2665
username5755fea2018-12-27 09:48:08 +08002666 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
2667 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
2668 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
2669 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
2670 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
2671 }
2672 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
2673 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
2674 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
2675 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002676 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08002677 }
2678 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
2679 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
2680 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
2681 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
2682 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002683 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002684}
2685
username5755fea2018-12-27 09:48:08 +08002686void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002687 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002688 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002689 if (--mSoundRef) return;
2690
2691 for (int i = 0; i < NUM_SOUNDS; i++) {
2692 if (mSoundPlayer[i] != 0) {
2693 mSoundPlayer[i]->disconnect();
2694 mSoundPlayer[i].clear();
2695 }
2696 }
2697}
2698
2699void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002700 ATRACE_CALL();
2701
Mathias Agopian65ab4712010-07-14 17:59:35 -07002702 LOG1("playSound(%d)", kind);
2703 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002704 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002705 sp<MediaPlayer> player = mSoundPlayer[kind];
2706 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08002707 player->seekTo(0);
2708 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002709 }
2710}
2711
2712// ----------------------------------------------------------------------------
2713
2714CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07002715 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002716 const String16& clientPackageName,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002717 const std::unique_ptr<String16>& clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002718 const String8& cameraIdStr,
2719 int api1CameraId, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002720 int clientPid, uid_t clientUid,
2721 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002722 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08002723 IInterface::asBinder(cameraClient),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002724 clientPackageName, clientFeatureId,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002725 cameraIdStr, cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002726 clientPid, clientUid,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002727 servicePid),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002728 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08002729{
Jayant Chowdhary12361932018-08-27 14:46:13 -07002730 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002731 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002732
Igor Murashkin44cfcf02013-03-01 16:22:28 -08002733 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002734
username5755fea2018-12-27 09:48:08 +08002735 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002736
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002737 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002738}
2739
Mathias Agopian65ab4712010-07-14 17:59:35 -07002740// tear down the client
2741CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002742 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08002743 mDestructionStarted = true;
2744
username5755fea2018-12-27 09:48:08 +08002745 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002746 // unconditionally disconnect. function is idempotent
2747 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002748}
2749
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002750sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
2751
Igor Murashkin634a5152013-02-20 17:15:11 -08002752CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002753 const sp<IBinder>& remoteCallback,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002754 const String16& clientPackageName, const std::unique_ptr<String16>& clientFeatureId,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002755 const String8& cameraIdStr, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002756 int clientPid, uid_t clientUid,
2757 int servicePid):
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002758 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002759 mClientPackageName(clientPackageName),
2760 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002761 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07002762 mDisconnected(false), mUidIsTrusted(false),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002763 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002764 mRemoteBinder(remoteCallback)
Igor Murashkin634a5152013-02-20 17:15:11 -08002765{
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002766 if (clientFeatureId) {
2767 mClientFeatureId = std::unique_ptr<String16>(new String16(*clientFeatureId));
2768 } else {
2769 mClientFeatureId = std::unique_ptr<String16>();
2770 }
2771
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002772 if (sCameraService == nullptr) {
2773 sCameraService = cameraService;
2774 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002775 mOpsActive = false;
Igor Murashkin634a5152013-02-20 17:15:11 -08002776 mDestructionStarted = false;
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08002777
2778 // In some cases the calling code has no access to the package it runs under.
2779 // For example, NDK camera API.
2780 // In this case we will get the packages for the calling UID and pick the first one
2781 // for attributing the app op. This will work correctly for runtime permissions
2782 // as for legacy apps we will toggle the app op for all packages in the UID.
2783 // The caveat is that the operation may be attributed to the wrong package and
2784 // stats based on app ops may be slightly off.
2785 if (mClientPackageName.size() <= 0) {
2786 sp<IServiceManager> sm = defaultServiceManager();
2787 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
2788 if (binder == 0) {
2789 ALOGE("Cannot get permission service");
2790 // Leave mClientPackageName unchanged (empty) and the further interaction
2791 // with camera will fail in BasicClient::startCameraOps
2792 return;
2793 }
2794
2795 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
2796 Vector<String16> packages;
2797
2798 permCtrl->getPackagesForUid(mClientUid, packages);
2799
2800 if (packages.isEmpty()) {
2801 ALOGE("No packages for calling UID");
2802 // Leave mClientPackageName unchanged (empty) and the further interaction
2803 // with camera will fail in BasicClient::startCameraOps
2804 return;
2805 }
2806 mClientPackageName = packages[0];
2807 }
Steven Moreland89a2c5c2020-01-31 15:02:25 -08002808 if (getCurrentServingCall() != BinderCallType::HWBINDER) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002809 mAppOpsManager = std::make_unique<AppOpsManager>();
2810 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07002811
2812 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08002813}
2814
2815CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002816 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08002817 mDestructionStarted = true;
2818}
2819
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002820binder::Status CameraService::BasicClient::disconnect() {
2821 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002822 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002823 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07002824 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07002825 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002826
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002827 sCameraService->removeByClient(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002828 sCameraService->logDisconnected(mCameraIdStr, mClientPid, String8(mClientPackageName));
Peter Kalauskasa29c1352018-10-10 12:05:42 -07002829 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
2830 mCameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002831
2832 sp<IBinder> remote = getRemote();
2833 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002834 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08002835 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002836
2837 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07002838 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002839 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
2840 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
2841 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002842
Igor Murashkincba2c162013-03-20 15:56:31 -07002843 // client shouldn't be able to call into us anymore
2844 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002845
2846 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08002847}
2848
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002849status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
2850 // No dumping of clients directly over Binder,
2851 // must go through CameraService::dump
2852 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07002853 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002854 return OK;
2855}
2856
Ruben Brunkcc776712015-02-17 20:18:47 -08002857String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002858 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08002859}
2860
2861
2862int CameraService::BasicClient::getClientPid() const {
2863 return mClientPid;
2864}
2865
Ruben Brunk6267b532015-04-30 17:44:07 -07002866uid_t CameraService::BasicClient::getClientUid() const {
2867 return mClientUid;
2868}
2869
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002870bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
2871 // Defaults to API2.
2872 return level == API_2;
2873}
2874
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002875status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002876 {
2877 Mutex::Autolock l(mAudioRestrictionLock);
2878 mAudioRestriction = mode;
2879 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002880 sCameraService->updateAudioRestriction();
2881 return OK;
2882}
2883
2884int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002885 return sCameraService->updateAudioRestriction();
2886}
2887
2888int32_t CameraService::BasicClient::getAudioRestriction() const {
2889 Mutex::Autolock l(mAudioRestrictionLock);
2890 return mAudioRestriction;
2891}
2892
2893bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
2894 switch (mode) {
2895 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
2896 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
2897 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
2898 return true;
2899 default:
2900 return false;
2901 }
2902}
2903
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002904status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002905 ATRACE_CALL();
2906
Igor Murashkine6800ce2013-03-04 17:25:57 -08002907 {
2908 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002909 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08002910 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002911 if (mAppOpsManager != nullptr) {
2912 // Notify app ops that the camera is not available
2913 mOpsCallback = new OpsCallback(this);
2914 int32_t res;
2915 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
2916 mClientPackageName, mOpsCallback);
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002917 res = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
2918 mClientPackageName, /*startIfModeDefault*/ false, mClientFeatureId,
2919 String16("start camera ") + String16(mCameraIdStr));
Igor Murashkine6800ce2013-03-04 17:25:57 -08002920
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002921 if (res == AppOpsManager::MODE_ERRORED) {
2922 ALOGI("Camera %s: Access for \"%s\" has been revoked",
2923 mCameraIdStr.string(), String8(mClientPackageName).string());
2924 return PERMISSION_DENIED;
2925 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002926
Shuzhen Wang2c656792020-04-13 17:36:49 -07002927 // If the calling Uid is trusted (a native service), the AppOpsManager could
2928 // return MODE_IGNORED. Do not treat such case as error.
2929 if (!mUidIsTrusted && res == AppOpsManager::MODE_IGNORED) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002930 ALOGI("Camera %s: Access for \"%s\" has been restricted",
2931 mCameraIdStr.string(), String8(mClientPackageName).string());
2932 // Return the same error as for device policy manager rejection
2933 return -EACCES;
2934 }
Svetoslav28e8ef72015-05-11 19:21:31 -07002935 }
2936
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002937 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002938
2939 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002940 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002941
Emilian Peev573291c2018-02-10 02:10:56 +00002942 int apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_1;
2943 if (canCastToApiClient(API_2)) {
2944 apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_2;
2945 }
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002946 // Transition device state to OPEN
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002947 sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_OPEN,
Emilian Peev573291c2018-02-10 02:10:56 +00002948 mCameraIdStr, mCameraFacing, mClientPackageName, apiLevel);
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002949
Emilian Peev53722fa2019-02-22 17:47:20 -08002950 sCameraService->mUidPolicy->registerMonitorUid(mClientUid);
2951
Shuzhen Wang695044d2020-03-06 09:02:23 -08002952 // Notify listeners of camera open/close status
2953 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
2954
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002955 return OK;
2956}
2957
2958status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002959 ATRACE_CALL();
2960
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002961 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002962 if (mOpsActive) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002963 // Notify app ops that the camera is available again
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002964 if (mAppOpsManager != nullptr) {
2965 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002966 mClientPackageName, mClientFeatureId);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002967 mOpsActive = false;
2968 }
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002969 // This function is called when a client disconnects. This should
2970 // release the camera, but actually only if it was in a proper
2971 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002972 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002973 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002974
Ruben Brunkcc776712015-02-17 20:18:47 -08002975 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002976 sCameraService->updateStatus(StatusInternal::PRESENT,
2977 mCameraIdStr, rejected);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002978
Emilian Peev573291c2018-02-10 02:10:56 +00002979 int apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_1;
2980 if (canCastToApiClient(API_2)) {
2981 apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_2;
2982 }
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002983 // Transition device state to CLOSED
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002984 sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_CLOSED,
Emilian Peev573291c2018-02-10 02:10:56 +00002985 mCameraIdStr, mCameraFacing, mClientPackageName, apiLevel);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002986 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002987 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002988 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
2989 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002990 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002991 mOpsCallback.clear();
2992
Emilian Peev53722fa2019-02-22 17:47:20 -08002993 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid);
2994
Shuzhen Wang695044d2020-03-06 09:02:23 -08002995 // Notify listeners of camera open/close status
2996 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
2997
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002998 return OK;
2999}
3000
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003001void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003002 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003003 if (mAppOpsManager == nullptr) {
3004 return;
3005 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003006 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003007 if (op != AppOpsManager::OP_CAMERA) {
3008 ALOGW("Unexpected app ops notification received: %d", op);
3009 return;
3010 }
3011
3012 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003013 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003014 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003015 ALOGV("checkOp returns: %d, %s ", res,
3016 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
3017 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
3018 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
3019 "UNKNOWN");
3020
3021 if (res != AppOpsManager::MODE_ALLOWED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003022 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003023 String8(mClientPackageName).string());
Svet Ganova453d0d2018-01-11 15:37:58 -08003024 block();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003025 }
3026}
3027
Svet Ganova453d0d2018-01-11 15:37:58 -08003028void CameraService::BasicClient::block() {
3029 ATRACE_CALL();
3030
3031 // Reset the client PID to allow server-initiated disconnect,
3032 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003033 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08003034 CaptureResultExtras resultExtras; // a dummy result (invalid)
3035 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
3036 disconnect();
3037}
3038
Mathias Agopian65ab4712010-07-14 17:59:35 -07003039// ----------------------------------------------------------------------------
3040
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003041void CameraService::Client::notifyError(int32_t errorCode,
Jianing Weicb0652e2014-03-12 18:29:36 -07003042 const CaptureResultExtras& resultExtras) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08003043 (void) resultExtras;
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003044 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07003045 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
3046 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
3047 api1ErrorCode = CAMERA_ERROR_DISABLED;
3048 }
3049 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003050 } else {
3051 ALOGE("mRemoteCallback is NULL!!");
3052 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003053}
3054
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003055// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003056binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003057 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003058 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08003059}
3060
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003061bool CameraService::Client::canCastToApiClient(apiLevel level) const {
3062 return level == API_1;
3063}
3064
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003065CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
3066 mClient(client) {
3067}
3068
3069void CameraService::Client::OpsCallback::opChanged(int32_t op,
3070 const String16& packageName) {
3071 sp<BasicClient> client = mClient.promote();
3072 if (client != NULL) {
3073 client->opChanged(op, packageName);
3074 }
3075}
3076
Mathias Agopian65ab4712010-07-14 17:59:35 -07003077// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08003078// UidPolicy
3079// ----------------------------------------------------------------------------
3080
3081void CameraService::UidPolicy::registerSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003082 Mutex::Autolock _l(mUidLock);
3083
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003084 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07003085 status_t res = mAm.linkToDeath(this);
3086 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08003087 | ActivityManager::UID_OBSERVER_IDLE
Emilian Peev53722fa2019-02-22 17:47:20 -08003088 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganova453d0d2018-01-11 15:37:58 -08003089 ActivityManager::PROCESS_STATE_UNKNOWN,
3090 String16("cameraserver"));
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003091 if (res == OK) {
3092 mRegistered = true;
3093 ALOGV("UidPolicy: Registered with ActivityManager");
3094 }
Svet Ganova453d0d2018-01-11 15:37:58 -08003095}
3096
3097void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003098 Mutex::Autolock _l(mUidLock);
3099
Steven Moreland2f348142019-07-02 15:59:07 -07003100 mAm.unregisterUidObserver(this);
3101 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003102 mRegistered = false;
3103 mActiveUids.clear();
3104 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08003105}
3106
3107void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
3108 onUidIdle(uid, disabled);
3109}
3110
3111void CameraService::UidPolicy::onUidActive(uid_t uid) {
3112 Mutex::Autolock _l(mUidLock);
3113 mActiveUids.insert(uid);
3114}
3115
3116void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
3117 bool deleted = false;
3118 {
3119 Mutex::Autolock _l(mUidLock);
3120 if (mActiveUids.erase(uid) > 0) {
3121 deleted = true;
3122 }
3123 }
3124 if (deleted) {
3125 sp<CameraService> service = mService.promote();
3126 if (service != nullptr) {
3127 service->blockClientsForUid(uid);
3128 }
3129 }
3130}
3131
Emilian Peev53722fa2019-02-22 17:47:20 -08003132void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07003133 int64_t procStateSeq __unused, int32_t capability __unused) {
Emilian Peev53722fa2019-02-22 17:47:20 -08003134 bool procStateChange = false;
3135 {
3136 Mutex::Autolock _l(mUidLock);
3137 if ((mMonitoredUids.find(uid) != mMonitoredUids.end()) &&
3138 (mMonitoredUids[uid].first != procState)) {
3139 mMonitoredUids[uid].first = procState;
3140 procStateChange = true;
3141 }
3142 }
3143
3144 if (procStateChange) {
3145 sp<CameraService> service = mService.promote();
3146 if (service != nullptr) {
3147 service->notifyMonitoredUids();
3148 }
3149 }
3150}
3151
3152void CameraService::UidPolicy::registerMonitorUid(uid_t uid) {
3153 Mutex::Autolock _l(mUidLock);
3154 auto it = mMonitoredUids.find(uid);
3155 if (it != mMonitoredUids.end()) {
3156 it->second.second++;
3157 } else {
3158 mMonitoredUids.emplace(
3159 std::pair<uid_t, std::pair<int32_t, size_t>> (uid,
3160 std::pair<int32_t, size_t> (ActivityManager::PROCESS_STATE_NONEXISTENT, 1)));
3161 }
3162}
3163
3164void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid) {
3165 Mutex::Autolock _l(mUidLock);
3166 auto it = mMonitoredUids.find(uid);
3167 if (it != mMonitoredUids.end()) {
3168 it->second.second--;
3169 if (it->second.second == 0) {
3170 mMonitoredUids.erase(it);
3171 }
3172 } else {
3173 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
3174 }
3175}
3176
Svet Ganov7b4ab782018-03-25 12:48:10 -07003177bool CameraService::UidPolicy::isUidActive(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003178 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003179 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003180}
3181
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003182static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
3183static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003184
Svet Ganov7b4ab782018-03-25 12:48:10 -07003185bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003186 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003187 // If activity manager is unreachable, assume everything is active
3188 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003189 return true;
3190 }
3191 auto it = mOverrideUids.find(uid);
3192 if (it != mOverrideUids.end()) {
3193 return it->second;
3194 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003195 bool active = mActiveUids.find(uid) != mActiveUids.end();
3196 if (!active) {
3197 // We want active UIDs to always access camera with their first attempt since
3198 // there is no guarantee the app is robustly written and would retry getting
3199 // the camera on failure. The inverse case is not a problem as we would take
3200 // camera away soon once we get the callback that the uid is no longer active.
3201 ActivityManager am;
3202 // Okay to access with a lock held as UID changes are dispatched without
3203 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07003204 int64_t startTimeMillis = 0;
3205 do {
3206 // TODO: Fix this b/109950150!
3207 // Okay this is a hack. There is a race between the UID turning active and
3208 // activity being resumed. The proper fix is very risky, so we temporary add
3209 // some polling which should happen pretty rarely anyway as the race is hard
3210 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003211 active = mActiveUids.find(uid) != mActiveUids.end();
Hui Yu12c7ec72020-05-04 17:40:52 +00003212 if (!active) active = am.isUidActive(uid, callingPackage);
Svet Ganov94ec46f2018-06-08 15:03:46 -07003213 if (active) {
3214 break;
3215 }
3216 if (startTimeMillis <= 0) {
3217 startTimeMillis = uptimeMillis();
3218 }
3219 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003220 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003221 if (remainingTimeMillis <= 0) {
3222 break;
3223 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003224 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
3225
3226 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003227 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003228 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003229 } while (true);
3230
Svet Ganov7b4ab782018-03-25 12:48:10 -07003231 if (active) {
3232 // Now that we found out the UID is actually active, cache that
3233 mActiveUids.insert(uid);
3234 }
3235 }
3236 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08003237}
3238
Varun Shahb42f1eb2019-04-16 14:45:13 -07003239int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
3240 Mutex::Autolock _l(mUidLock);
3241 return getProcStateLocked(uid);
3242}
3243
3244int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
3245 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
3246 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
3247 procState = mMonitoredUids[uid].first;
3248 }
3249 return procState;
3250}
3251
Svet Ganov7b4ab782018-03-25 12:48:10 -07003252void CameraService::UidPolicy::UidPolicy::addOverrideUid(uid_t uid,
3253 String16 callingPackage, bool active) {
3254 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08003255}
3256
Svet Ganov7b4ab782018-03-25 12:48:10 -07003257void CameraService::UidPolicy::removeOverrideUid(uid_t uid, String16 callingPackage) {
3258 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08003259}
3260
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003261void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
3262 Mutex::Autolock _l(mUidLock);
3263 ALOGV("UidPolicy: ActivityManager has died");
3264 mRegistered = false;
3265 mActiveUids.clear();
3266}
3267
Svet Ganov7b4ab782018-03-25 12:48:10 -07003268void CameraService::UidPolicy::updateOverrideUid(uid_t uid, String16 callingPackage,
3269 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003270 bool wasActive = false;
3271 bool isActive = false;
3272 {
3273 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003274 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003275 mOverrideUids.erase(uid);
3276 if (insert) {
3277 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
3278 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003279 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003280 }
3281 if (wasActive != isActive && !isActive) {
3282 sp<CameraService> service = mService.promote();
3283 if (service != nullptr) {
3284 service->blockClientsForUid(uid);
3285 }
3286 }
3287}
3288
3289// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08003290// SensorPrivacyPolicy
3291// ----------------------------------------------------------------------------
3292void CameraService::SensorPrivacyPolicy::registerSelf() {
3293 Mutex::Autolock _l(mSensorPrivacyLock);
3294 if (mRegistered) {
3295 return;
3296 }
Steven Moreland3cf67172020-01-29 11:44:22 -08003297 mSpm.addSensorPrivacyListener(this);
3298 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
3299 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003300 if (res == OK) {
3301 mRegistered = true;
3302 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
3303 }
3304}
3305
3306void CameraService::SensorPrivacyPolicy::unregisterSelf() {
3307 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08003308 mSpm.removeSensorPrivacyListener(this);
3309 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003310 mRegistered = false;
3311 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
3312}
3313
3314bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
3315 Mutex::Autolock _l(mSensorPrivacyLock);
3316 return mSensorPrivacyEnabled;
3317}
3318
3319binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
3320 {
3321 Mutex::Autolock _l(mSensorPrivacyLock);
3322 mSensorPrivacyEnabled = enabled;
3323 }
3324 // if sensor privacy is enabled then block all clients from accessing the camera
3325 if (enabled) {
3326 sp<CameraService> service = mService.promote();
3327 if (service != nullptr) {
3328 service->blockAllClients();
3329 }
3330 }
3331 return binder::Status::ok();
3332}
3333
3334void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
3335 Mutex::Autolock _l(mSensorPrivacyLock);
3336 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
3337 mRegistered = false;
3338}
3339
3340// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003341// CameraState
3342// ----------------------------------------------------------------------------
3343
3344CameraService::CameraState::CameraState(const String8& id, int cost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003345 const std::set<String8>& conflicting, SystemCameraKind systemCameraKind) : mId(id),
3346 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
3347 mSystemCameraKind(systemCameraKind) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08003348
3349CameraService::CameraState::~CameraState() {}
3350
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003351CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003352 Mutex::Autolock lock(mStatusLock);
3353 return mStatus;
3354}
3355
Shuzhen Wang43858162020-01-10 13:42:15 -08003356std::vector<String8> CameraService::CameraState::getUnavailablePhysicalIds() const {
3357 Mutex::Autolock lock(mStatusLock);
3358 std::vector<String8> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
3359 return res;
3360}
3361
Ruben Brunkcc776712015-02-17 20:18:47 -08003362CameraParameters CameraService::CameraState::getShimParams() const {
3363 return mShimParams;
3364}
3365
3366void CameraService::CameraState::setShimParams(const CameraParameters& params) {
3367 mShimParams = params;
3368}
3369
3370int CameraService::CameraState::getCost() const {
3371 return mCost;
3372}
3373
3374std::set<String8> CameraService::CameraState::getConflicting() const {
3375 return mConflicting;
3376}
3377
3378String8 CameraService::CameraState::getId() const {
3379 return mId;
3380}
3381
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003382SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
3383 return mSystemCameraKind;
3384}
3385
Shuzhen Wang43858162020-01-10 13:42:15 -08003386bool CameraService::CameraState::addUnavailablePhysicalId(const String8& physicalId) {
3387 Mutex::Autolock lock(mStatusLock);
3388 auto result = mUnavailablePhysicalIds.insert(physicalId);
3389 return result.second;
3390}
3391
3392bool CameraService::CameraState::removeUnavailablePhysicalId(const String8& physicalId) {
3393 Mutex::Autolock lock(mStatusLock);
3394 auto count = mUnavailablePhysicalIds.erase(physicalId);
3395 return count > 0;
3396}
3397
Ruben Brunkcc776712015-02-17 20:18:47 -08003398// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07003399// ClientEventListener
3400// ----------------------------------------------------------------------------
3401
3402void CameraService::ClientEventListener::onClientAdded(
3403 const resource_policy::ClientDescriptor<String8,
3404 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003405 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003406 if (basicClient.get() != nullptr) {
3407 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3408 notifier.noteStartCamera(descriptor.getKey(),
3409 static_cast<int>(basicClient->getClientUid()));
3410 }
3411}
3412
3413void CameraService::ClientEventListener::onClientRemoved(
3414 const resource_policy::ClientDescriptor<String8,
3415 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003416 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003417 if (basicClient.get() != nullptr) {
3418 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3419 notifier.noteStopCamera(descriptor.getKey(),
3420 static_cast<int>(basicClient->getClientUid()));
3421 }
3422}
3423
3424
3425// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003426// CameraClientManager
3427// ----------------------------------------------------------------------------
3428
Ruben Brunk99e69712015-05-26 17:25:07 -07003429CameraService::CameraClientManager::CameraClientManager() {
3430 setListener(std::make_shared<ClientEventListener>());
3431}
3432
Ruben Brunkcc776712015-02-17 20:18:47 -08003433CameraService::CameraClientManager::~CameraClientManager() {}
3434
3435sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
3436 const String8& id) const {
3437 auto descriptor = get(id);
3438 if (descriptor == nullptr) {
3439 return sp<BasicClient>{nullptr};
3440 }
3441 return descriptor->getValue();
3442}
3443
3444String8 CameraService::CameraClientManager::toString() const {
3445 auto all = getAll();
3446 String8 ret("[");
3447 bool hasAny = false;
3448 for (auto& i : all) {
3449 hasAny = true;
3450 String8 key = i->getKey();
3451 int32_t cost = i->getCost();
3452 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00003453 int32_t score = i->getPriority().getScore();
3454 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08003455 auto conflicting = i->getConflicting();
3456 auto clientSp = i->getValue();
3457 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07003458 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08003459 if (clientSp.get() != nullptr) {
3460 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07003461 uid_t clientUid = clientSp->getClientUid();
3462 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003463 }
Emilian Peev8131a262017-02-01 12:33:43 +00003464 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
3465 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08003466
Ruben Brunk6267b532015-04-30 17:44:07 -07003467 if (clientSp.get() != nullptr) {
3468 ret.appendFormat("User Id: %d, ", clientUserId);
3469 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003470 if (packageName.size() != 0) {
3471 ret.appendFormat("Client Package Name: %s", packageName.string());
3472 }
3473
3474 ret.append(", Conflicting Client Devices: {");
3475 for (auto& j : conflicting) {
3476 ret.appendFormat("%s, ", j.string());
3477 }
3478 ret.append("})");
3479 }
3480 if (hasAny) ret.append("\n");
3481 ret.append("]\n");
3482 return ret;
3483}
3484
3485CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3486 const String8& key, const sp<BasicClient>& value, int32_t cost,
Emilian Peev8131a262017-02-01 12:33:43 +00003487 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
3488 int32_t state) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003489
Steven Moreland89a2c5c2020-01-31 15:02:25 -08003490 bool isVendorClient = getCurrentServingCall() == BinderCallType::HWBINDER;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003491 int32_t score_adj = isVendorClient ? kVendorClientScore : score;
3492 int32_t state_adj = isVendorClient ? kVendorClientState: state;
3493
Ruben Brunkcc776712015-02-17 20:18:47 -08003494 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003495 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj, isVendorClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08003496}
3497
3498CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3499 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
3500 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00003501 partial->getConflicting(), partial->getPriority().getScore(),
3502 partial->getOwnerId(), partial->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08003503}
3504
3505// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07003506
3507static const int kDumpLockRetries = 50;
3508static const int kDumpLockSleep = 60000;
3509
3510static bool tryLock(Mutex& mutex)
3511{
3512 bool locked = false;
3513 for (int i = 0; i < kDumpLockRetries; ++i) {
3514 if (mutex.tryLock() == NO_ERROR) {
3515 locked = true;
3516 break;
3517 }
3518 usleep(kDumpLockSleep);
3519 }
3520 return locked;
3521}
3522
3523status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003524 ATRACE_CALL();
3525
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003526 if (checkCallingPermission(sDumpPermission) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003527 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07003528 CameraThreadState::getCallingPid(),
3529 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003530 return NO_ERROR;
3531 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003532 bool locked = tryLock(mServiceLock);
3533 // failed to lock - CameraService is probably deadlocked
3534 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003535 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003536 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003537
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003538 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003539 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07003540
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003541 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003542 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08003543
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003544 if (locked) mServiceLock.unlock();
3545 return NO_ERROR;
3546 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003547 dprintf(fd, "\n== Service global info: ==\n\n");
3548 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003549 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07003550 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
3551 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003552 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
3553 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
3554 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003555 String8 activeClientString = mActiveClientManager.toString();
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003556 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
3557 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003558
3559 dumpEventLog(fd);
3560
3561 bool stateLocked = tryLock(mCameraStatesLock);
3562 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003563 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003564 }
3565
Emilian Peevbd8c5032018-02-14 23:05:40 +00003566 int argSize = args.size();
3567 for (int i = 0; i < argSize; i++) {
3568 if (args[i] == TagMonitor::kMonitorOption) {
3569 if (i + 1 < argSize) {
3570 mMonitorTags = String8(args[i + 1]);
3571 }
3572 break;
3573 }
3574 }
3575
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003576 for (auto& state : mCameraStates) {
3577 String8 cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003578
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003579 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003580
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003581 CameraParameters p = state.second->getShimParams();
3582 if (!p.isEmpty()) {
3583 dprintf(fd, " Camera1 API shim is using parameters:\n ");
3584 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003585 }
3586
3587 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08003588 if (clientDescriptor != nullptr) {
3589 dprintf(fd, " Device %s is open. Client instance dump:\n",
3590 cameraId.string());
3591 dprintf(fd, " Client priority score: %d state: %d\n",
3592 clientDescriptor->getPriority().getScore(),
3593 clientDescriptor->getPriority().getState());
3594 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
3595
3596 auto client = clientDescriptor->getValue();
3597 dprintf(fd, " Client package: %s\n",
3598 String8(client->getPackageName()).string());
3599
3600 client->dumpClient(fd, args);
3601 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003602 dprintf(fd, " Device %s is closed, no client instance\n",
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003603 cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003604 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003605
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003606 }
3607
3608 if (stateLocked) mCameraStatesLock.unlock();
3609
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003610 if (locked) mServiceLock.unlock();
3611
Emilian Peevf53f66e2017-04-11 14:29:43 +01003612 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003613
3614 dprintf(fd, "\n== Vendor tags: ==\n\n");
3615
3616 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
3617 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00003618 sp<VendorTagDescriptorCache> cache =
3619 VendorTagDescriptorCache::getGlobalVendorTagCache();
3620 if (cache == NULL) {
3621 dprintf(fd, "No vendor tags.\n");
3622 } else {
3623 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
3624 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003625 } else {
3626 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
3627 }
3628
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003629 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003630 dprintf(fd, "\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003631 camera3::CameraTraces::dump(fd, args);
3632
3633 // Process dump arguments, if any
3634 int n = args.size();
3635 String16 verboseOption("-v");
3636 String16 unreachableOption("--unreachable");
3637 for (int i = 0; i < n; i++) {
3638 if (args[i] == verboseOption) {
3639 // change logging level
3640 if (i + 1 >= n) continue;
3641 String8 levelStr(args[i+1]);
3642 int level = atoi(levelStr.string());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003643 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003644 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003645 } else if (args[i] == unreachableOption) {
3646 // Dump memory analysis
3647 // TODO - should limit be an argument parameter?
3648 UnreachableMemoryInfo info;
3649 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
3650 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003651 dprintf(fd, "\n== Unable to dump unreachable memory. "
3652 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003653 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003654 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003655 std::string s = info.ToString(/*log_contents*/ true);
3656 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003657 }
3658 }
3659 }
3660 return NO_ERROR;
3661}
3662
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003663void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003664 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003665
3666 Mutex::Autolock l(mLogLock);
3667 for (const auto& msg : mEventLog) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003668 dprintf(fd, " %s\n", msg.string());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003669 }
3670
3671 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003672 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003673 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003674 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003675 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003676 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003677}
3678
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003679void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003680 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003681 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
3682 if (mTorchClientMap[i] == who) {
3683 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003684 String8 cameraId = mTorchClientMap.keyAt(i);
3685 status_t res = mFlashlight->setTorchMode(cameraId, false);
3686 if (res) {
3687 ALOGE("%s: torch client died but couldn't turn off torch: "
3688 "%s (%d)", __FUNCTION__, strerror(-res), res);
3689 return;
3690 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003691 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003692 break;
3693 }
3694 }
3695}
3696
Ruben Brunkcc776712015-02-17 20:18:47 -08003697/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003698
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003699 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07003700 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
3701 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003702 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003703 // PID here is approximate and can be wrong.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003704 logClientDied(CameraThreadState::getCallingPid(), String8("Binder died unexpectedly"));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003705
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003706 // check torch client
3707 handleTorchClientBinderDied(who);
3708
3709 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08003710 if(!evictClientIdByRemote(who)) {
3711 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003712 return;
3713 }
3714
Ruben Brunkcc776712015-02-17 20:18:47 -08003715 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
3716 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003717}
3718
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003719void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003720 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08003721}
3722
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003723void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
3724 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003725 // Do not lock mServiceLock here or can get into a deadlock from
3726 // connect() -> disconnect -> updateStatus
3727
3728 auto state = getCameraState(cameraId);
3729
3730 if (state == nullptr) {
3731 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
3732 cameraId.string());
3733 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07003734 }
3735
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003736 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
3737 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3738 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3739 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
3740 return;
3741 }
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003742 bool supportsHAL3 = false;
3743 // supportsCameraApi also holds mInterfaceMutex, we can't call it in the
3744 // HIDL onStatusChanged wrapper call (we'll hold mStatusListenerLock and
3745 // mInterfaceMutex together, which can lead to deadlocks)
3746 binder::Status sRet =
3747 supportsCameraApi(String16(cameraId), hardware::ICameraService::API_VERSION_2,
3748 &supportsHAL3);
3749 if (!sRet.isOk()) {
3750 ALOGW("%s: Failed to determine if device supports HAL3 %s, supportsCameraApi call failed",
3751 __FUNCTION__, cameraId.string());
3752 return;
3753 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003754
3755 // Collect the logical cameras without holding mStatusLock in updateStatus
3756 // as that can lead to a deadlock(b/162192331).
3757 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08003758 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08003759 // of the listeners with both the mStatusLock and mStatusListenerLock held
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003760 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind, &supportsHAL3,
3761 &logicalCameraIds]
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003762 (const String8& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003763
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003764 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003765 // Update torch status if it has a flash unit.
3766 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003767 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003768 if (getTorchStatusLocked(cameraId, &torchStatus) !=
3769 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003770 TorchModeStatus newTorchStatus =
3771 status == StatusInternal::PRESENT ?
3772 TorchModeStatus::AVAILABLE_OFF :
3773 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003774 if (torchStatus != newTorchStatus) {
3775 onTorchStatusChangedLocked(cameraId, newTorchStatus);
3776 }
3777 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003778 }
3779
3780 Mutex::Autolock lock(mStatusListenerLock);
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003781 notifyPhysicalCameraStatusLocked(mapToInterface(status), String16(cameraId),
3782 logicalCameraIds, deviceKind);
Shuzhen Wang43858162020-01-10 13:42:15 -08003783
Ruben Brunkcc776712015-02-17 20:18:47 -08003784 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003785 bool isVendorListener = listener->isVendorListener();
3786 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
3787 listener->getListenerPid(), listener->getListenerUid()) ||
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07003788 (isVendorListener && !supportsHAL3)) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003789 ALOGV("Skipping discovery callback for system-only camera/HAL1 device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003790 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003791 continue;
3792 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003793 listener->getListener()->onStatusChanged(mapToInterface(status),
Emilian Peev53722fa2019-02-22 17:47:20 -08003794 String16(cameraId));
Ruben Brunkcc776712015-02-17 20:18:47 -08003795 }
3796 });
Igor Murashkincba2c162013-03-20 15:56:31 -07003797}
3798
Shuzhen Wang695044d2020-03-06 09:02:23 -08003799void CameraService::updateOpenCloseStatus(const String8& cameraId, bool open,
3800 const String16& clientPackageName) {
3801 Mutex::Autolock lock(mStatusListenerLock);
3802
3803 for (const auto& it : mListenerList) {
3804 if (!it->isOpenCloseCallbackAllowed()) {
3805 continue;
3806 }
3807
3808 binder::Status ret;
3809 String16 cameraId64(cameraId);
3810 if (open) {
3811 ret = it->getListener()->onCameraOpened(cameraId64, clientPackageName);
3812 } else {
3813 ret = it->getListener()->onCameraClosed(cameraId64);
3814 }
3815 if (!ret.isOk()) {
3816 ALOGE("%s: Failed to trigger onCameraOpened/onCameraClosed callback: %d", __FUNCTION__,
3817 ret.exceptionCode());
3818 }
3819 }
3820}
3821
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003822template<class Func>
3823void CameraService::CameraState::updateStatus(StatusInternal status,
3824 const String8& cameraId,
3825 std::initializer_list<StatusInternal> rejectSourceStates,
3826 Func onStatusUpdatedLocked) {
3827 Mutex::Autolock lock(mStatusLock);
3828 StatusInternal oldStatus = mStatus;
3829 mStatus = status;
3830
3831 if (oldStatus == status) {
3832 return;
3833 }
3834
3835 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
3836 cameraId.string(), oldStatus, status);
3837
3838 if (oldStatus == StatusInternal::NOT_PRESENT &&
3839 (status != StatusInternal::PRESENT &&
3840 status != StatusInternal::ENUMERATING)) {
3841
3842 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
3843 __FUNCTION__);
3844 mStatus = oldStatus;
3845 return;
3846 }
3847
3848 /**
3849 * Sometimes we want to conditionally do a transition.
3850 * For example if a client disconnects, we want to go to PRESENT
3851 * only if we weren't already in NOT_PRESENT or ENUMERATING.
3852 */
3853 for (auto& rejectStatus : rejectSourceStates) {
3854 if (oldStatus == rejectStatus) {
3855 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
3856 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
3857 mStatus = oldStatus;
3858 return;
3859 }
3860 }
3861
3862 onStatusUpdatedLocked(cameraId, status);
3863}
3864
Eino-Ville Talvalae8c96c72017-06-27 12:24:07 -07003865void CameraService::updateProxyDeviceState(int newState,
Emilian Peev573291c2018-02-10 02:10:56 +00003866 const String8& cameraId, int facing, const String16& clientName, int apiLevel) {
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07003867 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
3868 if (proxyBinder == nullptr) return;
3869 String16 id(cameraId);
Emilian Peev573291c2018-02-10 02:10:56 +00003870 proxyBinder->notifyCameraState(id, newState, facing, clientName, apiLevel);
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07003871}
3872
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003873status_t CameraService::getTorchStatusLocked(
3874 const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003875 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003876 if (!status) {
3877 return BAD_VALUE;
3878 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003879 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3880 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003881 // invalid camera ID or the camera doesn't have a flash unit
3882 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003883 }
3884
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003885 *status = mTorchStatusMap.valueAt(index);
3886 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003887}
3888
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003889status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003890 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003891 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3892 if (index == NAME_NOT_FOUND) {
3893 return BAD_VALUE;
3894 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003895 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003896
3897 return OK;
3898}
3899
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003900std::list<String16> CameraService::getLogicalCameras(
3901 const String8& physicalCameraId) {
3902 std::list<String16> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08003903 Mutex::Autolock lock(mCameraStatesLock);
3904 for (const auto& state : mCameraStates) {
3905 std::vector<std::string> physicalCameraIds;
3906 if (!mCameraProviderManager->isLogicalCamera(state.first.c_str(), &physicalCameraIds)) {
3907 // This is not a logical multi-camera.
3908 continue;
3909 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003910 if (std::find(physicalCameraIds.begin(), physicalCameraIds.end(), physicalCameraId.c_str())
Shuzhen Wang43858162020-01-10 13:42:15 -08003911 == physicalCameraIds.end()) {
3912 // cameraId is not a physical camera of this logical multi-camera.
3913 continue;
3914 }
3915
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003916 retList.emplace_back(String16(state.first));
3917 }
3918 return retList;
3919}
3920
3921void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
3922 const String16& physicalCameraId, const std::list<String16>& logicalCameraIds,
3923 SystemCameraKind deviceKind) {
3924 // mStatusListenerLock is expected to be locked
3925 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08003926 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003927 // Note: we check only the deviceKind of the physical camera id
3928 // since, logical camera ids and their physical camera ids are
3929 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07003930 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
3931 listener->getListenerPid(), listener->getListenerUid())) {
3932 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003933 String8(physicalCameraId).c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07003934 continue;
3935 }
Shuzhen Wang43858162020-01-10 13:42:15 -08003936 listener->getListener()->onPhysicalCameraStatusChanged(status,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003937 logicalCameraId, physicalCameraId);
Shuzhen Wang43858162020-01-10 13:42:15 -08003938 }
3939 }
3940}
3941
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003942
Svet Ganova453d0d2018-01-11 15:37:58 -08003943void CameraService::blockClientsForUid(uid_t uid) {
3944 const auto clients = mActiveClientManager.getAll();
3945 for (auto& current : clients) {
3946 if (current != nullptr) {
3947 const auto basicClient = current->getValue();
3948 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
3949 basicClient->block();
3950 }
3951 }
3952 }
3953}
3954
Michael Grooverd1d435a2018-12-18 17:39:42 -08003955void CameraService::blockAllClients() {
3956 const auto clients = mActiveClientManager.getAll();
3957 for (auto& current : clients) {
3958 if (current != nullptr) {
3959 const auto basicClient = current->getValue();
3960 if (basicClient.get() != nullptr) {
3961 basicClient->block();
3962 }
3963 }
3964 }
3965}
3966
Svet Ganova453d0d2018-01-11 15:37:58 -08003967// NOTE: This is a remote API - make sure all args are validated
3968status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
3969 if (!checkCallingPermission(sManageCameraPermission, nullptr, nullptr)) {
3970 return PERMISSION_DENIED;
3971 }
3972 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
3973 return BAD_VALUE;
3974 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003975 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003976 return handleSetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07003977 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003978 return handleResetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07003979 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003980 return handleGetUidState(args, out, err);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003981 } else if (args.size() >= 2 && args[0] == String16("set-rotate-and-crop")) {
3982 return handleSetRotateAndCrop(args);
3983 } else if (args.size() >= 1 && args[0] == String16("get-rotate-and-crop")) {
3984 return handleGetRotateAndCrop(out);
Svet Ganova453d0d2018-01-11 15:37:58 -08003985 } else if (args.size() == 1 && args[0] == String16("help")) {
3986 printHelp(out);
3987 return NO_ERROR;
3988 }
3989 printHelp(err);
3990 return BAD_VALUE;
3991}
3992
3993status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07003994 String16 packageName = args[1];
3995
Svet Ganova453d0d2018-01-11 15:37:58 -08003996 bool active = false;
3997 if (args[2] == String16("active")) {
3998 active = true;
3999 } else if ((args[2] != String16("idle"))) {
4000 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
4001 return BAD_VALUE;
4002 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004003
4004 int userId = 0;
4005 if (args.size() >= 5 && args[3] == String16("--user")) {
4006 userId = atoi(String8(args[4]));
4007 }
4008
4009 uid_t uid;
4010 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
4011 return BAD_VALUE;
4012 }
4013
4014 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08004015 return NO_ERROR;
4016}
4017
4018status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004019 String16 packageName = args[1];
4020
4021 int userId = 0;
4022 if (args.size() >= 4 && args[2] == String16("--user")) {
4023 userId = atoi(String8(args[3]));
4024 }
4025
4026 uid_t uid;
4027 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004028 return BAD_VALUE;
4029 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004030
4031 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08004032 return NO_ERROR;
4033}
4034
4035status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004036 String16 packageName = args[1];
4037
4038 int userId = 0;
4039 if (args.size() >= 4 && args[2] == String16("--user")) {
4040 userId = atoi(String8(args[3]));
4041 }
4042
4043 uid_t uid;
4044 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004045 return BAD_VALUE;
4046 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004047
4048 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004049 return dprintf(out, "active\n");
4050 } else {
4051 return dprintf(out, "idle\n");
4052 }
4053}
4054
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004055status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
4056 int rotateValue = atoi(String8(args[1]));
4057 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
4058 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
4059 Mutex::Autolock lock(mServiceLock);
4060
4061 mOverrideRotateAndCropMode = rotateValue;
4062
4063 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
4064
4065 const auto clients = mActiveClientManager.getAll();
4066 for (auto& current : clients) {
4067 if (current != nullptr) {
4068 const auto basicClient = current->getValue();
4069 if (basicClient.get() != nullptr) {
4070 basicClient->setRotateAndCropOverride(rotateValue);
4071 }
4072 }
4073 }
4074
4075 return OK;
4076}
4077
4078status_t CameraService::handleGetRotateAndCrop(int out) {
4079 Mutex::Autolock lock(mServiceLock);
4080
4081 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
4082}
4083
Svet Ganova453d0d2018-01-11 15:37:58 -08004084status_t CameraService::printHelp(int out) {
4085 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07004086 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
4087 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
4088 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004089 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
4090 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
4091 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08004092 " help print this message\n");
4093}
4094
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004095int32_t CameraService::updateAudioRestriction() {
4096 Mutex::Autolock lock(mServiceLock);
4097 return updateAudioRestrictionLocked();
4098}
4099
4100int32_t CameraService::updateAudioRestrictionLocked() {
4101 int32_t mode = 0;
4102 // iterate through all active client
4103 for (const auto& i : mActiveClientManager.getAll()) {
4104 const auto clientSp = i->getValue();
4105 mode |= clientSp->getAudioRestriction();
4106 }
4107
4108 bool modeChanged = (mAudioRestriction != mode);
4109 mAudioRestriction = mode;
4110 if (modeChanged) {
4111 mAppOps.setCameraAudioRestriction(mode);
4112 }
4113 return mode;
4114}
4115
Mathias Agopian65ab4712010-07-14 17:59:35 -07004116}; // namespace android