blob: 453984e8240a4a5b858ce4188b5bcccb6b9600f5 [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");
Svet Ganova453d0d2018-01-11 15:37:58 -0800129
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700130// Matches with PERCEPTIBLE_APP_ADJ in ProcessList.java
131static constexpr int32_t kVendorClientScore = 200;
132// Matches with PROCESS_STATE_PERSISTENT_UI in ActivityManager.java
133static constexpr int32_t kVendorClientState = 1;
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800134const String8 CameraService::kOfflineDevice("offline-");
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700135
Eino-Ville Talvala7d5569f2019-04-08 13:57:54 -0700136Mutex CameraService::sProxyMutex;
137sp<hardware::ICameraServiceProxy> CameraService::sCameraServiceProxy;
138
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800139CameraService::CameraService() :
140 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800141 mNumberOfCameras(0),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700142 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700143 mSoundRef(0), mInitialized(false),
144 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000145 ALOGI("CameraService started (pid=%d)", getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800146 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700147}
148
Iliyan Malchev8951a972011-04-14 16:55:59 -0700149void CameraService::onFirstRef()
150{
Ruben Brunkcc776712015-02-17 20:18:47 -0800151 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800152
Iliyan Malchev8951a972011-04-14 16:55:59 -0700153 BnCameraService::onFirstRef();
154
Ruben Brunk99e69712015-05-26 17:25:07 -0700155 // Update battery life tracking if service is restarting
156 BatteryNotifier& notifier(BatteryNotifier::getInstance());
157 notifier.noteResetCamera();
158 notifier.noteResetFlashlight();
159
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800160 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800161
Emilian Peevf53f66e2017-04-11 14:29:43 +0100162 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800163 if (res == OK) {
164 mInitialized = true;
165 }
166
Svet Ganova453d0d2018-01-11 15:37:58 -0800167 mUidPolicy = new UidPolicy(this);
168 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800169 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
170 mSensorPrivacyPolicy->registerSelf();
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700171 mAppOps.setCameraAudioRestriction(mAudioRestriction);
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700172 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
173 if (hcs->registerAsService() != android::OK) {
174 ALOGE("%s: Failed to register default android.frameworks.cameraservice.service@1.0",
175 __FUNCTION__);
176 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700177
178 // This needs to be last call in this function, so that it's as close to
179 // ServiceManager::addService() as possible.
180 CameraService::pingCameraServiceProxy();
181 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800182}
183
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800184status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800185 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100186
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800187 std::vector<std::string> deviceIds;
188 {
189 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800190
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800191 if (nullptr == mCameraProviderManager.get()) {
192 mCameraProviderManager = new CameraProviderManager();
193 res = mCameraProviderManager->initialize(this);
194 if (res != OK) {
195 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
196 __FUNCTION__, strerror(-res), res);
197 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100198 }
199 }
200
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800201
202 // Setup vendor tags before we call get_camera_info the first time
203 // because HAL might need to setup static vendor keys in get_camera_info
204 // TODO: maybe put this into CameraProviderManager::initialize()?
205 mCameraProviderManager->setUpVendorTags();
206
207 if (nullptr == mFlashlight.get()) {
208 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700209 }
210
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800211 res = mFlashlight->findFlashUnits();
212 if (res != OK) {
213 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
214 }
215
216 deviceIds = mCameraProviderManager->getCameraDeviceIds();
217 }
218
219
220 for (auto& cameraId : deviceIds) {
221 String8 id8 = String8(cameraId.c_str());
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800222 if (getCameraState(id8) == nullptr) {
223 onDeviceStatusChanged(id8, CameraDeviceStatus::PRESENT);
224 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800225 }
226
227 return OK;
228}
229
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700230sp<ICameraServiceProxy> CameraService::getCameraServiceProxy() {
Christopher Wiley92c06fc2016-02-11 15:40:05 -0800231#ifndef __BRILLO__
Eino-Ville Talvala7d5569f2019-04-08 13:57:54 -0700232 Mutex::Autolock al(sProxyMutex);
233 if (sCameraServiceProxy == nullptr) {
234 sp<IServiceManager> sm = defaultServiceManager();
235 // Use checkService because cameraserver normally starts before the
236 // system server and the proxy service. So the long timeout that getService
237 // has before giving up is inappropriate.
238 sp<IBinder> binder = sm->checkService(String16("media.camera.proxy"));
239 if (binder != nullptr) {
240 sCameraServiceProxy = interface_cast<ICameraServiceProxy>(binder);
241 }
Ruben Brunk2823ce02015-05-19 17:25:13 -0700242 }
Christopher Wiley92c06fc2016-02-11 15:40:05 -0800243#endif
Eino-Ville Talvala7d5569f2019-04-08 13:57:54 -0700244 return sCameraServiceProxy;
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700245}
246
247void CameraService::pingCameraServiceProxy() {
248 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
249 if (proxyBinder == nullptr) return;
Ruben Brunk2823ce02015-05-19 17:25:13 -0700250 proxyBinder->pingForUserUpdate();
Iliyan Malchev8951a972011-04-14 16:55:59 -0700251}
252
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800253void CameraService::broadcastTorchModeStatus(const String8& cameraId, TorchModeStatus status) {
254 Mutex::Autolock lock(mStatusListenerLock);
255
256 for (auto& i : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700257 i->getListener()->onTorchStatusChanged(mapToInterface(status), String16{cameraId});
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800258 }
259}
260
Mathias Agopian65ab4712010-07-14 17:59:35 -0700261CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800262 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800263 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800264 mSensorPrivacyPolicy->unregisterSelf();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700265}
266
Emilian Peevaee727d2017-05-04 16:35:48 +0100267void CameraService::onNewProviderRegistered() {
268 enumerateProviders();
269}
270
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700271void CameraService::filterAPI1SystemCameraLocked(
272 const std::vector<std::string> &normalDeviceIds) {
273 mNormalDeviceIdsWithoutSystemCamera.clear();
274 for (auto &deviceId : normalDeviceIds) {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700275 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
276 if (getSystemCameraKind(String8(deviceId.c_str()), &deviceKind) != OK) {
277 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, deviceId.c_str());
278 continue;
279 }
280 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700281 // All system camera ids will necessarily come after public camera
282 // device ids as per the HAL interface contract.
283 break;
284 }
285 mNormalDeviceIdsWithoutSystemCamera.push_back(deviceId);
286 }
287 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
288 mNormalDeviceIdsWithoutSystemCamera.size());
289}
290
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700291status_t CameraService::getSystemCameraKind(const String8& cameraId, SystemCameraKind *kind) const {
292 auto state = getCameraState(cameraId);
293 if (state != nullptr) {
294 *kind = state->getSystemCameraKind();
295 return OK;
296 }
297 // Hidden physical camera ids won't have CameraState
298 return mCameraProviderManager->getSystemCameraKind(cameraId.c_str(), kind);
299}
300
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800301void CameraService::updateCameraNumAndIds() {
302 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700303 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
304 // Excludes hidden secure cameras
305 mNumberOfCameras =
306 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
307 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800308 mNormalDeviceIds =
309 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700310 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800311}
312
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100313void CameraService::addStates(const String8 id) {
314 std::string cameraId(id.c_str());
315 hardware::camera::common::V1_0::CameraResourceCost cost;
316 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700317 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100318 if (res != OK) {
319 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
320 return;
321 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700322 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
323 if (res != OK) {
324 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
325 return;
326 }
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100327 std::set<String8> conflicting;
328 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
329 conflicting.emplace(String8(cost.conflictingDevices[i].c_str()));
330 }
331
332 {
333 Mutex::Autolock lock(mCameraStatesLock);
334 mCameraStates.emplace(id, std::make_shared<CameraState>(id, cost.resourceCost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700335 conflicting, deviceKind));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100336 }
337
338 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100339 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100340 mTorchStatusMap.add(id, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800341
342 broadcastTorchModeStatus(id, TorchModeStatus::AVAILABLE_OFF);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100343 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800344
345 updateCameraNumAndIds();
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100346 logDeviceAdded(id, "Device added");
347}
348
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100349void CameraService::removeStates(const String8 id) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800350 updateCameraNumAndIds();
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100351 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100352 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100353 mTorchStatusMap.removeItem(id);
354 }
355
356 {
357 Mutex::Autolock lock(mCameraStatesLock);
358 mCameraStates.erase(id);
359 }
360}
361
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800362void CameraService::onDeviceStatusChanged(const String8& id,
363 CameraDeviceStatus newHalStatus) {
364 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
365 id.string(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700366
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800367 StatusInternal newStatus = mapToInternal(newHalStatus);
368
Ruben Brunkcc776712015-02-17 20:18:47 -0800369 std::shared_ptr<CameraState> state = getCameraState(id);
370
371 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700372 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100373 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700374 __FUNCTION__, id.string());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100375
376 // First add as absent to make sure clients are notified below
377 addStates(id);
378
379 updateStatus(newStatus, id);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700380 } else {
381 ALOGE("%s: Bad camera ID %s", __FUNCTION__, id.string());
382 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700383 return;
384 }
385
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800386 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800387
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800388 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800389 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700390 return;
391 }
392
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800393 if (newStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700394 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
395 newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800396
397 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
398 // to this device until the status changes
399 updateStatus(StatusInternal::NOT_PRESENT, id);
400
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800401 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700402 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800403 // Don't do this in updateStatus to avoid deadlock over mServiceLock
404 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700405
Ruben Brunkcc776712015-02-17 20:18:47 -0800406 // Remove cached shim parameters
407 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700408
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800409 // Remove online as well as offline client from the list of active clients,
410 // if they are present
411 clientToDisconnectOnline = removeClientLocked(id);
412 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + id);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700413 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800414
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800415 disconnectClient(id, clientToDisconnectOnline);
416 disconnectClient(kOfflineDevice + id, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700417
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100418 removeStates(id);
Ruben Brunkcc776712015-02-17 20:18:47 -0800419 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800420 if (oldStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700421 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
422 newStatus));
423 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800424 updateStatus(newStatus, id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700425 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800426}
Igor Murashkincba2c162013-03-20 15:56:31 -0700427
Shuzhen Wang43858162020-01-10 13:42:15 -0800428void CameraService::onDeviceStatusChanged(const String8& id,
429 const String8& physicalId,
430 CameraDeviceStatus newHalStatus) {
431 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
432 __FUNCTION__, id.string(), physicalId.string(), newHalStatus);
433
434 StatusInternal newStatus = mapToInternal(newHalStatus);
435
436 std::shared_ptr<CameraState> state = getCameraState(id);
437
438 if (state == nullptr) {
439 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
440 __FUNCTION__, id.string(), physicalId.string());
441 return;
442 }
443
444 StatusInternal logicalCameraStatus = state->getStatus();
445 if (logicalCameraStatus != StatusInternal::PRESENT &&
446 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
447 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
448 __FUNCTION__, physicalId.string(), newHalStatus, logicalCameraStatus);
449 return;
450 }
451
452 bool updated = false;
453 if (newStatus == StatusInternal::PRESENT) {
454 updated = state->removeUnavailablePhysicalId(physicalId);
455 } else {
456 updated = state->addUnavailablePhysicalId(physicalId);
457 }
458
459 if (updated) {
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800460 String8 idCombo = id + " : " + physicalId;
461 if (newStatus == StatusInternal::PRESENT) {
462 logDeviceAdded(idCombo,
463 String8::format("Device status changed to %d", newStatus));
464 } else {
465 logDeviceRemoved(idCombo,
466 String8::format("Device status changed to %d", newStatus));
467 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800468
469 String16 id16(id), physicalId16(physicalId);
470 Mutex::Autolock lock(mStatusListenerLock);
471 for (auto& listener : mListenerList) {
472 listener->getListener()->onPhysicalCameraStatusChanged(mapToInterface(newStatus),
473 id16, physicalId16);
474 }
475 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700476}
477
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800478void CameraService::disconnectClient(const String8& id, sp<BasicClient> clientToDisconnect) {
479 if (clientToDisconnect.get() != nullptr) {
480 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
481 __FUNCTION__, id.string());
482 // Notify the client of disconnection
483 clientToDisconnect->notifyError(
484 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
485 CaptureResultExtras{});
486 // Ensure not in binder RPC so client disconnect PID checks work correctly
487 LOG_ALWAYS_FATAL_IF(CameraThreadState::getCallingPid() != getpid(),
488 "onDeviceStatusChanged must be called from the camera service process!");
489 clientToDisconnect->disconnect();
490 }
491}
492
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800493void CameraService::onTorchStatusChanged(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800494 TorchModeStatus newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800495 Mutex::Autolock al(mTorchStatusMutex);
496 onTorchStatusChangedLocked(cameraId, newStatus);
497}
498
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800499void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800500 TorchModeStatus newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800501 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
502 __FUNCTION__, cameraId.string(), newStatus);
503
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800504 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800505 status_t res = getTorchStatusLocked(cameraId, &status);
506 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700507 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
508 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800509 return;
510 }
511 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800512 return;
513 }
514
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800515 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800516 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800517 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
518 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800519 return;
520 }
521
Ruben Brunkcc776712015-02-17 20:18:47 -0800522 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700523 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700524 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700525 auto iter = mTorchUidMap.find(cameraId);
526 if (iter != mTorchUidMap.end()) {
527 int oldUid = iter->second.second;
528 int newUid = iter->second.first;
529 BatteryNotifier& notifier(BatteryNotifier::getInstance());
530 if (oldUid != newUid) {
531 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800532 if (status == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700533 notifier.noteFlashlightOff(cameraId, oldUid);
534 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800535 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700536 notifier.noteFlashlightOn(cameraId, newUid);
537 }
538 iter->second.second = newUid;
539 } else {
540 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800541 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700542 notifier.noteFlashlightOn(cameraId, oldUid);
543 } else {
544 notifier.noteFlashlightOff(cameraId, oldUid);
545 }
546 }
547 }
548 }
549
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800550 broadcastTorchModeStatus(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800551}
552
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700553static bool hasPermissionsForSystemCamera(int callingPid, int callingUid) {
554 return checkPermission(sSystemCameraPermission, callingPid, callingUid) &&
555 checkPermission(sCameraPermission, callingPid, callingUid);
556}
557
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800558Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700559 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100560 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700561 bool hasSystemCameraPermissions =
562 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
563 CameraThreadState::getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700564 switch (type) {
565 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700566 if (hasSystemCameraPermissions) {
567 *numCameras = static_cast<int>(mNormalDeviceIds.size());
568 } else {
569 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
570 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800571 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700572 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700573 if (hasSystemCameraPermissions) {
574 *numCameras = mNumberOfCameras;
575 } else {
576 *numCameras = mNumberOfCamerasWithoutSystemCamera;
577 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800578 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700579 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800580 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700581 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800582 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
583 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700584 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800585 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700586}
587
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800588Status CameraService::getCameraInfo(int cameraId,
589 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700590 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100591 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700592 std::string cameraIdStr = cameraIdIntToStrLocked(cameraId);
593 if (shouldRejectSystemCameraConnection(String8(cameraIdStr.c_str()))) {
594 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
595 "characteristics for system only device %s: ", cameraIdStr.c_str());
596 }
Emilian Peevaee727d2017-05-04 16:35:48 +0100597
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800598 if (!mInitialized) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800599 return STATUS_ERROR(ERROR_DISCONNECTED,
600 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -0700601 }
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700602 bool hasSystemCameraPermissions =
603 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
604 CameraThreadState::getCallingUid());
605 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
606 if (hasSystemCameraPermissions) {
607 cameraIdBound = mNumberOfCameras;
608 }
609 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800610 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
611 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700612 }
613
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800614 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800615 status_t err = mCameraProviderManager->getCameraInfo(
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700616 cameraIdStr.c_str(), cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100617 if (err != OK) {
618 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
619 "Error retrieving camera info from device %d: %s (%d)", cameraId,
620 strerror(-err), err);
Ruben Brunkcc776712015-02-17 20:18:47 -0800621 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100622
Ruben Brunkcc776712015-02-17 20:18:47 -0800623 return ret;
624}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700625
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800626std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700627 const std::vector<std::string> *deviceIds = &mNormalDeviceIdsWithoutSystemCamera;
628 auto callingPid = CameraThreadState::getCallingPid();
629 auto callingUid = CameraThreadState::getCallingUid();
630 if (checkPermission(sSystemCameraPermission, callingPid, callingUid) ||
631 getpid() == callingPid) {
632 deviceIds = &mNormalDeviceIds;
633 }
634 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(deviceIds->size())) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800635 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700636 __FUNCTION__, cameraIdInt, deviceIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800637 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800638 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800639
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700640 return (*deviceIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800641}
642
643String8 CameraService::cameraIdIntToStr(int cameraIdInt) {
644 Mutex::Autolock lock(mServiceLock);
645 return String8(cameraIdIntToStrLocked(cameraIdInt).c_str());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800646}
647
648Status CameraService::getCameraCharacteristics(const String16& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800649 CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700650 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700651 if (!cameraInfo) {
652 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800653 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -0700654 }
655
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800656 if (!mInitialized) {
657 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800658 return STATUS_ERROR(ERROR_DISCONNECTED,
659 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -0700660 }
661
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700662 if (shouldRejectSystemCameraConnection(String8(cameraId))) {
663 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
664 "characteristics for system only device %s: ", String8(cameraId).string());
665 }
666
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800667 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800668
Emilian Peevf53f66e2017-04-11 14:29:43 +0100669 status_t res = mCameraProviderManager->getCameraCharacteristics(
670 String8(cameraId).string(), cameraInfo);
671 if (res != OK) {
672 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
673 "characteristics for device %s: %s (%d)", String8(cameraId).string(),
674 strerror(-res), res);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700675 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700676 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
677 if (getSystemCameraKind(String8(cameraId), &deviceKind) != OK) {
678 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, String8(cameraId).string());
679 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera kind "
680 "for device %s", String8(cameraId).string());
681 }
Jayant Chowdhary12361932018-08-27 14:46:13 -0700682 int callingPid = CameraThreadState::getCallingPid();
683 int callingUid = CameraThreadState::getCallingUid();
Emilian Peeve20c6372018-08-14 18:45:53 +0100684 std::vector<int32_t> tagsRemoved;
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700685 // If it's not calling from cameraserver, check the permission only if
686 // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
687 // it would've already been checked in shouldRejectSystemCameraConnection.
Emilian Peeve20c6372018-08-14 18:45:53 +0100688 if ((callingPid != getpid()) &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700689 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700690 !checkPermission(sCameraPermission, callingPid, callingUid)) {
Emilian Peeve20c6372018-08-14 18:45:53 +0100691 res = cameraInfo->removePermissionEntries(
692 mCameraProviderManager->getProviderTagIdLocked(String8(cameraId).string()),
693 &tagsRemoved);
694 if (res != OK) {
695 cameraInfo->clear();
696 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
697 " characteristics needing camera permission for device %s: %s (%d)",
698 String8(cameraId).string(), strerror(-res), res);
699 }
700 }
701
702 if (!tagsRemoved.empty()) {
703 res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
704 tagsRemoved.data(), tagsRemoved.size());
705 if (res != OK) {
706 cameraInfo->clear();
707 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
708 "keys needing permission for device %s: %s (%d)", String8(cameraId).string(),
709 strerror(-res), res);
710 }
711 }
712
Zhijun He2b59be82013-09-25 10:14:30 -0700713 return ret;
714}
715
Ruben Brunkcc776712015-02-17 20:18:47 -0800716String8 CameraService::getFormattedCurrentTime() {
717 time_t now = time(nullptr);
718 char formattedTime[64];
719 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
720 return String8(formattedTime);
721}
722
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800723Status CameraService::getCameraVendorTagDescriptor(
724 /*out*/
725 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700726 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800727 if (!mInitialized) {
728 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800729 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800730 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -0800731 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
732 if (globalDescriptor != nullptr) {
733 *desc = *(globalDescriptor.get());
734 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800735 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800736}
737
Emilian Peev71c73a22017-03-21 16:35:51 +0000738Status CameraService::getCameraVendorTagCache(
739 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
740 ATRACE_CALL();
741 if (!mInitialized) {
742 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
743 return STATUS_ERROR(ERROR_DISCONNECTED,
744 "Camera subsystem not available");
745 }
746 sp<VendorTagDescriptorCache> globalCache =
747 VendorTagDescriptorCache::getGlobalVendorTagCache();
748 if (globalCache != nullptr) {
749 *cache = *(globalCache.get());
750 }
751 return Status::ok();
752}
753
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800754int CameraService::getDeviceVersion(const String8& cameraId, int* facing) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700755 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800756
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800757 int deviceVersion = 0;
758
Emilian Peevf53f66e2017-04-11 14:29:43 +0100759 status_t res;
760 hardware::hidl_version maxVersion{0,0};
761 res = mCameraProviderManager->getHighestSupportedVersion(cameraId.string(),
762 &maxVersion);
763 if (res != OK) return -1;
764 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800765
Emilian Peevf53f66e2017-04-11 14:29:43 +0100766 hardware::CameraInfo info;
767 if (facing) {
768 res = mCameraProviderManager->getCameraInfo(cameraId.string(), &info);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -0800769 if (res != OK) return -1;
Emilian Peevf53f66e2017-04-11 14:29:43 +0100770 *facing = info.facing;
Igor Murashkin634a5152013-02-20 17:15:11 -0800771 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100772
Igor Murashkin634a5152013-02-20 17:15:11 -0800773 return deviceVersion;
774}
775
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800776Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700777 switch(err) {
778 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800779 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800780 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800781 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
782 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800783 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800784 return STATUS_ERROR(ERROR_DISCONNECTED,
785 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700786 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800787 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
788 "Camera HAL encountered error %d: %s",
789 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700790 }
Igor Murashkinbfc99152013-02-27 12:55:20 -0800791}
792
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800793Status CameraService::makeClient(const sp<CameraService>& cameraService,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800794 const sp<IInterface>& cameraCb, const String16& packageName,
795 const std::unique_ptr<String16>& featureId, const String8& cameraId, int api1CameraId,
796 int facing, int clientPid, uid_t clientUid, int servicePid, int halVersion,
797 int deviceVersion, apiLevel effectiveApiLevel,
Ruben Brunkcc776712015-02-17 20:18:47 -0800798 /*out*/sp<BasicClient>* client) {
799
Ruben Brunkcc776712015-02-17 20:18:47 -0800800 if (halVersion < 0 || halVersion == deviceVersion) {
801 // Default path: HAL version is unspecified by caller, create CameraClient
802 // based on device version reported by the HAL.
803 switch(deviceVersion) {
804 case CAMERA_DEVICE_API_VERSION_1_0:
805 if (effectiveApiLevel == API_1) { // Camera1 API route
806 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800807 *client = new CameraClient(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800808 api1CameraId, facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700809 getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800810 } else { // Camera2 API route
811 ALOGW("Camera using old HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800812 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800813 "Camera device \"%s\" HAL version %d does not support camera2 API",
814 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800815 }
816 break;
Ruben Brunkcc776712015-02-17 20:18:47 -0800817 case CAMERA_DEVICE_API_VERSION_3_0:
818 case CAMERA_DEVICE_API_VERSION_3_1:
819 case CAMERA_DEVICE_API_VERSION_3_2:
820 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -0700821 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -0700822 case CAMERA_DEVICE_API_VERSION_3_5:
Yin-Chia Yeh56d98ba2020-01-16 16:57:14 -0800823 case CAMERA_DEVICE_API_VERSION_3_6:
Ruben Brunkcc776712015-02-17 20:18:47 -0800824 if (effectiveApiLevel == API_1) { // Camera1 API route
825 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800826 *client = new Camera2Client(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800827 cameraId, api1CameraId,
828 facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700829 servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800830 } else { // Camera2 API route
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800831 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
832 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800833 *client = new CameraDeviceClient(cameraService, tmp, packageName, featureId,
834 cameraId, facing, clientPid, clientUid, servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800835 }
836 break;
837 default:
838 // Should not be reachable
839 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800840 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800841 "Camera device \"%s\" has unknown HAL version %d",
842 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800843 }
844 } else {
845 // A particular HAL version is requested by caller. Create CameraClient
846 // based on the requested HAL version.
847 if (deviceVersion > CAMERA_DEVICE_API_VERSION_1_0 &&
848 halVersion == CAMERA_DEVICE_API_VERSION_1_0) {
849 // Only support higher HAL version device opened as HAL1.0 device.
850 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800851 *client = new CameraClient(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800852 api1CameraId, facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700853 servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800854 } else {
855 // Other combinations (e.g. HAL3.x open as HAL2.x) are not supported yet.
856 ALOGE("Invalid camera HAL version %x: HAL %x device can only be"
857 " opened as HAL %x device", halVersion, deviceVersion,
858 CAMERA_DEVICE_API_VERSION_1_0);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800859 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800860 "Camera device \"%s\" (HAL version %d) cannot be opened as HAL version %d",
861 cameraId.string(), deviceVersion, halVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800862 }
863 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800864 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800865}
866
Ruben Brunk6267b532015-04-30 17:44:07 -0700867String8 CameraService::toString(std::set<userid_t> intSet) {
868 String8 s("");
869 bool first = true;
870 for (userid_t i : intSet) {
871 if (first) {
872 s.appendFormat("%d", i);
873 first = false;
874 } else {
875 s.appendFormat(", %d", i);
876 }
877 }
878 return s;
879}
880
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800881int32_t CameraService::mapToInterface(TorchModeStatus status) {
882 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
883 switch (status) {
884 case TorchModeStatus::NOT_AVAILABLE:
885 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
886 break;
887 case TorchModeStatus::AVAILABLE_OFF:
888 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
889 break;
890 case TorchModeStatus::AVAILABLE_ON:
891 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
892 break;
893 default:
894 ALOGW("Unknown new flash status: %d", status);
895 }
896 return serviceStatus;
897}
898
899CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
900 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
901 switch (status) {
902 case CameraDeviceStatus::NOT_PRESENT:
903 serviceStatus = StatusInternal::NOT_PRESENT;
904 break;
905 case CameraDeviceStatus::PRESENT:
906 serviceStatus = StatusInternal::PRESENT;
907 break;
908 case CameraDeviceStatus::ENUMERATING:
909 serviceStatus = StatusInternal::ENUMERATING;
910 break;
911 default:
912 ALOGW("Unknown new HAL device status: %d", status);
913 }
914 return serviceStatus;
915}
916
917int32_t CameraService::mapToInterface(StatusInternal status) {
918 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
919 switch (status) {
920 case StatusInternal::NOT_PRESENT:
921 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
922 break;
923 case StatusInternal::PRESENT:
924 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
925 break;
926 case StatusInternal::ENUMERATING:
927 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
928 break;
929 case StatusInternal::NOT_AVAILABLE:
930 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
931 break;
932 case StatusInternal::UNKNOWN:
933 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
934 break;
935 default:
936 ALOGW("Unknown new internal device status: %d", status);
937 }
938 return serviceStatus;
939}
940
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800941Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -0700942 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700943
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800944 String16 internalPackageName("cameraserver");
Ruben Brunkcc776712015-02-17 20:18:47 -0800945 String8 id = String8::format("%d", cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800946 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800947 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800948 if (!(ret = connectHelper<ICameraClient,Client>(
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800949 sp<ICameraClient>{nullptr}, id, cameraId,
950 static_cast<int>(CAMERA_HAL_API_VERSION_UNSPECIFIED),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800951 internalPackageName, std::unique_ptr<String16>(), uid, USE_CALLING_PID,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700952 API_1, /*shimUpdateOnly*/ true, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800953 ).isOk()) {
954 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
Ruben Brunkb2119af2014-05-09 19:57:56 -0700955 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800956 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700957}
958
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800959Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -0700960 /*out*/
961 CameraParameters* parameters) {
962
963 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
964
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800965 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -0700966
967 if (parameters == NULL) {
968 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800969 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -0700970 }
971
Ruben Brunkcc776712015-02-17 20:18:47 -0800972 String8 id = String8::format("%d", cameraId);
973
974 // Check if we already have parameters
975 {
976 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -0700977 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -0800978 auto cameraState = getCameraState(id);
979 if (cameraState == nullptr) {
980 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800981 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
982 "Invalid camera ID: %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -0800983 }
984 CameraParameters p = cameraState->getShimParams();
985 if (!p.isEmpty()) {
986 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800987 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700988 }
989 }
990
Jayant Chowdhary12361932018-08-27 14:46:13 -0700991 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -0800992 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -0700993 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800994 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800995 // Error already logged by callee
996 return ret;
997 }
998
999 // Check for parameters again
1000 {
1001 // Scope for service lock
1002 Mutex::Autolock lock(mServiceLock);
1003 auto cameraState = getCameraState(id);
1004 if (cameraState == nullptr) {
1005 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001006 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1007 "Invalid camera ID: %s", id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001008 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001009 CameraParameters p = cameraState->getShimParams();
1010 if (!p.isEmpty()) {
1011 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001012 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001013 }
1014 }
1015
Ruben Brunkcc776712015-02-17 20:18:47 -08001016 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1017 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001018 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001019}
1020
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001021// Can camera service trust the caller based on the calling UID?
1022static bool isTrustedCallingUid(uid_t uid) {
1023 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001024 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001025 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001026 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001027 return true;
1028 default:
1029 return false;
1030 }
1031}
1032
Nicholas Sauera3620332019-04-03 14:05:17 -07001033static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1034 PermissionController pc;
1035 uid = pc.getPackageUid(packageName, 0);
1036 if (uid <= 0) {
1037 ALOGE("Unknown package: '%s'", String8(packageName).string());
1038 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
1039 return BAD_VALUE;
1040 }
1041
1042 if (userId < 0) {
1043 ALOGE("Invalid user: %d", userId);
1044 dprintf(err, "Invalid user: %d\n", userId);
1045 return BAD_VALUE;
1046 }
1047
1048 uid = multiuser_get_uid(userId, uid);
1049 return NO_ERROR;
1050}
1051
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001052Status CameraService::validateConnectLocked(const String8& cameraId,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001053 const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
1054 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001055
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001056#ifdef __BRILLO__
1057 UNUSED(clientName8);
1058 UNUSED(clientUid);
1059 UNUSED(clientPid);
1060 UNUSED(originalClientPid);
1061#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001062 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1063 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001064 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001065 return allowed;
1066 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001067#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001068
Jayant Chowdhary12361932018-08-27 14:46:13 -07001069 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001070
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001071 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001072 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1073 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001074 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1075 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001076 }
1077
Ruben Brunkcc776712015-02-17 20:18:47 -08001078 if (getCameraState(cameraId) == nullptr) {
1079 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1080 cameraId.string());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001081 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1082 "No camera device with ID \"%s\" available", cameraId.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001083 }
1084
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001085 status_t err = checkIfDeviceIsUsable(cameraId);
1086 if (err != NO_ERROR) {
1087 switch(err) {
1088 case -ENODEV:
1089 case -EBUSY:
1090 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1091 "No camera device with ID \"%s\" currently available", cameraId.string());
1092 default:
1093 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1094 "Unknown error connecting to ID \"%s\"", cameraId.string());
1095 }
1096 }
1097 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001098}
1099
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001100Status CameraService::validateClientPermissionsLocked(const String8& cameraId,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001101 const String8& clientName8, int& clientUid, int& clientPid,
1102 /*out*/int& originalClientPid) const {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001103 int callingPid = CameraThreadState::getCallingPid();
1104 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001105
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001106 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001107 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001108 clientUid = callingUid;
1109 } else if (!isTrustedCallingUid(callingUid)) {
1110 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1111 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001112 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1113 "Untrusted caller (calling PID %d, UID %d) trying to "
1114 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1115 callingPid, callingUid, cameraId.string(),
1116 clientName8.string(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001117 }
1118
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001119 // Check if we can trust clientPid
1120 if (clientPid == USE_CALLING_PID) {
1121 clientPid = callingPid;
1122 } else if (!isTrustedCallingUid(callingUid)) {
1123 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1124 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001125 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1126 "Untrusted caller (calling PID %d, UID %d) trying to "
1127 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1128 callingPid, callingUid, cameraId.string(),
1129 clientName8.string(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001130 }
1131
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001132 if (shouldRejectSystemCameraConnection(cameraId)) {
1133 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1134 cameraId.c_str());
1135 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
1136 "available", cameraId.string());
1137 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001138 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1139 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1140 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
1141 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
1142 "found while trying to query device kind", cameraId.string());
1143
1144 }
1145
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001146 // If it's not calling from cameraserver, check the permission if the
1147 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1148 // android.permission.SYSTEM_CAMERA for system only camera devices).
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001149 if (callingPid != getpid() &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001150 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001151 !checkPermission(sCameraPermission, clientPid, clientUid)) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001152 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001153 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1154 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
1155 clientName8.string(), clientUid, clientPid, cameraId.string());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001156 }
1157
Svet Ganova453d0d2018-01-11 15:37:58 -08001158 // Make sure the UID is in an active state to use the camera
Svet Ganov7b4ab782018-03-25 12:48:10 -07001159 if (!mUidPolicy->isUidActive(callingUid, String16(clientName8))) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001160 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001161 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1162 clientPid, clientUid);
1163 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001164 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1165 "calling UID %d proc state %" PRId32 ")",
1166 clientName8.string(), clientUid, clientPid, cameraId.string(),
1167 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001168 }
1169
Michael Grooverd1d435a2018-12-18 17:39:42 -08001170 // If sensor privacy is enabled then prevent access to the camera
1171 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1172 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1173 return STATUS_ERROR_FMT(ERROR_DISABLED,
1174 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
1175 "is enabled", clientName8.string(), clientUid, clientPid, cameraId.string());
1176 }
1177
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001178 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1179 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001180 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001181 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001182
Ruben Brunk6267b532015-04-30 17:44:07 -07001183 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001184
Ruben Brunka8ca9152015-04-07 14:23:40 -07001185 // Only allow clients who are being used by the current foreground device user, unless calling
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001186 // from our own process OR the caller is using the cameraserver's HIDL interface.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001187 if (getCurrentServingCall() != BinderCallType::HWBINDER && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001188 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001189 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1190 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
1191 toString(mAllowedUsers).string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001192 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1193 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
1194 clientUserId, cameraId.string());
Ruben Brunk36597b22015-03-20 22:15:57 -07001195 }
1196
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001197 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001198}
1199
1200status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
1201 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001202 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001203 if (cameraState == nullptr) {
1204 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1205 cameraId.string());
1206 return -ENODEV;
1207 }
1208
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001209 StatusInternal currentStatus = cameraState->getStatus();
1210 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001211 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
1212 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001213 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001214 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001215 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
1216 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001217 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001218 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001219
Ruben Brunkcc776712015-02-17 20:18:47 -08001220 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001221}
1222
Ruben Brunkcc776712015-02-17 20:18:47 -08001223void CameraService::finishConnectLocked(const sp<BasicClient>& client,
1224 const CameraService::DescriptorPtr& desc) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001225
Ruben Brunkcc776712015-02-17 20:18:47 -08001226 // Make a descriptor for the incoming client
1227 auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
1228 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1229
1230 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
1231 String8(client->getPackageName()));
1232
1233 if (evicted.size() > 0) {
1234 // This should never happen - clients should already have been removed in disconnect
1235 for (auto& i : evicted) {
1236 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
1237 __FUNCTION__, i->getKey().string());
1238 }
1239
1240 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1241 __FUNCTION__);
1242 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001243
1244 // And register a death notification for the client callback. Do
1245 // this last to avoid Binder policy where a nested Binder
1246 // transaction might be pre-empted to service the client death
1247 // notification if the client process dies before linkToDeath is
1248 // invoked.
1249 sp<IBinder> remoteCallback = client->getRemote();
1250 if (remoteCallback != nullptr) {
1251 remoteCallback->linkToDeath(this);
1252 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001253}
1254
1255status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
1256 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
1257 /*out*/
1258 sp<BasicClient>* client,
1259 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001260 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001261 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001262 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001263 DescriptorPtr clientDescriptor;
1264 {
1265 if (effectiveApiLevel == API_1) {
1266 // If we are using API1, any existing client for this camera ID with the same remote
1267 // should be returned rather than evicted to allow MediaRecorder to work properly.
1268
1269 auto current = mActiveClientManager.get(cameraId);
1270 if (current != nullptr) {
1271 auto clientSp = current->getValue();
1272 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001273 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
1274 ALOGW("CameraService connect called from same client, but with a different"
1275 " API level, evicting prior client...");
1276 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001277 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001278 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001279 *client = clientSp;
1280 return NO_ERROR;
1281 }
1282 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001283 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001284 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001285
Ruben Brunkcc776712015-02-17 20:18:47 -08001286 // Get current active client PIDs
1287 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1288 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001289
Emilian Peev8131a262017-02-01 12:33:43 +00001290 std::vector<int> priorityScores(ownerPids.size());
1291 std::vector<int> states(ownerPids.size());
Igor Murashkine6800ce2013-03-04 17:25:57 -08001292
Emilian Peev8131a262017-02-01 12:33:43 +00001293 // Get priority scores of all active PIDs
1294 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1295 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1296 /*out*/&priorityScores[0]);
1297 if (err != OK) {
1298 ALOGE("%s: Priority score query failed: %d",
1299 __FUNCTION__, err);
1300 return err;
1301 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001302
Ruben Brunkcc776712015-02-17 20:18:47 -08001303 // Update all active clients' priorities
Emilian Peev8131a262017-02-01 12:33:43 +00001304 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
Ruben Brunkcc776712015-02-17 20:18:47 -08001305 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
Emilian Peev8131a262017-02-01 12:33:43 +00001306 pidToPriorityMap.emplace(ownerPids[i],
Jayant Chowdharyc578a502019-05-08 10:57:54 -07001307 resource_policy::ClientPriority(priorityScores[i], states[i],
1308 /* isVendorClient won't get copied over*/ false));
Ruben Brunkcc776712015-02-17 20:18:47 -08001309 }
1310 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001311
Ruben Brunkcc776712015-02-17 20:18:47 -08001312 // Get state for the given cameraId
1313 auto state = getCameraState(cameraId);
1314 if (state == nullptr) {
1315 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1316 clientPid, cameraId.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001317 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001318 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001319 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001320
1321 // Make descriptor for incoming client
Shuzhen Wang2db86ff2018-04-25 01:11:17 +00001322 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001323 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1324 state->getConflicting(),
Emilian Peev8131a262017-02-01 12:33:43 +00001325 priorityScores[priorityScores.size() - 1],
1326 clientPid,
1327 states[states.size() - 1]);
Ruben Brunkcc776712015-02-17 20:18:47 -08001328
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001329 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1330
Ruben Brunkcc776712015-02-17 20:18:47 -08001331 // Find clients that would be evicted
1332 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1333
1334 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1335 // background, so we cannot do evictions
1336 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1337 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1338 " priority).", clientPid);
1339
1340 sp<BasicClient> clientSp = clientDescriptor->getValue();
1341 String8 curTime = getFormattedCurrentTime();
1342 auto incompatibleClients =
1343 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1344
1345 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Emilian Peev8131a262017-02-01 12:33:43 +00001346 "(PID %d, score %d state %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001347 cameraId.string(), packageName.string(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001348 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001349
1350 for (auto& i : incompatibleClients) {
1351 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001352 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
1353 i->getKey().string(),
1354 String8{i->getValue()->getPackageName()}.string(),
1355 i->getOwnerId(), i->getPriority().getScore(),
1356 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001357 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00001358 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(),
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001359 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001360 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001361 }
1362
1363 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001364 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001365 mEventLog.add(msg);
1366
1367 return -EBUSY;
1368 }
1369
1370 for (auto& i : evicted) {
1371 sp<BasicClient> clientSp = i->getValue();
1372 if (clientSp.get() == nullptr) {
1373 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1374
1375 // TODO: Remove this
1376 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1377 __FUNCTION__);
1378 mActiveClientManager.remove(i);
1379 continue;
1380 }
1381
1382 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1383 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001384 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001385
Ruben Brunkcc776712015-02-17 20:18:47 -08001386 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001387 logEvent(String8::format("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00001388 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1389 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001390 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
Emilian Peev8131a262017-02-01 12:33:43 +00001391 i->getOwnerId(), i->getPriority().getScore(),
1392 i->getPriority().getState(), cameraId.string(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001393 packageName.string(), clientPid, clientPriority.getScore(),
1394 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08001395
1396 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001397 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001398 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001399 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001400 }
1401
Ruben Brunkcc776712015-02-17 20:18:47 -08001402 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1403 // other clients from connecting in mServiceLockWrapper if held
1404 mServiceLock.unlock();
1405
1406 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07001407 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001408
1409 // Destroy evicted clients
1410 for (auto& i : evictedClients) {
1411 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001412 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001413 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001414
Jayant Chowdhary12361932018-08-27 14:46:13 -07001415 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08001416
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001417 for (const auto& i : evictedClients) {
1418 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1419 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1420 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1421 if (ret == TIMED_OUT) {
1422 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1423 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1424 mActiveClientManager.toString().string());
1425 return -EBUSY;
1426 }
1427 if (ret != NO_ERROR) {
1428 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1429 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1430 ret, mActiveClientManager.toString().string());
1431 return ret;
1432 }
1433 }
1434
1435 evictedClients.clear();
1436
Ruben Brunkcc776712015-02-17 20:18:47 -08001437 // Once clients have been disconnected, relock
1438 mServiceLock.lock();
1439
1440 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1441 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1442 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001443 }
1444
Ruben Brunkcc776712015-02-17 20:18:47 -08001445 *partial = clientDescriptor;
1446 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001447}
1448
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001449Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001450 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001451 int api1CameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001452 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001453 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001454 int clientPid,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001455 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001456 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001457
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001458 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001459 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001460
1461 String8 id = cameraIdIntToStr(api1CameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001462 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001463 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001464 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, std::unique_ptr<String16>(),
1465 clientUid, clientPid, API_1, /*shimUpdateOnly*/ false, /*out*/client);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001466
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001467 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001468 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001469 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001470 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001471 }
1472
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001473 *device = client;
1474 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001475}
1476
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001477Status CameraService::connectLegacy(
Zhijun Heb10cdad2014-06-16 16:38:35 -07001478 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001479 int api1CameraId, int halVersion,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001480 const String16& clientPackageName,
Zhijun Heb10cdad2014-06-16 16:38:35 -07001481 int clientUid,
1482 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001483 sp<ICamera>* device) {
Zhijun Heb10cdad2014-06-16 16:38:35 -07001484
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001485 ATRACE_CALL();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001486 String8 id = cameraIdIntToStr(api1CameraId);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001487
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001488 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001489 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001490 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId, halVersion,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001491 clientPackageName, std::unique_ptr<String16>(), clientUid, USE_CALLING_PID, API_1,
1492 /*shimUpdateOnly*/ false, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001493
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001494 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001495 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001496 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001497 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001498 }
1499
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001500 *device = client;
1501 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001502}
1503
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001504bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
1505 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001506 // If the client is not a vendor client, don't add listener if
1507 // a) the camera is a publicly hidden secure camera OR
1508 // b) the camera is a system only camera and the client doesn't
1509 // have android.permission.SYSTEM_CAMERA permissions.
1510 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
1511 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1512 !hasPermissionsForSystemCamera(clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001513 return true;
1514 }
1515 return false;
1516}
1517
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001518bool CameraService::shouldRejectSystemCameraConnection(const String8& cameraId) const {
1519 // Rules for rejection:
1520 // 1) If cameraserver tries to access this camera device, accept the
1521 // connection.
1522 // 2) The camera device is a publicly hidden secure camera device AND some
1523 // component is trying to access it on a non-hwbinder thread (generally a non HAL client),
1524 // reject it.
1525 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
1526 // and the serving thread is a non hwbinder thread, the client must have
1527 // android.permission.SYSTEM_CAMERA permissions to connect.
1528
1529 int cPid = CameraThreadState::getCallingPid();
1530 int cUid = CameraThreadState::getCallingUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001531 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
1532 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
1533 ALOGE("%s: Invalid camera id %s, ", __FUNCTION__, cameraId.c_str());
1534 return true;
1535 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001536
1537 // (1) Cameraserver trying to connect, accept.
1538 if (CameraThreadState::getCallingPid() == getpid()) {
1539 return false;
1540 }
1541 // (2)
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001542 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001543 systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
1544 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
1545 return true;
1546 }
1547 // (3) Here we only check for permissions if it is a system only camera device. This is since
1548 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
1549 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
1550 // same behavior for system camera devices.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001551 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001552 systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1553 !hasPermissionsForSystemCamera(cPid, cUid)) {
1554 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
1555 cameraId.c_str());
1556 return true;
1557 }
1558
1559 return false;
1560}
1561
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001562Status CameraService::connectDevice(
1563 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001564 const String16& cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001565 const String16& clientPackageName,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001566 const std::unique_ptr<String16>& clientFeatureId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001567 int clientUid,
1568 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001569 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001570
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001571 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001572 Status ret = Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001573 String8 id = String8(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001574 sp<CameraDeviceClient> client = nullptr;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001575 String16 clientPackageNameAdj = clientPackageName;
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001576
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001577 if (getCurrentServingCall() == BinderCallType::HWBINDER) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001578 std::string vendorClient =
1579 StringPrintf("vendor.client.pid<%d>", CameraThreadState::getCallingPid());
1580 clientPackageNameAdj = String16(vendorClient.c_str());
1581 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001582 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001583 /*api1CameraId*/-1,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001584 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageNameAdj, clientFeatureId,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001585 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08001586
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001587 if(!ret.isOk()) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001588 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageNameAdj),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001589 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001590 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001591 }
1592
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001593 *device = client;
1594 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001595}
1596
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001597template<class CALLBACK, class CLIENT>
1598Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001599 int api1CameraId, int halVersion, const String16& clientPackageName,
1600 const std::unique_ptr<String16>& clientFeatureId, int clientUid, int clientPid,
1601 apiLevel effectiveApiLevel, bool shimUpdateOnly,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001602 /*out*/sp<CLIENT>& device) {
1603 binder::Status ret = binder::Status::ok();
1604
1605 String8 clientName8(clientPackageName);
1606
1607 int originalClientPid = 0;
1608
1609 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) for HAL version %s and "
1610 "Camera API version %d", clientPid, clientName8.string(), cameraId.string(),
1611 (halVersion == -1) ? "default" : std::to_string(halVersion).c_str(),
1612 static_cast<int>(effectiveApiLevel));
1613
1614 sp<CLIENT> client = nullptr;
1615 {
1616 // Acquire mServiceLock and prevent other clients from connecting
1617 std::unique_ptr<AutoConditionLock> lock =
1618 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1619
1620 if (lock == nullptr) {
1621 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
1622 , clientPid);
1623 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1624 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
1625 cameraId.string(), clientName8.string(), clientPid);
1626 }
1627
1628 // Enforce client permissions and do basic sanity checks
1629 if(!(ret = validateConnectLocked(cameraId, clientName8,
1630 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
1631 return ret;
1632 }
1633
1634 // Check the shim parameters after acquiring lock, if they have already been updated and
1635 // we were doing a shim update, return immediately
1636 if (shimUpdateOnly) {
1637 auto cameraState = getCameraState(cameraId);
1638 if (cameraState != nullptr) {
1639 if (!cameraState->getShimParams().isEmpty()) return ret;
1640 }
1641 }
1642
1643 status_t err;
1644
1645 sp<BasicClient> clientTmp = nullptr;
1646 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
1647 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
1648 IInterface::asBinder(cameraCb), clientName8, /*out*/&clientTmp,
1649 /*out*/&partial)) != NO_ERROR) {
1650 switch (err) {
1651 case -ENODEV:
1652 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1653 "No camera device with ID \"%s\" currently available",
1654 cameraId.string());
1655 case -EBUSY:
1656 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1657 "Higher-priority client using camera, ID \"%s\" currently unavailable",
1658 cameraId.string());
1659 default:
1660 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1661 "Unexpected error %s (%d) opening camera \"%s\"",
1662 strerror(-err), err, cameraId.string());
1663 }
1664 }
1665
1666 if (clientTmp.get() != nullptr) {
1667 // Handle special case for API1 MediaRecorder where the existing client is returned
1668 device = static_cast<CLIENT*>(clientTmp.get());
1669 return ret;
1670 }
1671
1672 // give flashlight a chance to close devices if necessary.
1673 mFlashlight->prepareDeviceOpen(cameraId);
1674
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001675 int facing = -1;
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001676 int deviceVersion = getDeviceVersion(cameraId, /*out*/&facing);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08001677 if (facing == -1) {
1678 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.string());
1679 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1680 "Unable to get camera device \"%s\" facing", cameraId.string());
1681 }
1682
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001683 sp<BasicClient> tmp = nullptr;
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001684 if(!(ret = makeClient(this, cameraCb, clientPackageName, clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001685 cameraId, api1CameraId, facing,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001686 clientPid, clientUid, getpid(),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001687 halVersion, deviceVersion, effectiveApiLevel,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001688 /*out*/&tmp)).isOk()) {
1689 return ret;
1690 }
1691 client = static_cast<CLIENT*>(tmp.get());
1692
1693 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
1694 __FUNCTION__);
1695
Emilian Peevbd8c5032018-02-14 23:05:40 +00001696 err = client->initialize(mCameraProviderManager, mMonitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001697 if (err != OK) {
1698 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001699 // Errors could be from the HAL module open call or from AppOpsManager
1700 switch(err) {
1701 case BAD_VALUE:
1702 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1703 "Illegal argument to HAL module for camera \"%s\"", cameraId.string());
1704 case -EBUSY:
1705 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1706 "Camera \"%s\" is already open", cameraId.string());
1707 case -EUSERS:
1708 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1709 "Too many cameras already open, cannot open camera \"%s\"",
1710 cameraId.string());
1711 case PERMISSION_DENIED:
1712 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1713 "No permission to open camera \"%s\"", cameraId.string());
1714 case -EACCES:
1715 return STATUS_ERROR_FMT(ERROR_DISABLED,
1716 "Camera \"%s\" disabled by policy", cameraId.string());
1717 case -ENODEV:
1718 default:
1719 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1720 "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
1721 strerror(-err), err);
1722 }
1723 }
1724
1725 // Update shim paremeters for legacy clients
1726 if (effectiveApiLevel == API_1) {
1727 // Assume we have always received a Client subclass for API1
1728 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
1729 String8 rawParams = shimClient->getParameters();
1730 CameraParameters params(rawParams);
1731
1732 auto cameraState = getCameraState(cameraId);
1733 if (cameraState != nullptr) {
1734 cameraState->setShimParams(params);
1735 } else {
1736 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
1737 __FUNCTION__, cameraId.string());
1738 }
1739 }
1740
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001741 // Set rotate-and-crop override behavior
1742 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
1743 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
1744 }
1745
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001746 if (shimUpdateOnly) {
1747 // If only updating legacy shim parameters, immediately disconnect client
1748 mServiceLock.unlock();
1749 client->disconnect();
1750 mServiceLock.lock();
1751 } else {
1752 // Otherwise, add client to active clients list
1753 finishConnectLocked(client, partial);
1754 }
1755 } // lock is destroyed, allow further connect calls
1756
1757 // Important: release the mutex here so the client can call back into the service from its
1758 // destructor (can be at the end of the call)
1759 device = client;
1760 return ret;
1761}
1762
Emilian Peevb2bc5a42019-11-20 16:02:14 -08001763status_t CameraService::addOfflineClient(String8 cameraId, sp<BasicClient> offlineClient) {
1764 if (offlineClient.get() == nullptr) {
1765 return BAD_VALUE;
1766 }
1767
1768 {
1769 // Acquire mServiceLock and prevent other clients from connecting
1770 std::unique_ptr<AutoConditionLock> lock =
1771 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1772
1773 if (lock == nullptr) {
1774 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
1775 , __FUNCTION__, offlineClient->getClientPid());
1776 return TIMED_OUT;
1777 }
1778
1779 auto onlineClientDesc = mActiveClientManager.get(cameraId);
1780 if (onlineClientDesc.get() == nullptr) {
1781 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
1782 cameraId.c_str());
1783 return BAD_VALUE;
1784 }
1785
1786 // Offline clients do not evict or conflict with other online devices. Resource sharing
1787 // conflicts are handled by the camera provider which will either succeed or fail before
1788 // reaching this method.
1789 const auto& onlinePriority = onlineClientDesc->getPriority();
1790 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
1791 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
1792 /*conflictingKeys*/ std::set<String8>(), onlinePriority.getScore(),
1793 onlineClientDesc->getOwnerId(), onlinePriority.getState());
1794
1795 // Allow only one offline device per camera
1796 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
1797 if (!incompatibleClients.empty()) {
1798 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
1799 return BAD_VALUE;
1800 }
1801
1802 auto err = offlineClient->initialize(mCameraProviderManager, mMonitorTags);
1803 if (err != OK) {
1804 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
1805 return err;
1806 }
1807
1808 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
1809 if (evicted.size() > 0) {
1810 for (auto& i : evicted) {
1811 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
1812 __FUNCTION__, i->getKey().string());
1813 }
1814
1815 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
1816 "properly", __FUNCTION__);
1817
1818 return BAD_VALUE;
1819 }
1820
1821 logConnectedOffline(offlineClientDesc->getKey(),
1822 static_cast<int>(offlineClientDesc->getOwnerId()),
1823 String8(offlineClient->getPackageName()));
1824
1825 sp<IBinder> remoteCallback = offlineClient->getRemote();
1826 if (remoteCallback != nullptr) {
1827 remoteCallback->linkToDeath(this);
1828 }
1829 } // lock is destroyed, allow further connect calls
1830
1831 return OK;
1832}
1833
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001834Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001835 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001836 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001837
1838 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07001839 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001840 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001841 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1842 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001843 }
1844
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001845 String8 id = String8(cameraId.string());
Jayant Chowdhary12361932018-08-27 14:46:13 -07001846 int uid = CameraThreadState::getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001847
1848 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08001849 auto state = getCameraState(id);
1850 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001851 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001852 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1853 "Camera ID \"%s\" is a not valid camera ID", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001854 }
1855
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001856 StatusInternal cameraStatus = state->getStatus();
1857 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001858 cameraStatus != StatusInternal::NOT_AVAILABLE) {
1859 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001860 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1861 "Camera ID \"%s\" is a not valid camera ID", id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001862 }
1863
1864 {
1865 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001866 TorchModeStatus status;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001867 status_t err = getTorchStatusLocked(id, &status);
1868 if (err != OK) {
1869 if (err == NAME_NOT_FOUND) {
1870 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1871 "Camera \"%s\" does not have a flash unit", id.string());
1872 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001873 ALOGE("%s: getting current torch status failed for camera %s",
1874 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001875 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1876 "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
1877 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001878 }
1879
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001880 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001881 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001882 ALOGE("%s: torch mode of camera %s is not available because "
1883 "camera is in use", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001884 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1885 "Torch for camera \"%s\" is not available due to an existing camera user",
1886 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001887 } else {
1888 ALOGE("%s: torch mode of camera %s is not available due to "
1889 "insufficient resources", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001890 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1891 "Torch for camera \"%s\" is not available due to insufficient resources",
1892 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001893 }
1894 }
1895 }
1896
Ruben Brunk99e69712015-05-26 17:25:07 -07001897 {
1898 // Update UID map - this is used in the torch status changed callbacks, so must be done
1899 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07001900 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -07001901 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
1902 mTorchUidMap[id].first = uid;
1903 mTorchUidMap[id].second = uid;
1904 } else {
1905 // Set the pending UID
1906 mTorchUidMap[id].first = uid;
1907 }
1908 }
1909
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001910 status_t err = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07001911
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001912 if (err != OK) {
1913 int32_t errorCode;
1914 String8 msg;
1915 switch (err) {
1916 case -ENOSYS:
1917 msg = String8::format("Camera \"%s\" has no flashlight",
1918 id.string());
1919 errorCode = ERROR_ILLEGAL_ARGUMENT;
1920 break;
1921 default:
1922 msg = String8::format(
1923 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
1924 id.string(), enabled, strerror(-err), err);
1925 errorCode = ERROR_INVALID_OPERATION;
1926 }
1927 ALOGE("%s: %s", __FUNCTION__, msg.string());
1928 return STATUS_ERROR(errorCode, msg.string());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001929 }
1930
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001931 {
1932 // update the link to client's death
1933 Mutex::Autolock al(mTorchClientMapMutex);
1934 ssize_t index = mTorchClientMap.indexOfKey(id);
1935 if (enabled) {
1936 if (index == NAME_NOT_FOUND) {
1937 mTorchClientMap.add(id, clientBinder);
1938 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07001939 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001940 mTorchClientMap.replaceValueAt(index, clientBinder);
1941 }
1942 clientBinder->linkToDeath(this);
1943 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07001944 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001945 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001946 }
1947
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07001948 int clientPid = CameraThreadState::getCallingPid();
1949 const char *id_cstr = id.c_str();
1950 const char *torchState = enabled ? "on" : "off";
1951 ALOGI("Torch for camera id %s turned %s for client PID %d", id_cstr, torchState, clientPid);
1952 logTorchEvent(id_cstr, torchState , clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001953 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001954}
1955
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001956Status CameraService::notifySystemEvent(int32_t eventId,
1957 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001958 const int pid = CameraThreadState::getCallingPid();
1959 const int selfPid = getpid();
1960
1961 // Permission checks
1962 if (pid != selfPid) {
1963 // Ensure we're being called by system_server, or similar process with
1964 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001965 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001966 const int uid = CameraThreadState::getCallingUid();
1967 ALOGE("Permission Denial: cannot send updates to camera service about system"
1968 " events from pid=%d, uid=%d", pid, uid);
1969 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09001970 "No permission to send updates to camera service about system events"
1971 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001972 }
1973 }
1974
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001975 ATRACE_CALL();
1976
Ruben Brunk36597b22015-03-20 22:15:57 -07001977 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001978 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001979 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07001980 // from a system server crash
1981 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08001982 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001983 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07001984 break;
1985 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001986 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07001987 default: {
1988 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
1989 eventId);
1990 break;
1991 }
1992 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001993 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07001994}
1995
Emilian Peev53722fa2019-02-22 17:47:20 -08001996void CameraService::notifyMonitoredUids() {
1997 Mutex::Autolock lock(mStatusListenerLock);
1998
1999 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002000 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Emilian Peev53722fa2019-02-22 17:47:20 -08002001 if (!ret.isOk()) {
2002 ALOGE("%s: Failed to trigger permission callback: %d", __FUNCTION__,
2003 ret.exceptionCode());
2004 }
2005 }
2006}
2007
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002008Status CameraService::notifyDeviceStateChange(int64_t newState) {
2009 const int pid = CameraThreadState::getCallingPid();
2010 const int selfPid = getpid();
2011
2012 // Permission checks
2013 if (pid != selfPid) {
2014 // Ensure we're being called by system_server, or similar process with
2015 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002016 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002017 const int uid = CameraThreadState::getCallingUid();
2018 ALOGE("Permission Denial: cannot send updates to camera service about device"
2019 " state changes from pid=%d, uid=%d", pid, uid);
2020 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2021 "No permission to send updates to camera service about device state"
2022 " changes from pid=%d, uid=%d", pid, uid);
2023 }
2024 }
2025
2026 ATRACE_CALL();
2027
2028 using hardware::camera::provider::V2_5::DeviceState;
2029 hardware::hidl_bitfield<DeviceState> newDeviceState{};
2030 if (newState & ICameraService::DEVICE_STATE_BACK_COVERED) {
2031 newDeviceState |= DeviceState::BACK_COVERED;
2032 }
2033 if (newState & ICameraService::DEVICE_STATE_FRONT_COVERED) {
2034 newDeviceState |= DeviceState::FRONT_COVERED;
2035 }
2036 if (newState & ICameraService::DEVICE_STATE_FOLDED) {
2037 newDeviceState |= DeviceState::FOLDED;
2038 }
2039 // Only map vendor bits directly
2040 uint64_t vendorBits = static_cast<uint64_t>(newState) & 0xFFFFFFFF00000000l;
2041 newDeviceState |= vendorBits;
2042
2043 ALOGV("%s: New device state 0x%" PRIx64, __FUNCTION__, newDeviceState);
2044 Mutex::Autolock l(mServiceLock);
2045 mCameraProviderManager->notifyDeviceStateChange(newDeviceState);
2046
2047 return Status::ok();
2048}
2049
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002050 Status CameraService::getConcurrentStreamingCameraIds(
2051 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
2052 ATRACE_CALL();
2053 if (!concurrentCameraIds) {
2054 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
2055 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
2056 }
2057
2058 if (!mInitialized) {
2059 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2060 return STATUS_ERROR(ERROR_DISCONNECTED,
2061 "Camera subsystem is not available");
2062 }
2063 // First call into the provider and get the set of concurrent camera
2064 // combinations
2065 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
2066 mCameraProviderManager->getConcurrentStreamingCameraIds();
2067 for (auto &combination : concurrentCameraCombinations) {
2068 std::vector<std::string> validCombination;
2069 for (auto &cameraId : combination) {
2070 // if the camera state is not present, skip
2071 String8 cameraIdStr(cameraId.c_str());
2072 auto state = getCameraState(cameraIdStr);
2073 if (state == nullptr) {
2074 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
2075 continue;
2076 }
2077 StatusInternal status = state->getStatus();
2078 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
2079 continue;
2080 }
2081 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
2082 continue;
2083 }
2084 validCombination.push_back(cameraId);
2085 }
2086 if (validCombination.size() != 0) {
2087 concurrentCameraIds->push_back(std::move(validCombination));
2088 }
2089 }
2090 return Status::ok();
2091}
2092
2093Status CameraService::isConcurrentSessionConfigurationSupported(
2094 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
2095 /*out*/bool* isSupported) {
2096 if (!isSupported) {
2097 ALOGE("%s: isSupported is NULL", __FUNCTION__);
2098 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
2099 }
2100
2101 if (!mInitialized) {
2102 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2103 return STATUS_ERROR(ERROR_DISCONNECTED,
2104 "Camera subsystem is not available");
2105 }
2106
2107 // Check for camera permissions
2108 int callingPid = CameraThreadState::getCallingPid();
2109 int callingUid = CameraThreadState::getCallingUid();
2110 if ((callingPid != getpid()) && !checkPermission(sCameraPermission, callingPid, callingUid)) {
2111 ALOGE("%s: pid %d doesn't have camera permissions", __FUNCTION__, callingPid);
2112 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2113 "android.permission.CAMERA needed to call"
2114 "isConcurrentSessionConfigurationSupported");
2115 }
2116
2117 status_t res =
2118 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
2119 cameraIdsAndSessionConfigurations, isSupported);
2120 if (res != OK) {
2121 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
2122 "support %s (%d)", strerror(-res), res);
2123 }
2124 return Status::ok();
2125}
2126
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002127Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
2128 /*out*/
2129 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002130 return addListenerHelper(listener, cameraStatuses);
2131}
2132
2133Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
2134 /*out*/
2135 std::vector<hardware::CameraStatus> *cameraStatuses,
2136 bool isVendorListener) {
2137
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002138 ATRACE_CALL();
2139
Igor Murashkinbfc99152013-02-27 12:55:20 -08002140 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08002141
Ruben Brunk3450ba72015-06-16 11:00:37 -07002142 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002143 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002144 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002145 }
2146
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002147 auto clientUid = CameraThreadState::getCallingUid();
2148 auto clientPid = CameraThreadState::getCallingPid();
2149
Igor Murashkinbfc99152013-02-27 12:55:20 -08002150 Mutex::Autolock lock(mServiceLock);
2151
Ruben Brunkcc776712015-02-17 20:18:47 -08002152 {
2153 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08002154 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002155 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002156 ALOGW("%s: Tried to add listener %p which was already subscribed",
2157 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002158 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08002159 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002160 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002161
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002162 sp<ServiceListener> serviceListener =
2163 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08002164 auto ret = serviceListener->initialize();
2165 if (ret != NO_ERROR) {
2166 String8 msg = String8::format("Failed to initialize service listener: %s (%d)",
2167 strerror(-ret), ret);
2168 ALOGE("%s: %s", __FUNCTION__, msg.string());
2169 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
2170 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002171 // The listener still needs to be added to the list of listeners, regardless of what
2172 // permissions the listener process has / whether it is a vendor listener. Since it might be
2173 // eligible to listen to other camera ids.
2174 mListenerList.emplace_back(serviceListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08002175 mUidPolicy->registerMonitorUid(clientUid);
Igor Murashkinbfc99152013-02-27 12:55:20 -08002176 }
2177
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002178 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07002179 {
Ruben Brunkcc776712015-02-17 20:18:47 -08002180 Mutex::Autolock lock(mCameraStatesLock);
2181 for (auto& i : mCameraStates) {
Shuzhen Wang43858162020-01-10 13:42:15 -08002182 cameraStatuses->emplace_back(i.first,
2183 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds());
Igor Murashkincba2c162013-03-20 15:56:31 -07002184 }
2185 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002186 // Remove the camera statuses that should be hidden from the client, we do
2187 // this after collecting the states in order to avoid holding
2188 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
2189 // the same time.
2190 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
2191 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
2192 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
2193 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
2194 ALOGE("%s: Invalid camera id %s, skipping status update",
2195 __FUNCTION__, s.cameraId.c_str());
2196 return true;
2197 }
2198 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
2199 clientUid);}), cameraStatuses->end());
2200
Igor Murashkincba2c162013-03-20 15:56:31 -07002201
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002202 /*
2203 * Immediately signal current torch status to this listener only
2204 * This may be a subset of all the devices, so don't include it in the response directly
2205 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002206 {
2207 Mutex::Autolock al(mTorchStatusMutex);
2208 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002209 String16 id = String16(mTorchStatusMap.keyAt(i).string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002210 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002211 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002212 }
2213
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002214 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08002215}
Ruben Brunkcc776712015-02-17 20:18:47 -08002216
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002217Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002218 ATRACE_CALL();
2219
Igor Murashkinbfc99152013-02-27 12:55:20 -08002220 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
2221
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002222 if (listener == 0) {
2223 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002224 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002225 }
2226
Igor Murashkinbfc99152013-02-27 12:55:20 -08002227 Mutex::Autolock lock(mServiceLock);
2228
Ruben Brunkcc776712015-02-17 20:18:47 -08002229 {
2230 Mutex::Autolock lock(mStatusListenerLock);
2231 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002232 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
2233 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid());
2234 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08002235 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002236 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002237 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002238 }
2239 }
2240
2241 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
2242 __FUNCTION__, listener.get());
2243
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002244 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08002245}
2246
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002247Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002248
2249 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002250 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
2251
2252 if (parameters == NULL) {
2253 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002254 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07002255 }
2256
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002257 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002258
2259 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002260 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07002261 // Error logged by caller
2262 return ret;
2263 }
2264
2265 String8 shimParamsString8 = shimParams.flatten();
2266 String16 shimParamsString16 = String16(shimParamsString8);
2267
2268 *parameters = shimParamsString16;
2269
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002270 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07002271}
2272
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002273Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
2274 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002275 ATRACE_CALL();
2276
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002277 const String8 id = String8(cameraId);
2278
2279 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002280
2281 switch (apiVersion) {
2282 case API_VERSION_1:
2283 case API_VERSION_2:
2284 break;
2285 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002286 String8 msg = String8::format("Unknown API version %d", apiVersion);
2287 ALOGE("%s: %s", __FUNCTION__, msg.string());
2288 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002289 }
2290
Emilian Peev28ad2ea2017-02-07 16:14:32 +00002291 int deviceVersion = getDeviceVersion(id);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002292 switch (deviceVersion) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002293 case CAMERA_DEVICE_API_VERSION_1_0:
2294 case CAMERA_DEVICE_API_VERSION_3_0:
2295 case CAMERA_DEVICE_API_VERSION_3_1:
2296 if (apiVersion == API_VERSION_2) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002297 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without shim",
2298 __FUNCTION__, id.string(), deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002299 *isSupported = false;
2300 } else { // if (apiVersion == API_VERSION_1) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002301 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always supported",
2302 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002303 *isSupported = true;
2304 }
2305 break;
2306 case CAMERA_DEVICE_API_VERSION_3_2:
2307 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -07002308 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002309 case CAMERA_DEVICE_API_VERSION_3_5:
Yin-Chia Yeh56d98ba2020-01-16 16:57:14 -08002310 case CAMERA_DEVICE_API_VERSION_3_6:
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002311 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
2312 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002313 *isSupported = true;
2314 break;
2315 case -1: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002316 String8 msg = String8::format("Unknown camera ID %s", id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002317 ALOGE("%s: %s", __FUNCTION__, msg.string());
2318 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002319 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002320 default: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002321 String8 msg = String8::format("Unknown device version %x for device %s",
2322 deviceVersion, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002323 ALOGE("%s: %s", __FUNCTION__, msg.string());
2324 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
2325 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07002326 }
2327
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002328 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002329}
2330
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002331Status CameraService::isHiddenPhysicalCamera(const String16& cameraId,
2332 /*out*/ bool *isSupported) {
2333 ATRACE_CALL();
2334
2335 const String8 id = String8(cameraId);
2336
2337 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
2338 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(id.string());
2339
2340 return Status::ok();
2341}
2342
Ruben Brunkcc776712015-02-17 20:18:47 -08002343void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002344 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002345 for (auto& i : mActiveClientManager.getAll()) {
2346 auto clientSp = i->getValue();
2347 if (clientSp.get() == client) {
2348 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08002349 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07002350 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002351 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08002352}
2353
Ruben Brunkcc776712015-02-17 20:18:47 -08002354bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002355 bool ret = false;
2356 {
2357 // Acquire mServiceLock and prevent other clients from connecting
2358 std::unique_ptr<AutoConditionLock> lock =
2359 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08002360
Igor Murashkin634a5152013-02-20 17:15:11 -08002361
Ruben Brunkcc776712015-02-17 20:18:47 -08002362 std::vector<sp<BasicClient>> evicted;
2363 for (auto& i : mActiveClientManager.getAll()) {
2364 auto clientSp = i->getValue();
2365 if (clientSp.get() == nullptr) {
2366 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2367 mActiveClientManager.remove(i);
2368 continue;
2369 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08002370 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002371 mActiveClientManager.remove(i);
2372 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08002373
Ruben Brunkcc776712015-02-17 20:18:47 -08002374 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002375 clientSp->notifyError(
2376 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002377 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08002378 }
2379 }
2380
Ruben Brunkcc776712015-02-17 20:18:47 -08002381 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2382 // other clients from connecting in mServiceLockWrapper if held
2383 mServiceLock.unlock();
2384
Ruben Brunk36597b22015-03-20 22:15:57 -07002385 // Do not clear caller identity, remote caller should be client proccess
2386
Ruben Brunkcc776712015-02-17 20:18:47 -08002387 for (auto& i : evicted) {
2388 if (i.get() != nullptr) {
2389 i->disconnect();
2390 ret = true;
2391 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002392 }
2393
Ruben Brunkcc776712015-02-17 20:18:47 -08002394 // Reacquire mServiceLock
2395 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08002396
Ruben Brunkcc776712015-02-17 20:18:47 -08002397 } // lock is destroyed, allow further connect calls
2398
2399 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07002400}
2401
Ruben Brunkcc776712015-02-17 20:18:47 -08002402std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
2403 const String8& cameraId) const {
2404 std::shared_ptr<CameraState> state;
2405 {
2406 Mutex::Autolock lock(mCameraStatesLock);
2407 auto iter = mCameraStates.find(cameraId);
2408 if (iter != mCameraStates.end()) {
2409 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002410 }
2411 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002412 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002413}
2414
Ruben Brunkcc776712015-02-17 20:18:47 -08002415sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
2416 // Remove from active clients list
2417 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
2418 if (clientDescriptorPtr == nullptr) {
2419 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
2420 cameraId.string());
2421 return sp<BasicClient>{nullptr};
2422 }
2423
2424 return clientDescriptorPtr->getValue();
Keun young Parkd8973a72012-03-28 14:13:09 -07002425}
2426
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002427void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07002428 // Acquire mServiceLock and prevent other clients from connecting
2429 std::unique_ptr<AutoConditionLock> lock =
2430 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
2431
Ruben Brunk6267b532015-04-30 17:44:07 -07002432 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002433 for (size_t i = 0; i < newUserIds.size(); i++) {
2434 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07002435 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002436 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07002437 return;
2438 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002439 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07002440 }
2441
Ruben Brunka8ca9152015-04-07 14:23:40 -07002442
Ruben Brunk6267b532015-04-30 17:44:07 -07002443 if (newAllowedUsers == mAllowedUsers) {
2444 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
2445 return;
2446 }
2447
2448 logUserSwitch(mAllowedUsers, newAllowedUsers);
2449
2450 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07002451
2452 // Current user has switched, evict all current clients.
2453 std::vector<sp<BasicClient>> evicted;
2454 for (auto& i : mActiveClientManager.getAll()) {
2455 auto clientSp = i->getValue();
2456
2457 if (clientSp.get() == nullptr) {
2458 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2459 continue;
2460 }
2461
Ruben Brunk6267b532015-04-30 17:44:07 -07002462 // Don't evict clients that are still allowed.
2463 uid_t clientUid = clientSp->getClientUid();
2464 userid_t clientUserId = multiuser_get_user_id(clientUid);
2465 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
2466 continue;
2467 }
2468
Ruben Brunk36597b22015-03-20 22:15:57 -07002469 evicted.push_back(clientSp);
2470
2471 String8 curTime = getFormattedCurrentTime();
2472
2473 ALOGE("Evicting conflicting client for camera ID %s due to user change",
2474 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07002475
Ruben Brunk36597b22015-03-20 22:15:57 -07002476 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002477 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00002478 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
2479 " to user switch.", i->getKey().string(),
2480 String8{clientSp->getPackageName()}.string(),
2481 i->getOwnerId(), i->getPriority().getScore(),
2482 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07002483
2484 }
2485
2486 // Do not hold mServiceLock while disconnecting clients, but retain the condition
2487 // blocking other clients from connecting in mServiceLockWrapper if held.
2488 mServiceLock.unlock();
2489
2490 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07002491 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07002492
2493 for (auto& i : evicted) {
2494 i->disconnect();
2495 }
2496
Jayant Chowdhary12361932018-08-27 14:46:13 -07002497 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07002498
2499 // Reacquire mServiceLock
2500 mServiceLock.lock();
2501}
Ruben Brunkcc776712015-02-17 20:18:47 -08002502
Ruben Brunka8ca9152015-04-07 14:23:40 -07002503void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002504 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07002505 Mutex::Autolock l(mLogLock);
2506 mEventLog.add(String8::format("%s : %s", curTime.string(), event));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002507}
2508
Ruben Brunka8ca9152015-04-07 14:23:40 -07002509void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002510 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002511 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002512 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002513 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002514}
2515
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002516void CameraService::logDisconnectedOffline(const char* cameraId, int clientPid,
2517 const char* clientPackage) {
2518 // Log the clients evicted
2519 logEvent(String8::format("DISCONNECT offline device %s client for package %s (PID %d)",
2520 cameraId, clientPackage, clientPid));
2521}
2522
Ruben Brunka8ca9152015-04-07 14:23:40 -07002523void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002524 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002525 // Log the clients evicted
2526 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002527 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002528}
2529
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002530void CameraService::logConnectedOffline(const char* cameraId, int clientPid,
2531 const char* clientPackage) {
2532 // Log the clients evicted
2533 logEvent(String8::format("CONNECT offline device %s client for package %s (PID %d)", cameraId,
2534 clientPackage, clientPid));
2535}
2536
Ruben Brunka8ca9152015-04-07 14:23:40 -07002537void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002538 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002539 // Log the client rejected
2540 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002541 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002542}
2543
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002544void CameraService::logTorchEvent(const char* cameraId, const char *torchState, int clientPid) {
2545 // Log torch event
2546 logEvent(String8::format("Torch for camera id %s turned %s for client PID %d", cameraId,
2547 torchState, clientPid));
2548}
2549
Ruben Brunk6267b532015-04-30 17:44:07 -07002550void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
2551 const std::set<userid_t>& newUserIds) {
2552 String8 newUsers = toString(newUserIds);
2553 String8 oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002554 if (oldUsers.size() == 0) {
2555 oldUsers = "<None>";
2556 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07002557 // Log the new and old users
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002558 logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
Ruben Brunk6267b532015-04-30 17:44:07 -07002559 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002560}
2561
2562void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
2563 // Log the device removal
2564 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
2565}
2566
2567void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
2568 // Log the device removal
2569 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
2570}
2571
2572void CameraService::logClientDied(int clientPid, const char* reason) {
2573 // Log the device removal
2574 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07002575}
2576
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002577void CameraService::logServiceError(const char* msg, int errorCode) {
2578 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002579 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002580}
2581
Ruben Brunk36597b22015-03-20 22:15:57 -07002582status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
2583 uint32_t flags) {
2584
Mathias Agopian65ab4712010-07-14 17:59:35 -07002585 // Permission checks
2586 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002587 case SHELL_COMMAND_TRANSACTION: {
2588 int in = data.readFileDescriptor();
2589 int out = data.readFileDescriptor();
2590 int err = data.readFileDescriptor();
2591 int argc = data.readInt32();
2592 Vector<String16> args;
2593 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
2594 args.add(data.readString16());
2595 }
2596 sp<IBinder> unusedCallback;
2597 sp<IResultReceiver> resultReceiver;
2598 status_t status;
2599 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
2600 return status;
2601 }
2602 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
2603 return status;
2604 }
2605 status = shellCommand(in, out, err, args);
2606 if (resultReceiver != nullptr) {
2607 resultReceiver->send(status);
2608 }
2609 return NO_ERROR;
2610 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002611 }
2612
2613 return BnCameraService::onTransact(code, data, reply, flags);
2614}
2615
Mathias Agopian65ab4712010-07-14 17:59:35 -07002616// We share the media players for shutter and recording sound for all clients.
2617// A reference count is kept to determine when we will actually release the
2618// media players.
2619
Jaekyun Seokef498052018-03-23 13:09:44 +09002620sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
2621 sp<MediaPlayer> mp = new MediaPlayer();
2622 status_t error;
2623 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08002624 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09002625 error = mp->prepare();
2626 }
2627 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00002628 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09002629 mp->disconnect();
2630 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002631 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002632 }
2633 return mp;
2634}
2635
username5755fea2018-12-27 09:48:08 +08002636void CameraService::increaseSoundRef() {
2637 Mutex::Autolock lock(mSoundLock);
2638 mSoundRef++;
2639}
2640
2641void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002642 ATRACE_CALL();
2643
username5755fea2018-12-27 09:48:08 +08002644 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
2645 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
2646 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
2647 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
2648 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
2649 }
2650 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
2651 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
2652 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
2653 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002654 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08002655 }
2656 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
2657 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
2658 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
2659 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
2660 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002661 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002662}
2663
username5755fea2018-12-27 09:48:08 +08002664void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002665 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002666 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002667 if (--mSoundRef) return;
2668
2669 for (int i = 0; i < NUM_SOUNDS; i++) {
2670 if (mSoundPlayer[i] != 0) {
2671 mSoundPlayer[i]->disconnect();
2672 mSoundPlayer[i].clear();
2673 }
2674 }
2675}
2676
2677void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002678 ATRACE_CALL();
2679
Mathias Agopian65ab4712010-07-14 17:59:35 -07002680 LOG1("playSound(%d)", kind);
2681 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002682 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002683 sp<MediaPlayer> player = mSoundPlayer[kind];
2684 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08002685 player->seekTo(0);
2686 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002687 }
2688}
2689
2690// ----------------------------------------------------------------------------
2691
2692CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07002693 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002694 const String16& clientPackageName,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002695 const std::unique_ptr<String16>& clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002696 const String8& cameraIdStr,
2697 int api1CameraId, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002698 int clientPid, uid_t clientUid,
2699 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002700 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08002701 IInterface::asBinder(cameraClient),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002702 clientPackageName, clientFeatureId,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002703 cameraIdStr, cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002704 clientPid, clientUid,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002705 servicePid),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002706 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08002707{
Jayant Chowdhary12361932018-08-27 14:46:13 -07002708 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002709 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002710
Igor Murashkin44cfcf02013-03-01 16:22:28 -08002711 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002712
username5755fea2018-12-27 09:48:08 +08002713 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002714
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002715 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002716}
2717
Mathias Agopian65ab4712010-07-14 17:59:35 -07002718// tear down the client
2719CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002720 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08002721 mDestructionStarted = true;
2722
username5755fea2018-12-27 09:48:08 +08002723 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002724 // unconditionally disconnect. function is idempotent
2725 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002726}
2727
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002728sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
2729
Igor Murashkin634a5152013-02-20 17:15:11 -08002730CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002731 const sp<IBinder>& remoteCallback,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002732 const String16& clientPackageName, const std::unique_ptr<String16>& clientFeatureId,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002733 const String8& cameraIdStr, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002734 int clientPid, uid_t clientUid,
2735 int servicePid):
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002736 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002737 mClientPackageName(clientPackageName),
2738 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002739 mServicePid(servicePid),
2740 mDisconnected(false),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002741 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002742 mRemoteBinder(remoteCallback)
Igor Murashkin634a5152013-02-20 17:15:11 -08002743{
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002744 if (clientFeatureId) {
2745 mClientFeatureId = std::unique_ptr<String16>(new String16(*clientFeatureId));
2746 } else {
2747 mClientFeatureId = std::unique_ptr<String16>();
2748 }
2749
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002750 if (sCameraService == nullptr) {
2751 sCameraService = cameraService;
2752 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002753 mOpsActive = false;
Igor Murashkin634a5152013-02-20 17:15:11 -08002754 mDestructionStarted = false;
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08002755
2756 // In some cases the calling code has no access to the package it runs under.
2757 // For example, NDK camera API.
2758 // In this case we will get the packages for the calling UID and pick the first one
2759 // for attributing the app op. This will work correctly for runtime permissions
2760 // as for legacy apps we will toggle the app op for all packages in the UID.
2761 // The caveat is that the operation may be attributed to the wrong package and
2762 // stats based on app ops may be slightly off.
2763 if (mClientPackageName.size() <= 0) {
2764 sp<IServiceManager> sm = defaultServiceManager();
2765 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
2766 if (binder == 0) {
2767 ALOGE("Cannot get permission service");
2768 // Leave mClientPackageName unchanged (empty) and the further interaction
2769 // with camera will fail in BasicClient::startCameraOps
2770 return;
2771 }
2772
2773 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
2774 Vector<String16> packages;
2775
2776 permCtrl->getPackagesForUid(mClientUid, packages);
2777
2778 if (packages.isEmpty()) {
2779 ALOGE("No packages for calling UID");
2780 // Leave mClientPackageName unchanged (empty) and the further interaction
2781 // with camera will fail in BasicClient::startCameraOps
2782 return;
2783 }
2784 mClientPackageName = packages[0];
2785 }
Steven Moreland89a2c5c2020-01-31 15:02:25 -08002786 if (getCurrentServingCall() != BinderCallType::HWBINDER) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002787 mAppOpsManager = std::make_unique<AppOpsManager>();
2788 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002789}
2790
2791CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002792 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08002793 mDestructionStarted = true;
2794}
2795
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002796binder::Status CameraService::BasicClient::disconnect() {
2797 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002798 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002799 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07002800 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07002801 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002802
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002803 sCameraService->removeByClient(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002804 sCameraService->logDisconnected(mCameraIdStr, mClientPid, String8(mClientPackageName));
Peter Kalauskasa29c1352018-10-10 12:05:42 -07002805 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
2806 mCameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002807
2808 sp<IBinder> remote = getRemote();
2809 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002810 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08002811 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002812
2813 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07002814 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002815 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
2816 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
2817 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002818
Igor Murashkincba2c162013-03-20 15:56:31 -07002819 // client shouldn't be able to call into us anymore
2820 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002821
2822 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08002823}
2824
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002825status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
2826 // No dumping of clients directly over Binder,
2827 // must go through CameraService::dump
2828 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07002829 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002830 return OK;
2831}
2832
Ruben Brunkcc776712015-02-17 20:18:47 -08002833String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002834 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08002835}
2836
2837
2838int CameraService::BasicClient::getClientPid() const {
2839 return mClientPid;
2840}
2841
Ruben Brunk6267b532015-04-30 17:44:07 -07002842uid_t CameraService::BasicClient::getClientUid() const {
2843 return mClientUid;
2844}
2845
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002846bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
2847 // Defaults to API2.
2848 return level == API_2;
2849}
2850
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002851status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002852 {
2853 Mutex::Autolock l(mAudioRestrictionLock);
2854 mAudioRestriction = mode;
2855 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002856 sCameraService->updateAudioRestriction();
2857 return OK;
2858}
2859
2860int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002861 return sCameraService->updateAudioRestriction();
2862}
2863
2864int32_t CameraService::BasicClient::getAudioRestriction() const {
2865 Mutex::Autolock l(mAudioRestrictionLock);
2866 return mAudioRestriction;
2867}
2868
2869bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
2870 switch (mode) {
2871 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
2872 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
2873 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
2874 return true;
2875 default:
2876 return false;
2877 }
2878}
2879
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002880status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002881 ATRACE_CALL();
2882
Igor Murashkine6800ce2013-03-04 17:25:57 -08002883 {
2884 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002885 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08002886 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002887 if (mAppOpsManager != nullptr) {
2888 // Notify app ops that the camera is not available
2889 mOpsCallback = new OpsCallback(this);
2890 int32_t res;
2891 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
2892 mClientPackageName, mOpsCallback);
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002893 res = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
2894 mClientPackageName, /*startIfModeDefault*/ false, mClientFeatureId,
2895 String16("start camera ") + String16(mCameraIdStr));
Igor Murashkine6800ce2013-03-04 17:25:57 -08002896
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002897 if (res == AppOpsManager::MODE_ERRORED) {
2898 ALOGI("Camera %s: Access for \"%s\" has been revoked",
2899 mCameraIdStr.string(), String8(mClientPackageName).string());
2900 return PERMISSION_DENIED;
2901 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002902
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002903 if (res == AppOpsManager::MODE_IGNORED) {
2904 ALOGI("Camera %s: Access for \"%s\" has been restricted",
2905 mCameraIdStr.string(), String8(mClientPackageName).string());
2906 // Return the same error as for device policy manager rejection
2907 return -EACCES;
2908 }
Svetoslav28e8ef72015-05-11 19:21:31 -07002909 }
2910
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002911 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002912
2913 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002914 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002915
Emilian Peev573291c2018-02-10 02:10:56 +00002916 int apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_1;
2917 if (canCastToApiClient(API_2)) {
2918 apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_2;
2919 }
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002920 // Transition device state to OPEN
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002921 sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_OPEN,
Emilian Peev573291c2018-02-10 02:10:56 +00002922 mCameraIdStr, mCameraFacing, mClientPackageName, apiLevel);
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002923
Emilian Peev53722fa2019-02-22 17:47:20 -08002924 sCameraService->mUidPolicy->registerMonitorUid(mClientUid);
2925
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002926 return OK;
2927}
2928
2929status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002930 ATRACE_CALL();
2931
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002932 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002933 if (mOpsActive) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002934 // Notify app ops that the camera is available again
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002935 if (mAppOpsManager != nullptr) {
2936 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002937 mClientPackageName, mClientFeatureId);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002938 mOpsActive = false;
2939 }
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002940 // This function is called when a client disconnects. This should
2941 // release the camera, but actually only if it was in a proper
2942 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002943 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002944 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002945
Ruben Brunkcc776712015-02-17 20:18:47 -08002946 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002947 sCameraService->updateStatus(StatusInternal::PRESENT,
2948 mCameraIdStr, rejected);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002949
Emilian Peev573291c2018-02-10 02:10:56 +00002950 int apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_1;
2951 if (canCastToApiClient(API_2)) {
2952 apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_2;
2953 }
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002954 // Transition device state to CLOSED
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002955 sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_CLOSED,
Emilian Peev573291c2018-02-10 02:10:56 +00002956 mCameraIdStr, mCameraFacing, mClientPackageName, apiLevel);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002957 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002958 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002959 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
2960 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002961 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002962 mOpsCallback.clear();
2963
Emilian Peev53722fa2019-02-22 17:47:20 -08002964 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid);
2965
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002966 return OK;
2967}
2968
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002969void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002970 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002971 if (mAppOpsManager == nullptr) {
2972 return;
2973 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002974 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002975 if (op != AppOpsManager::OP_CAMERA) {
2976 ALOGW("Unexpected app ops notification received: %d", op);
2977 return;
2978 }
2979
2980 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002981 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002982 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002983 ALOGV("checkOp returns: %d, %s ", res,
2984 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
2985 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
2986 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
2987 "UNKNOWN");
2988
2989 if (res != AppOpsManager::MODE_ALLOWED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002990 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002991 String8(mClientPackageName).string());
Svet Ganova453d0d2018-01-11 15:37:58 -08002992 block();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002993 }
2994}
2995
Svet Ganova453d0d2018-01-11 15:37:58 -08002996void CameraService::BasicClient::block() {
2997 ATRACE_CALL();
2998
2999 // Reset the client PID to allow server-initiated disconnect,
3000 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003001 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08003002 CaptureResultExtras resultExtras; // a dummy result (invalid)
3003 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
3004 disconnect();
3005}
3006
Mathias Agopian65ab4712010-07-14 17:59:35 -07003007// ----------------------------------------------------------------------------
3008
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003009void CameraService::Client::notifyError(int32_t errorCode,
Jianing Weicb0652e2014-03-12 18:29:36 -07003010 const CaptureResultExtras& resultExtras) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08003011 (void) resultExtras;
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003012 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07003013 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
3014 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
3015 api1ErrorCode = CAMERA_ERROR_DISABLED;
3016 }
3017 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003018 } else {
3019 ALOGE("mRemoteCallback is NULL!!");
3020 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003021}
3022
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003023// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003024binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003025 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003026 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08003027}
3028
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003029bool CameraService::Client::canCastToApiClient(apiLevel level) const {
3030 return level == API_1;
3031}
3032
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003033CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
3034 mClient(client) {
3035}
3036
3037void CameraService::Client::OpsCallback::opChanged(int32_t op,
3038 const String16& packageName) {
3039 sp<BasicClient> client = mClient.promote();
3040 if (client != NULL) {
3041 client->opChanged(op, packageName);
3042 }
3043}
3044
Mathias Agopian65ab4712010-07-14 17:59:35 -07003045// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08003046// UidPolicy
3047// ----------------------------------------------------------------------------
3048
3049void CameraService::UidPolicy::registerSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003050 Mutex::Autolock _l(mUidLock);
3051
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003052 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07003053 status_t res = mAm.linkToDeath(this);
3054 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08003055 | ActivityManager::UID_OBSERVER_IDLE
Emilian Peev53722fa2019-02-22 17:47:20 -08003056 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganova453d0d2018-01-11 15:37:58 -08003057 ActivityManager::PROCESS_STATE_UNKNOWN,
3058 String16("cameraserver"));
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003059 if (res == OK) {
3060 mRegistered = true;
3061 ALOGV("UidPolicy: Registered with ActivityManager");
3062 }
Svet Ganova453d0d2018-01-11 15:37:58 -08003063}
3064
3065void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003066 Mutex::Autolock _l(mUidLock);
3067
Steven Moreland2f348142019-07-02 15:59:07 -07003068 mAm.unregisterUidObserver(this);
3069 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003070 mRegistered = false;
3071 mActiveUids.clear();
3072 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08003073}
3074
3075void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
3076 onUidIdle(uid, disabled);
3077}
3078
3079void CameraService::UidPolicy::onUidActive(uid_t uid) {
3080 Mutex::Autolock _l(mUidLock);
3081 mActiveUids.insert(uid);
3082}
3083
3084void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
3085 bool deleted = false;
3086 {
3087 Mutex::Autolock _l(mUidLock);
3088 if (mActiveUids.erase(uid) > 0) {
3089 deleted = true;
3090 }
3091 }
3092 if (deleted) {
3093 sp<CameraService> service = mService.promote();
3094 if (service != nullptr) {
3095 service->blockClientsForUid(uid);
3096 }
3097 }
3098}
3099
Emilian Peev53722fa2019-02-22 17:47:20 -08003100void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07003101 int64_t procStateSeq __unused, int32_t capability __unused) {
Emilian Peev53722fa2019-02-22 17:47:20 -08003102 bool procStateChange = false;
3103 {
3104 Mutex::Autolock _l(mUidLock);
3105 if ((mMonitoredUids.find(uid) != mMonitoredUids.end()) &&
3106 (mMonitoredUids[uid].first != procState)) {
3107 mMonitoredUids[uid].first = procState;
3108 procStateChange = true;
3109 }
3110 }
3111
3112 if (procStateChange) {
3113 sp<CameraService> service = mService.promote();
3114 if (service != nullptr) {
3115 service->notifyMonitoredUids();
3116 }
3117 }
3118}
3119
3120void CameraService::UidPolicy::registerMonitorUid(uid_t uid) {
3121 Mutex::Autolock _l(mUidLock);
3122 auto it = mMonitoredUids.find(uid);
3123 if (it != mMonitoredUids.end()) {
3124 it->second.second++;
3125 } else {
3126 mMonitoredUids.emplace(
3127 std::pair<uid_t, std::pair<int32_t, size_t>> (uid,
3128 std::pair<int32_t, size_t> (ActivityManager::PROCESS_STATE_NONEXISTENT, 1)));
3129 }
3130}
3131
3132void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid) {
3133 Mutex::Autolock _l(mUidLock);
3134 auto it = mMonitoredUids.find(uid);
3135 if (it != mMonitoredUids.end()) {
3136 it->second.second--;
3137 if (it->second.second == 0) {
3138 mMonitoredUids.erase(it);
3139 }
3140 } else {
3141 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
3142 }
3143}
3144
Svet Ganov7b4ab782018-03-25 12:48:10 -07003145bool CameraService::UidPolicy::isUidActive(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003146 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003147 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003148}
3149
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003150static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
3151static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003152
Svet Ganov7b4ab782018-03-25 12:48:10 -07003153bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003154 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003155 // If activity manager is unreachable, assume everything is active
3156 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003157 return true;
3158 }
3159 auto it = mOverrideUids.find(uid);
3160 if (it != mOverrideUids.end()) {
3161 return it->second;
3162 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003163 bool active = mActiveUids.find(uid) != mActiveUids.end();
3164 if (!active) {
3165 // We want active UIDs to always access camera with their first attempt since
3166 // there is no guarantee the app is robustly written and would retry getting
3167 // the camera on failure. The inverse case is not a problem as we would take
3168 // camera away soon once we get the callback that the uid is no longer active.
3169 ActivityManager am;
3170 // Okay to access with a lock held as UID changes are dispatched without
3171 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07003172 int64_t startTimeMillis = 0;
3173 do {
3174 // TODO: Fix this b/109950150!
3175 // Okay this is a hack. There is a race between the UID turning active and
3176 // activity being resumed. The proper fix is very risky, so we temporary add
3177 // some polling which should happen pretty rarely anyway as the race is hard
3178 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003179 active = mActiveUids.find(uid) != mActiveUids.end();
3180 if (!active) active = am.isUidActive(uid, callingPackage);
Svet Ganov94ec46f2018-06-08 15:03:46 -07003181 if (active) {
3182 break;
3183 }
3184 if (startTimeMillis <= 0) {
3185 startTimeMillis = uptimeMillis();
3186 }
3187 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003188 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003189 if (remainingTimeMillis <= 0) {
3190 break;
3191 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003192 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
3193
3194 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003195 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003196 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003197 } while (true);
3198
Svet Ganov7b4ab782018-03-25 12:48:10 -07003199 if (active) {
3200 // Now that we found out the UID is actually active, cache that
3201 mActiveUids.insert(uid);
3202 }
3203 }
3204 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08003205}
3206
Varun Shahb42f1eb2019-04-16 14:45:13 -07003207int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
3208 Mutex::Autolock _l(mUidLock);
3209 return getProcStateLocked(uid);
3210}
3211
3212int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
3213 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
3214 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
3215 procState = mMonitoredUids[uid].first;
3216 }
3217 return procState;
3218}
3219
Svet Ganov7b4ab782018-03-25 12:48:10 -07003220void CameraService::UidPolicy::UidPolicy::addOverrideUid(uid_t uid,
3221 String16 callingPackage, bool active) {
3222 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08003223}
3224
Svet Ganov7b4ab782018-03-25 12:48:10 -07003225void CameraService::UidPolicy::removeOverrideUid(uid_t uid, String16 callingPackage) {
3226 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08003227}
3228
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003229void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
3230 Mutex::Autolock _l(mUidLock);
3231 ALOGV("UidPolicy: ActivityManager has died");
3232 mRegistered = false;
3233 mActiveUids.clear();
3234}
3235
Svet Ganov7b4ab782018-03-25 12:48:10 -07003236void CameraService::UidPolicy::updateOverrideUid(uid_t uid, String16 callingPackage,
3237 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003238 bool wasActive = false;
3239 bool isActive = false;
3240 {
3241 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003242 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003243 mOverrideUids.erase(uid);
3244 if (insert) {
3245 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
3246 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003247 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003248 }
3249 if (wasActive != isActive && !isActive) {
3250 sp<CameraService> service = mService.promote();
3251 if (service != nullptr) {
3252 service->blockClientsForUid(uid);
3253 }
3254 }
3255}
3256
3257// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08003258// SensorPrivacyPolicy
3259// ----------------------------------------------------------------------------
3260void CameraService::SensorPrivacyPolicy::registerSelf() {
3261 Mutex::Autolock _l(mSensorPrivacyLock);
3262 if (mRegistered) {
3263 return;
3264 }
Steven Moreland3cf67172020-01-29 11:44:22 -08003265 mSpm.addSensorPrivacyListener(this);
3266 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
3267 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003268 if (res == OK) {
3269 mRegistered = true;
3270 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
3271 }
3272}
3273
3274void CameraService::SensorPrivacyPolicy::unregisterSelf() {
3275 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08003276 mSpm.removeSensorPrivacyListener(this);
3277 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003278 mRegistered = false;
3279 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
3280}
3281
3282bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
3283 Mutex::Autolock _l(mSensorPrivacyLock);
3284 return mSensorPrivacyEnabled;
3285}
3286
3287binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
3288 {
3289 Mutex::Autolock _l(mSensorPrivacyLock);
3290 mSensorPrivacyEnabled = enabled;
3291 }
3292 // if sensor privacy is enabled then block all clients from accessing the camera
3293 if (enabled) {
3294 sp<CameraService> service = mService.promote();
3295 if (service != nullptr) {
3296 service->blockAllClients();
3297 }
3298 }
3299 return binder::Status::ok();
3300}
3301
3302void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
3303 Mutex::Autolock _l(mSensorPrivacyLock);
3304 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
3305 mRegistered = false;
3306}
3307
3308// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003309// CameraState
3310// ----------------------------------------------------------------------------
3311
3312CameraService::CameraState::CameraState(const String8& id, int cost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003313 const std::set<String8>& conflicting, SystemCameraKind systemCameraKind) : mId(id),
3314 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
3315 mSystemCameraKind(systemCameraKind) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08003316
3317CameraService::CameraState::~CameraState() {}
3318
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003319CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003320 Mutex::Autolock lock(mStatusLock);
3321 return mStatus;
3322}
3323
Shuzhen Wang43858162020-01-10 13:42:15 -08003324std::vector<String8> CameraService::CameraState::getUnavailablePhysicalIds() const {
3325 Mutex::Autolock lock(mStatusLock);
3326 std::vector<String8> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
3327 return res;
3328}
3329
Ruben Brunkcc776712015-02-17 20:18:47 -08003330CameraParameters CameraService::CameraState::getShimParams() const {
3331 return mShimParams;
3332}
3333
3334void CameraService::CameraState::setShimParams(const CameraParameters& params) {
3335 mShimParams = params;
3336}
3337
3338int CameraService::CameraState::getCost() const {
3339 return mCost;
3340}
3341
3342std::set<String8> CameraService::CameraState::getConflicting() const {
3343 return mConflicting;
3344}
3345
3346String8 CameraService::CameraState::getId() const {
3347 return mId;
3348}
3349
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003350SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
3351 return mSystemCameraKind;
3352}
3353
Shuzhen Wang43858162020-01-10 13:42:15 -08003354bool CameraService::CameraState::addUnavailablePhysicalId(const String8& physicalId) {
3355 Mutex::Autolock lock(mStatusLock);
3356 auto result = mUnavailablePhysicalIds.insert(physicalId);
3357 return result.second;
3358}
3359
3360bool CameraService::CameraState::removeUnavailablePhysicalId(const String8& physicalId) {
3361 Mutex::Autolock lock(mStatusLock);
3362 auto count = mUnavailablePhysicalIds.erase(physicalId);
3363 return count > 0;
3364}
3365
Ruben Brunkcc776712015-02-17 20:18:47 -08003366// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07003367// ClientEventListener
3368// ----------------------------------------------------------------------------
3369
3370void CameraService::ClientEventListener::onClientAdded(
3371 const resource_policy::ClientDescriptor<String8,
3372 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003373 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003374 if (basicClient.get() != nullptr) {
3375 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3376 notifier.noteStartCamera(descriptor.getKey(),
3377 static_cast<int>(basicClient->getClientUid()));
3378 }
3379}
3380
3381void CameraService::ClientEventListener::onClientRemoved(
3382 const resource_policy::ClientDescriptor<String8,
3383 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003384 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003385 if (basicClient.get() != nullptr) {
3386 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3387 notifier.noteStopCamera(descriptor.getKey(),
3388 static_cast<int>(basicClient->getClientUid()));
3389 }
3390}
3391
3392
3393// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003394// CameraClientManager
3395// ----------------------------------------------------------------------------
3396
Ruben Brunk99e69712015-05-26 17:25:07 -07003397CameraService::CameraClientManager::CameraClientManager() {
3398 setListener(std::make_shared<ClientEventListener>());
3399}
3400
Ruben Brunkcc776712015-02-17 20:18:47 -08003401CameraService::CameraClientManager::~CameraClientManager() {}
3402
3403sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
3404 const String8& id) const {
3405 auto descriptor = get(id);
3406 if (descriptor == nullptr) {
3407 return sp<BasicClient>{nullptr};
3408 }
3409 return descriptor->getValue();
3410}
3411
3412String8 CameraService::CameraClientManager::toString() const {
3413 auto all = getAll();
3414 String8 ret("[");
3415 bool hasAny = false;
3416 for (auto& i : all) {
3417 hasAny = true;
3418 String8 key = i->getKey();
3419 int32_t cost = i->getCost();
3420 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00003421 int32_t score = i->getPriority().getScore();
3422 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08003423 auto conflicting = i->getConflicting();
3424 auto clientSp = i->getValue();
3425 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07003426 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08003427 if (clientSp.get() != nullptr) {
3428 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07003429 uid_t clientUid = clientSp->getClientUid();
3430 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003431 }
Emilian Peev8131a262017-02-01 12:33:43 +00003432 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
3433 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08003434
Ruben Brunk6267b532015-04-30 17:44:07 -07003435 if (clientSp.get() != nullptr) {
3436 ret.appendFormat("User Id: %d, ", clientUserId);
3437 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003438 if (packageName.size() != 0) {
3439 ret.appendFormat("Client Package Name: %s", packageName.string());
3440 }
3441
3442 ret.append(", Conflicting Client Devices: {");
3443 for (auto& j : conflicting) {
3444 ret.appendFormat("%s, ", j.string());
3445 }
3446 ret.append("})");
3447 }
3448 if (hasAny) ret.append("\n");
3449 ret.append("]\n");
3450 return ret;
3451}
3452
3453CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3454 const String8& key, const sp<BasicClient>& value, int32_t cost,
Emilian Peev8131a262017-02-01 12:33:43 +00003455 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
3456 int32_t state) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003457
Steven Moreland89a2c5c2020-01-31 15:02:25 -08003458 bool isVendorClient = getCurrentServingCall() == BinderCallType::HWBINDER;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003459 int32_t score_adj = isVendorClient ? kVendorClientScore : score;
3460 int32_t state_adj = isVendorClient ? kVendorClientState: state;
3461
Ruben Brunkcc776712015-02-17 20:18:47 -08003462 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003463 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj, isVendorClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08003464}
3465
3466CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3467 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
3468 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00003469 partial->getConflicting(), partial->getPriority().getScore(),
3470 partial->getOwnerId(), partial->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08003471}
3472
3473// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07003474
3475static const int kDumpLockRetries = 50;
3476static const int kDumpLockSleep = 60000;
3477
3478static bool tryLock(Mutex& mutex)
3479{
3480 bool locked = false;
3481 for (int i = 0; i < kDumpLockRetries; ++i) {
3482 if (mutex.tryLock() == NO_ERROR) {
3483 locked = true;
3484 break;
3485 }
3486 usleep(kDumpLockSleep);
3487 }
3488 return locked;
3489}
3490
3491status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003492 ATRACE_CALL();
3493
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003494 if (checkCallingPermission(sDumpPermission) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003495 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07003496 CameraThreadState::getCallingPid(),
3497 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003498 return NO_ERROR;
3499 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003500 bool locked = tryLock(mServiceLock);
3501 // failed to lock - CameraService is probably deadlocked
3502 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003503 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003504 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003505
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003506 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003507 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07003508
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003509 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003510 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08003511
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003512 if (locked) mServiceLock.unlock();
3513 return NO_ERROR;
3514 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003515 dprintf(fd, "\n== Service global info: ==\n\n");
3516 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003517 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07003518 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
3519 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003520 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
3521 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
3522 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003523 String8 activeClientString = mActiveClientManager.toString();
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003524 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
3525 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003526
3527 dumpEventLog(fd);
3528
3529 bool stateLocked = tryLock(mCameraStatesLock);
3530 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003531 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003532 }
3533
Emilian Peevbd8c5032018-02-14 23:05:40 +00003534 int argSize = args.size();
3535 for (int i = 0; i < argSize; i++) {
3536 if (args[i] == TagMonitor::kMonitorOption) {
3537 if (i + 1 < argSize) {
3538 mMonitorTags = String8(args[i + 1]);
3539 }
3540 break;
3541 }
3542 }
3543
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003544 for (auto& state : mCameraStates) {
3545 String8 cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003546
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003547 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003548
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003549 CameraParameters p = state.second->getShimParams();
3550 if (!p.isEmpty()) {
3551 dprintf(fd, " Camera1 API shim is using parameters:\n ");
3552 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003553 }
3554
3555 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08003556 if (clientDescriptor != nullptr) {
3557 dprintf(fd, " Device %s is open. Client instance dump:\n",
3558 cameraId.string());
3559 dprintf(fd, " Client priority score: %d state: %d\n",
3560 clientDescriptor->getPriority().getScore(),
3561 clientDescriptor->getPriority().getState());
3562 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
3563
3564 auto client = clientDescriptor->getValue();
3565 dprintf(fd, " Client package: %s\n",
3566 String8(client->getPackageName()).string());
3567
3568 client->dumpClient(fd, args);
3569 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003570 dprintf(fd, " Device %s is closed, no client instance\n",
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003571 cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003572 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003573
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003574 }
3575
3576 if (stateLocked) mCameraStatesLock.unlock();
3577
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003578 if (locked) mServiceLock.unlock();
3579
Emilian Peevf53f66e2017-04-11 14:29:43 +01003580 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003581
3582 dprintf(fd, "\n== Vendor tags: ==\n\n");
3583
3584 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
3585 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00003586 sp<VendorTagDescriptorCache> cache =
3587 VendorTagDescriptorCache::getGlobalVendorTagCache();
3588 if (cache == NULL) {
3589 dprintf(fd, "No vendor tags.\n");
3590 } else {
3591 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
3592 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003593 } else {
3594 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
3595 }
3596
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003597 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003598 dprintf(fd, "\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003599 camera3::CameraTraces::dump(fd, args);
3600
3601 // Process dump arguments, if any
3602 int n = args.size();
3603 String16 verboseOption("-v");
3604 String16 unreachableOption("--unreachable");
3605 for (int i = 0; i < n; i++) {
3606 if (args[i] == verboseOption) {
3607 // change logging level
3608 if (i + 1 >= n) continue;
3609 String8 levelStr(args[i+1]);
3610 int level = atoi(levelStr.string());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003611 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003612 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003613 } else if (args[i] == unreachableOption) {
3614 // Dump memory analysis
3615 // TODO - should limit be an argument parameter?
3616 UnreachableMemoryInfo info;
3617 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
3618 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003619 dprintf(fd, "\n== Unable to dump unreachable memory. "
3620 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003621 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003622 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003623 std::string s = info.ToString(/*log_contents*/ true);
3624 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003625 }
3626 }
3627 }
3628 return NO_ERROR;
3629}
3630
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003631void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003632 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003633
3634 Mutex::Autolock l(mLogLock);
3635 for (const auto& msg : mEventLog) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003636 dprintf(fd, " %s\n", msg.string());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003637 }
3638
3639 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003640 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003641 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003642 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003643 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003644 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003645}
3646
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003647void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003648 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003649 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
3650 if (mTorchClientMap[i] == who) {
3651 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003652 String8 cameraId = mTorchClientMap.keyAt(i);
3653 status_t res = mFlashlight->setTorchMode(cameraId, false);
3654 if (res) {
3655 ALOGE("%s: torch client died but couldn't turn off torch: "
3656 "%s (%d)", __FUNCTION__, strerror(-res), res);
3657 return;
3658 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003659 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003660 break;
3661 }
3662 }
3663}
3664
Ruben Brunkcc776712015-02-17 20:18:47 -08003665/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003666
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003667 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07003668 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
3669 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003670 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003671 // PID here is approximate and can be wrong.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003672 logClientDied(CameraThreadState::getCallingPid(), String8("Binder died unexpectedly"));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003673
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003674 // check torch client
3675 handleTorchClientBinderDied(who);
3676
3677 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08003678 if(!evictClientIdByRemote(who)) {
3679 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003680 return;
3681 }
3682
Ruben Brunkcc776712015-02-17 20:18:47 -08003683 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
3684 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003685}
3686
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003687void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003688 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08003689}
3690
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003691void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
3692 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003693 // Do not lock mServiceLock here or can get into a deadlock from
3694 // connect() -> disconnect -> updateStatus
3695
3696 auto state = getCameraState(cameraId);
3697
3698 if (state == nullptr) {
3699 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
3700 cameraId.string());
3701 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07003702 }
3703
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003704 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
3705 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3706 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3707 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
3708 return;
3709 }
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003710 bool supportsHAL3 = false;
3711 // supportsCameraApi also holds mInterfaceMutex, we can't call it in the
3712 // HIDL onStatusChanged wrapper call (we'll hold mStatusListenerLock and
3713 // mInterfaceMutex together, which can lead to deadlocks)
3714 binder::Status sRet =
3715 supportsCameraApi(String16(cameraId), hardware::ICameraService::API_VERSION_2,
3716 &supportsHAL3);
3717 if (!sRet.isOk()) {
3718 ALOGW("%s: Failed to determine if device supports HAL3 %s, supportsCameraApi call failed",
3719 __FUNCTION__, cameraId.string());
3720 return;
3721 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003722 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08003723 // of the listeners with both the mStatusLock and mStatusListenerLock held
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003724 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind, &supportsHAL3]
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003725 (const String8& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003726
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003727 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003728 // Update torch status if it has a flash unit.
3729 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003730 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003731 if (getTorchStatusLocked(cameraId, &torchStatus) !=
3732 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003733 TorchModeStatus newTorchStatus =
3734 status == StatusInternal::PRESENT ?
3735 TorchModeStatus::AVAILABLE_OFF :
3736 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003737 if (torchStatus != newTorchStatus) {
3738 onTorchStatusChangedLocked(cameraId, newTorchStatus);
3739 }
3740 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003741 }
3742
3743 Mutex::Autolock lock(mStatusListenerLock);
3744
Shuzhen Wang43858162020-01-10 13:42:15 -08003745 notifyPhysicalCameraStatusLocked(mapToInterface(status), cameraId);
3746
Ruben Brunkcc776712015-02-17 20:18:47 -08003747 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003748 bool isVendorListener = listener->isVendorListener();
3749 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
3750 listener->getListenerPid(), listener->getListenerUid()) ||
3751 (isVendorListener && !supportsHAL3)) {
3752 ALOGV("Skipping discovery callback for system-only camera/HAL1 device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003753 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003754 continue;
3755 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003756 listener->getListener()->onStatusChanged(mapToInterface(status),
Emilian Peev53722fa2019-02-22 17:47:20 -08003757 String16(cameraId));
Ruben Brunkcc776712015-02-17 20:18:47 -08003758 }
3759 });
Igor Murashkincba2c162013-03-20 15:56:31 -07003760}
3761
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003762template<class Func>
3763void CameraService::CameraState::updateStatus(StatusInternal status,
3764 const String8& cameraId,
3765 std::initializer_list<StatusInternal> rejectSourceStates,
3766 Func onStatusUpdatedLocked) {
3767 Mutex::Autolock lock(mStatusLock);
3768 StatusInternal oldStatus = mStatus;
3769 mStatus = status;
3770
3771 if (oldStatus == status) {
3772 return;
3773 }
3774
3775 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
3776 cameraId.string(), oldStatus, status);
3777
3778 if (oldStatus == StatusInternal::NOT_PRESENT &&
3779 (status != StatusInternal::PRESENT &&
3780 status != StatusInternal::ENUMERATING)) {
3781
3782 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
3783 __FUNCTION__);
3784 mStatus = oldStatus;
3785 return;
3786 }
3787
3788 /**
3789 * Sometimes we want to conditionally do a transition.
3790 * For example if a client disconnects, we want to go to PRESENT
3791 * only if we weren't already in NOT_PRESENT or ENUMERATING.
3792 */
3793 for (auto& rejectStatus : rejectSourceStates) {
3794 if (oldStatus == rejectStatus) {
3795 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
3796 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
3797 mStatus = oldStatus;
3798 return;
3799 }
3800 }
3801
3802 onStatusUpdatedLocked(cameraId, status);
3803}
3804
Eino-Ville Talvalae8c96c72017-06-27 12:24:07 -07003805void CameraService::updateProxyDeviceState(int newState,
Emilian Peev573291c2018-02-10 02:10:56 +00003806 const String8& cameraId, int facing, const String16& clientName, int apiLevel) {
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07003807 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
3808 if (proxyBinder == nullptr) return;
3809 String16 id(cameraId);
Emilian Peev573291c2018-02-10 02:10:56 +00003810 proxyBinder->notifyCameraState(id, newState, facing, clientName, apiLevel);
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07003811}
3812
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003813status_t CameraService::getTorchStatusLocked(
3814 const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003815 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003816 if (!status) {
3817 return BAD_VALUE;
3818 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003819 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3820 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003821 // invalid camera ID or the camera doesn't have a flash unit
3822 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003823 }
3824
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003825 *status = mTorchStatusMap.valueAt(index);
3826 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003827}
3828
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003829status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003830 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003831 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3832 if (index == NAME_NOT_FOUND) {
3833 return BAD_VALUE;
3834 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003835 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003836
3837 return OK;
3838}
3839
Shuzhen Wang43858162020-01-10 13:42:15 -08003840void CameraService::notifyPhysicalCameraStatusLocked(int32_t status, const String8& cameraId) {
3841 Mutex::Autolock lock(mCameraStatesLock);
3842 for (const auto& state : mCameraStates) {
3843 std::vector<std::string> physicalCameraIds;
3844 if (!mCameraProviderManager->isLogicalCamera(state.first.c_str(), &physicalCameraIds)) {
3845 // This is not a logical multi-camera.
3846 continue;
3847 }
3848 if (std::find(physicalCameraIds.begin(), physicalCameraIds.end(), cameraId.c_str())
3849 == physicalCameraIds.end()) {
3850 // cameraId is not a physical camera of this logical multi-camera.
3851 continue;
3852 }
3853
3854 String16 id16(state.first), physicalId16(cameraId);
3855 for (auto& listener : mListenerList) {
3856 listener->getListener()->onPhysicalCameraStatusChanged(status,
3857 id16, physicalId16);
3858 }
3859 }
3860}
3861
Svet Ganova453d0d2018-01-11 15:37:58 -08003862void CameraService::blockClientsForUid(uid_t uid) {
3863 const auto clients = mActiveClientManager.getAll();
3864 for (auto& current : clients) {
3865 if (current != nullptr) {
3866 const auto basicClient = current->getValue();
3867 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
3868 basicClient->block();
3869 }
3870 }
3871 }
3872}
3873
Michael Grooverd1d435a2018-12-18 17:39:42 -08003874void CameraService::blockAllClients() {
3875 const auto clients = mActiveClientManager.getAll();
3876 for (auto& current : clients) {
3877 if (current != nullptr) {
3878 const auto basicClient = current->getValue();
3879 if (basicClient.get() != nullptr) {
3880 basicClient->block();
3881 }
3882 }
3883 }
3884}
3885
Svet Ganova453d0d2018-01-11 15:37:58 -08003886// NOTE: This is a remote API - make sure all args are validated
3887status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
3888 if (!checkCallingPermission(sManageCameraPermission, nullptr, nullptr)) {
3889 return PERMISSION_DENIED;
3890 }
3891 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
3892 return BAD_VALUE;
3893 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003894 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003895 return handleSetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07003896 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003897 return handleResetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07003898 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003899 return handleGetUidState(args, out, err);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003900 } else if (args.size() >= 2 && args[0] == String16("set-rotate-and-crop")) {
3901 return handleSetRotateAndCrop(args);
3902 } else if (args.size() >= 1 && args[0] == String16("get-rotate-and-crop")) {
3903 return handleGetRotateAndCrop(out);
Svet Ganova453d0d2018-01-11 15:37:58 -08003904 } else if (args.size() == 1 && args[0] == String16("help")) {
3905 printHelp(out);
3906 return NO_ERROR;
3907 }
3908 printHelp(err);
3909 return BAD_VALUE;
3910}
3911
3912status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07003913 String16 packageName = args[1];
3914
Svet Ganova453d0d2018-01-11 15:37:58 -08003915 bool active = false;
3916 if (args[2] == String16("active")) {
3917 active = true;
3918 } else if ((args[2] != String16("idle"))) {
3919 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
3920 return BAD_VALUE;
3921 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003922
3923 int userId = 0;
3924 if (args.size() >= 5 && args[3] == String16("--user")) {
3925 userId = atoi(String8(args[4]));
3926 }
3927
3928 uid_t uid;
3929 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
3930 return BAD_VALUE;
3931 }
3932
3933 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08003934 return NO_ERROR;
3935}
3936
3937status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07003938 String16 packageName = args[1];
3939
3940 int userId = 0;
3941 if (args.size() >= 4 && args[2] == String16("--user")) {
3942 userId = atoi(String8(args[3]));
3943 }
3944
3945 uid_t uid;
3946 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003947 return BAD_VALUE;
3948 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003949
3950 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08003951 return NO_ERROR;
3952}
3953
3954status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07003955 String16 packageName = args[1];
3956
3957 int userId = 0;
3958 if (args.size() >= 4 && args[2] == String16("--user")) {
3959 userId = atoi(String8(args[3]));
3960 }
3961
3962 uid_t uid;
3963 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003964 return BAD_VALUE;
3965 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003966
3967 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003968 return dprintf(out, "active\n");
3969 } else {
3970 return dprintf(out, "idle\n");
3971 }
3972}
3973
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003974status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
3975 int rotateValue = atoi(String8(args[1]));
3976 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
3977 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
3978 Mutex::Autolock lock(mServiceLock);
3979
3980 mOverrideRotateAndCropMode = rotateValue;
3981
3982 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
3983
3984 const auto clients = mActiveClientManager.getAll();
3985 for (auto& current : clients) {
3986 if (current != nullptr) {
3987 const auto basicClient = current->getValue();
3988 if (basicClient.get() != nullptr) {
3989 basicClient->setRotateAndCropOverride(rotateValue);
3990 }
3991 }
3992 }
3993
3994 return OK;
3995}
3996
3997status_t CameraService::handleGetRotateAndCrop(int out) {
3998 Mutex::Autolock lock(mServiceLock);
3999
4000 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
4001}
4002
Svet Ganova453d0d2018-01-11 15:37:58 -08004003status_t CameraService::printHelp(int out) {
4004 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07004005 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
4006 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
4007 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004008 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
4009 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
4010 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08004011 " help print this message\n");
4012}
4013
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004014int32_t CameraService::updateAudioRestriction() {
4015 Mutex::Autolock lock(mServiceLock);
4016 return updateAudioRestrictionLocked();
4017}
4018
4019int32_t CameraService::updateAudioRestrictionLocked() {
4020 int32_t mode = 0;
4021 // iterate through all active client
4022 for (const auto& i : mActiveClientManager.getAll()) {
4023 const auto clientSp = i->getValue();
4024 mode |= clientSp->getAudioRestriction();
4025 }
4026
4027 bool modeChanged = (mAudioRestriction != mode);
4028 mAudioRestriction = mode;
4029 if (modeChanged) {
4030 mAppOps.setCameraAudioRestriction(mode);
4031 }
4032 return mode;
4033}
4034
Mathias Agopian65ab4712010-07-14 17:59:35 -07004035}; // namespace android